简体   繁体   English

如何在jButton的右侧添加复选框?

[英]How to add checkbox to the right side of jButton?

I want to create a button with checkbox in the right side of it. 我想创建一个带有复选框的按钮。 i tried this but checkbox stays on the center of button on the top of button label text. 我尝试过此操作,但复选框位于按钮标签文本顶部的按钮中心。

Any ideas welkom. 任何想法。

thanks in advance: 提前致谢:

public class MainTest extends JPanel {
    JButton button;
    JPanel panel;
    public MainTest() {
        createComponents();
        layoutComponents();
    }

    public void createComponents() {
        // attempting to add checkbox to button
        button = new JButton("Print with Edge");
        JCheckBox checkBox = new JCheckBox();
        jcb.setHorizontalAlignment(SwingConstants.RIGHT);
        button.add(checkBox,new BorderLayout());
        panel = new JPanel(new BorderLayout());
    }

    public void layoutComponents() {
        panel.add(button,BorderLayout.SOUTH);
        add(panel);
    }

    public static void main(String[] args) {
        MainTest demo = new MainTest();
        JFrame frame = new JFrame();
        Container cp = frame.getContentPane();
        cp.add(demo);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setLocation(500, 500);
        frame.setVisible(true);
    }
} 

You can wrap a JCheckBox inside a JPanel and make the JPanel look like a button. 您可以在JPanel中包装JCheckBox并使JPanel看起来像一个按钮。 For example: 例如:

在此处输入图片说明

public class Test {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(new Dimension(100, 100));

    JCheckBox button = new JCheckBox();

    final JPanel buttonWrapper = new JPanel();
    buttonWrapper.add(new JLabel("Button Text"));
    buttonWrapper.add(button);
    buttonWrapper.setBorder(BorderFactory.createRaisedBevelBorder());
    buttonWrapper.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent me) {
            buttonWrapper.setBorder(BorderFactory.createEtchedBorder());
        }



        @Override
        public void mouseReleased(MouseEvent me) {
            buttonWrapper.setBorder(BorderFactory.createRaisedBevelBorder());
        }



        @Override
        public void mouseClicked(MouseEvent me) {
            System.out.println("mouse clicked");
        }
    });

    JPanel mainPanel = new JPanel();
    mainPanel.add(buttonWrapper);

    frame.getContentPane().add(mainPanel);
    frame.setVisible(true);
}

} }

I want to create a button with checkbox in the right side of it. 我想创建一个带有复选框的按钮。

Maybe you just want the checkbox on the right side of the text? 也许您只想要文本右侧的复选框?

If so you can do: 如果是这样,您可以执行以下操作:

JCheckBox cb = new JCheckBox("Print with Edge");
cb.setHorizontalTextPosition(SwingConstants.LEADING);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM