问题
I use JToolbarButton button, I want to make it be "pressed" when I click on it, just like JButton works.How can I do this? Please help!Thanks.
回答1:
As mentioned in Costis' reply, you are probably after a JToggleButton. It might also be necessary to suppress the painting of the border, as in the 2nd tool bar in this example.
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class ToggleBar {
public static JToggleButton getButton(
Image selected,
Image unselected,
boolean decorated) {
JToggleButton b = new JToggleButton();
b.setSelectedIcon(new ImageIcon(selected));
b.setIcon(new ImageIcon(unselected));
b.setBorderPainted(decorated);
return b;
}
public static Image getCircleImage(Color c) {
BufferedImage bi = new BufferedImage(
32,32,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.setColor(c);
g.fillOval(0,0,32,32);
g.dispose();
return bi;
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
Image red = getCircleImage(Color.RED);
Image green = getCircleImage(Color.GREEN);
JPanel p = new JPanel(new GridLayout(0,1));
JToolBar tb1 = new JToolBar();
for (int ii=0; ii<5; ii++) {
tb1.add( getButton(red, green, true) );
}
p.add(tb1);
JToolBar tb2 = new JToolBar();
for (int ii=0; ii<5; ii++) {
tb2.add( getButton(red, green, false) );
}
p.add(tb2);
JOptionPane.showMessageDialog(null, p);
}
});
}
}
回答2:
There is a JToolbarButton in Apache Batik.
It seems to me though that what you are looking for is a JToggleButton. You can adjust it to display a small image and to be small.
jToggleButton1.setIcon(new javax.swing.ImageIcon("image.png"));
jToggleButton1.setSelectedIcon(new javax.swing.ImageIcon("selected_image.png"));
Add another image with setSelectedIcon in order to make you button look pressed.
来源:https://stackoverflow.com/questions/7359906/swing-jtoolbarbutton-pressing