【问题标题】:How to add a JPanel button for boolean values?如何为布尔值添加 JPanel 按钮?
【发布时间】:2015-02-15 15:19:07
【问题描述】:

我是摇摆新手, 我有一个方法以真或假(布尔)格式返回值。 我需要使用 JPanel 显示一个标志,它显示真值或假值。

我该怎么做?

【问题讨论】:

  • “我该怎么做?” 通过添加一些代码。为了尽快获得更好的帮助,请发布MCVE(最小完整可验证示例)或SSCCE(简短、独立、正确的示例)。
  • 顺便说一句 - JCheckBox 是显示真/假值的好组件。或者,根据要求,JToggleButtonJRadioButton 或启用/禁用JButton..
  • 您也可以通过更改任何Component 的颜色来做到这一点,例如绿色/红色与真/假
  • @Sarz 是的,那太好了。有这方面的样本吗?

标签: java swing jpanel awt


【解决方案1】:

在这里,JFrame 设置为 BorderLayout,您可以将其称为底部的功能区,因为用户界面显示为绿色/红色。

public class SampleClass extends JFrame{
    JPanel centerPanel;
    JPanel topPanel;
    JButton btn;
    boolean check=true;

    SampleClass(){
        centerPanel = new JPanel();
        topPanel = new JPanel();
        btn=new JButton("Check");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        setSize(200,200);
        setLocationRelativeTo(null);
    }
    void add(){
        btn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                if(check){
                    topPanel.setBackground(Color.GREEN);
                    repaint();
                    check=false;
                }else{
                    topPanel.setBackground(Color.RED);
                    repaint();
                    check=true;
                }
            }
        });
        centerPanel.add(btn);
        add(topPanel,BorderLayout.SOUTH);
        add(centerPanel,BorderLayout.CENTER);
    }
    void setShow(){
        setVisible(true);
    }
    public static void main(String[]args){
        SampleClass sc=new SampleClass();
        sc.add();
        sc.setShow();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-26
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多