Jlabel change color on mouse click Java - java

I am adding multiple Jlabel using for loop. What I want is on mouse click, the color of the selected JLabel should change and set to the default color on click of anotherJLabel.

Since you changed the state of the label, you need someway to change it back. The simplest solution is to maintain a reference to the last label that was changed and when the new label is clicked, reset it's state
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
HighlightMouseListener hml = new HighlightMouseListener();
for (int index = 0; index < 10; index++) {
JLabel label = new JLabel("Hello " + index);
label.addMouseListener(hml);
add(label, gbc);
}
}
}
public class HighlightMouseListener extends MouseAdapter {
private JLabel previous;
#Override
public void mouseClicked(MouseEvent e) {
Component source = e.getComponent();
if (!(source instanceof JLabel)) {
return;
}
JLabel label = (JLabel) source;
if (previous != null) {
previous.setBackground(null);
previous.setForeground(null);
previous.setOpaque(false);
}
previous = label;
label.setForeground(Color.WHITE);
label.setBackground(Color.BLUE);
label.setOpaque(true);
}
}
}
I still wonder if a JList would be a better and simpler solution, but since I don't know what you're doing, it's all I can do

Related

How do I set the size of my program's window? It seems to automatically be small. I'm using a lot of different 'containers' I guess

With all the different 'containers' I'm using, it's hard to set my window size in the code. I guess I need them but at the same time need to find a way to change settings around it.
I've tried doing frame.setSize(int x, int y), did not work.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TweetProgram1{
public static void main(String[] args) {
new TweetProgram1();
}
public TweetProgram1() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Tweet Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TweetProgram1Pane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TweetProgram1Pane extends JPanel {
public TweetProgram1Pane() {
setLayout(new GridBagLayout());
JLabel lbl = new JLabel("Random tweet");
JButton btn = new JButton("Send it");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 300;
gbc.gridheight = 300;
add(lbl, gbc);
add(btn, gbc);
}
}
}
I expect to be able to re-scale the window size (in the code) to whatever I need it to be.
Thanks

How to set caret position at the end of JFormattedTextField when it is clicked/focused?

I have frame with JFormattedTextField(s). My simplified code can look like:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100,100);
frame.setLayout(new GridLayout(2,2));
JFormattedTextField field1 = new JFormattedTextField(NumberFormat.getInstance());
field1.setValue(0.4);
frame.add(new JLabel("value A"));
frame.add(field1);
JFormattedTextField field2 = new JFormattedTextField(NumberFormat.getInstance());
field2.setValue(0.8);
frame.add(new JLabel("value B"));
frame.add(field2);
frame.setVisible(true);
which generates:
Goal
When I click/focus on any of JFormattedTextField I would like it to automatically place caret at the end
Problem
I tried using following solutions before calling frame.setVisible(true); but none of them seems to work
from How to set AUTO-SCROLLING of JTextArea in Java GUI?
field1.setCaretPosition(field1.getDocument().getLength());
from https://tips4java.wordpress.com/2008/10/22/text-area-scrolling/ ((DefaultCaret)field2.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
Works without issue for me....
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JTextField textField = new JTextField("This is a test");
add(textField, gbc);
JButton button = new JButton("This is a button");
add(button, gbc);
button.setFocusable(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textField.getCaretPosition() != 0) {
textField.setCaretPosition(0);
} else {
textField.setCaretPosition(textField.getText().length());
}
textField.requestFocusInWindow();
}
});
}
}
}
Provide a runnable example which doesn't work if you still have issues
Update with JFormattedTextField....
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JFormattedTextField textField = new JFormattedTextField("This is a test");
textField.setValue(0.8d);
add(textField, gbc);
JButton button = new JButton("This is a button");
add(button, gbc);
button.setFocusable(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textField.getCaretPosition() != 0) {
textField.setCaretPosition(0);
} else {
textField.setCaretPosition(textField.getText().length());
}
textField.requestFocusInWindow();
}
});
}
}
}
Updated with "set at beginning"
Okay, I just want to point out that I have personally dislike of JFormattedTextField, it does a lot of "things" at times which don't always make sense.
An "old" trick I've used, when implementing a "auto select all on focus gain", is to offload the request to the end of the Event Dispatching Thread, this places the request AFTER all the "funky stuff" that the JFormattedTextField does when the field becomes focused...
JFormattedTextField textField = new JFormattedTextField("This is a test");
textField.setValue(0.8d);
add(textField, gbc);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
textField.setCaretPosition(textField.getText().length());
}
});
}
});
Yes, I'm serious ...

Reset radio buttons in Java

