如何为布尔值添加 JPanel 按钮



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

我该怎么做?

在这里,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();
    }
}

最新更新