Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

jbutton - Swing JToolbarButton pressing

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Toggle Bar

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);
            }
        });
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...