I have three radio buttons in one button group. I want, on JButton click, for the radio buttons to be reset so they're unfilled. I've tried the logical suggestions that come up with you type .set and all of the booleans didn't do what I wanted it to do. So if you have suggestions that would be greatly appreciated. Thanks!
Simply use ButtonGroup#clearSelection
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JRadioButton[] buttons;
private ButtonGroup buttonGroup;
public TestPane() {
buttons = new JRadioButton[] {
new JRadioButton("Nuclear"),
new JRadioButton("Gas"),
new JRadioButton("Stream"),
new JRadioButton("Peddle"),
new JRadioButton("Electric")
};
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
buttonGroup = new ButtonGroup();
for (JRadioButton btn : buttons) {
add(btn, gbc);
buttonGroup.add(btn);
}
JButton clear = new JButton("Clear");
add(clear, gbc);
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonGroup.clearSelection();
}
});
}
}
}

Change image in JLabel based on which button the cursor is hovering over?

I have created a Swing interface where I want an icon to appear in a JLabel when the cursor is hovered over a button. The icon will change based in which button the cursor hovers over.
Here is the coding I am using at the moment:
public void iconchange()
{
if(btnPlay.isRolloverEnabled() == true)
{
lblIcon.setIcon(new ImageIcon("Images/Play-icon.png"));
}
}
I know the coding above is wrong, so what can I do to achieve the feature I mentioned above?
Use a ChangeListener on the JButton's ButtonModel to monitor changes to the models state, update your UI based on the state of the model, for example...
public class ChangeHandler implements ChangeListener {
private JLabel label;
private Icon armedIcon;
public ChangeHandler(JLabel label, Icon armedIcon) {
this.armedIcon = armedIcon;
this.label = label;
}
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isRollover()) {
label.setIcon(armedIcon);
} else {
label.setIcon(null);
}
}
}
This will update the supplied JLabel, changing it's icon to the specified icon when the ButtonModel it's attached to is in the rollOver state
This could be used something like this...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ButtonModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class RollOver {
public static void main(String[] args) {
new RollOver();
}
public RollOver() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel label;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
// I'm doing this, because I don't have blank icon of 128x128 and my
// icons are both 128x128
label = new JLabel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(128, 128);
}
};
add(label, gbc);
try {
JButton btn = new JButton("Bunnies");
btn.getModel().addChangeListener(new ChangeHandler(label, new ImageIcon(ImageIO.read(getClass().getResource("/Bunny.png")))));
add(btn);
btn = new JButton("Zomnies");
btn.getModel().addChangeListener(new ChangeHandler(label, new ImageIcon(ImageIO.read(getClass().getResource("/Zombi.png")))));
add(btn);
} catch (IOException exp) {
exp.printStackTrace();
}
}
public class ChangeHandler implements ChangeListener {
private JLabel label;
private Icon armedIcon;
public ChangeHandler(JLabel label, Icon armedIcon) {
this.armedIcon = armedIcon;
this.label = label;
}
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isRollover()) {
label.setIcon(armedIcon);
} else {
label.setIcon(null);
}
}
}
}
}
Take a closer look at How to Use Buttons, Check Boxes, and Radio Buttons for more details
Add an MouseListener to btnPlay, and use the mouse exit and enter methods
btnPlay.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
lblIcon.setIcon(new ImageIcon("Images/Play-icon.png"));
}
public void mouseExited(java.awt.event.MouseEvent evt) {
//I assume you want to remove or change the icon afterward
}
});

Is it possible to use a JSlider controlling multiple JTextfield?

I tried to use a JSlider to set text in three JTextFields.
My condition is the slider should work for textfield_1, only when a textfield_1 get its focus, similarly for the other two textfields.
When I tried to use the same slider with other textfield, only the first text field values getting changed.
Expecting valuable suggestions Thanks in Advance.
JSlider slider;
JTextField tf;
tf.addFocusListener(new FoucusListener(){
public void foucusGained(FocusEvent fe){
slider.addChangeListener(new ChangeListener()){
public void stateChanged(ChangeEvent ce){
JSlider slider =(JSlider)ce.getSource();
if(slider.getValueisAdjusting())
tf.setText(String.valueOf(slider.getValue()))
}
});
});
The basic idea is you need to know what field was last selected. The problem is, when you select the slider, it will fire a focus gained event...
The simplest idea would be to use a FocusListener registered only to the text fields and maintain a reference to the last field selected.
When the slider changes, you would simply interact with the last selected field (if it's not null)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderControl {
public static void main(String[] args) {
new SliderControl();
}
public SliderControl() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JSlider slider;
private JTextField[] fields;
private JTextField selectedField;
public TestPane() {
setLayout(new GridBagLayout());
fields = new JTextField[3];
FocusHandler focusHandler = new FocusHandler();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < 3; index++) {
fields[index] = new JTextField(3);
fields[index].addFocusListener(focusHandler);
add(fields[index], gbc);
gbc.gridy++;
}
gbc.fill = GridBagConstraints.HORIZONTAL;
slider = new JSlider();
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (selectedField != null) {
selectedField.setText(String.valueOf(slider.getValue()));
}
}
});
add(slider, gbc);
}
protected class FocusHandler extends FocusAdapter {
#Override
public void focusGained(FocusEvent e) {
if (e.getComponent() instanceof JTextField) {
selectedField = (JTextField) e.getComponent();
}
}
}
}
}

Categories

Resources