java - 设置按钮可见

标签 java swing scope visibility jbutton

我试图在单击单选按钮后将按钮设置为在 void 方法中“重新选择”可见,但该按钮的变量不能在 actionPerformed 方法中使用?

public class SelectionForm extends WindowAdapter implements  ActionListener {

    void select() {

        JFrame frame = new JFrame("Selection Form");

        JPanel leftPanel = new JPanel();
        // JPanel has BoxLayout in x-direction
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.X_AXIS));
        JRadioButton rd1 = new JRadioButton("Laptop");
        JRadioButton rd2 = new JRadioButton("Desktop");
        //submit button
        JButton reselect = new JButton(" Re-select ");
        reselect.setVisible(false);

        // adding radio buttons in the JPanel
        leftPanel.add(rd1);
        leftPanel.add(rd2);
        leftPanel.add(reselect);

        rd1.addActionListener(this);
        rd2.addActionListener(this);
        //reselect button
        reselect.addActionListener(this);

        // add JLabels in the frame
        frame.getContentPane().add(leftPanel);

        frame.setSize(300, 200);
        //frame.pack();
        frame.setVisible(true);
    }


    public void actionPerformed(ActionEvent e) {
        System.out.println("Selected: " + e.getActionCommand());

        if(e.getActionCommand().equals("Laptop") || 
            (e.getActionCommand().equals("Desktop"))){

            //OnlineShop oS = new OnlineShop();
            // oS.onlineShop();

            reselect.setVisible(true);
        }
    }

}

class MyWindowListener extends WindowAdapter {

    public void windowClosing(WindowEvent e) {
        System.out.println("Closing window!");
        System.exit(0);

    }
}

最佳答案

将按钮的变量放在方法之外。像这样:

public class SelectionForm extends WindowAdapter implements  ActionListener 
{
    private JButton reselect;
    void select() {

        ...
        //submit button
        reselect = new JButton(" Re-select ");
        reselect.setVisible(false);


        ....
    }


    public void actionPerformed(ActionEvent e) {
        System.out.println("Selected: " + e.getActionCommand());

        if(e.getActionCommand().equals("Laptop") || (e.getActionCommand().equals("Desktop"))){

            //OnlineShop oS = new OnlineShop();
            // oS.onlineShop();

            reselect.setVisible(true);
        }
    }

}

class MyWindowListener extends WindowAdapter {

    public void windowClosing(WindowEvent e) {
        System.out.println("Closing window!");
        System.exit(0);

    }
}

关于java - 设置按钮可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8505620/

相关文章:

c# - C#检查表达式的动态 "Scoping"

javascript - 访问类中的构造函数属性

Java - 从 url 读取页面源返回未知字符

java - 使用从数据库事件返回的 RowId 更新数据库中的另一个表

java - jframe 执行的操作 jframe

java - 使用 MySQL 数据库创建 jar 到 exe

Python 回调变量作用域

Java 连接到 Cassandra NoHostAvailableException

java - 如何在tomcat上处理2000+个请求/秒?

java - 将行添加到数据模型时出现 ArrayIndexOutOfBoundsException