Re: Changing JButton icon when pressed
jill.mcafee@vanderbilt.edu wrote:
Knute - Thank you so much for your response and advice. I altered the
the ActionListener to call the setIcon() method, as follows:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Center")) {
zoomlevel = defaultzoomlevel;
}
else if (e.getActionCommand().equals("ZoomIn")) {
if (zoomlevel > 1) {
zoomlevel = zoomlevel - 1;
}
ZoomInButton.setIcon(ZoomInSel);
}
else if (e.getActionCommand().equals("ZoomOut")) {
if (zoomlevel < 5) {
zoomlevel = zoomlevel + 1;
}
}
zoom.repaint();
}
At this point, I am just trying to get the button to change, and stay
changed, when I click it. The button will stay the "selected" color
until I move the mouse off the button, and then it changes back to the
unselected color. Any ideas?
Jill
Jill:
I can't really tell what you are doing without the actual code or a
simplified example. If your buttons are responding to mouse events
though it must be happening in a mouse listener not the action listener.
You shouldn't need to call repaint() in the action listener to change
icons or colors. Below is a simplified example of how to highlight the
last button pressed. You should be able to modify this to work with
icons without much trouble.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test4 {
static JButton b0,b1,b2;
public static void createGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String ac = ae.getActionCommand();
if (ac.equals("0")) {
b0.setBackground(Color.BLUE);
b1.setBackground(Color.WHITE);
b2.setBackground(Color.WHITE);
} else if (ac.equals("1")) {
b0.setBackground(Color.WHITE);
b1.setBackground(Color.BLUE);
b2.setBackground(Color.WHITE);
} else if (ac.equals("2")) {
b0.setBackground(Color.WHITE);
b1.setBackground(Color.WHITE);
b2.setBackground(Color.BLUE);
}
}
};
b0 = new JButton("0");
b0.addActionListener(al);
f.add(b0,BorderLayout.NORTH);
b1 = new JButton("1");
b1.addActionListener(al);
f.add(b1,BorderLayout.CENTER);
b2 = new JButton("2");
b2.addActionListener(al);
f.add(b2,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
createGUI();
}
};
EventQueue.invokeLater(r);
}
}
--
Knute Johnson
email s/nospam/knute/