【问题标题】:Setting button to be visible设置按钮可见
【发布时间】:2012-01-20 07:04:30
【问题描述】:

我试图在 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);

    }
}

【问题讨论】:

  • 如果你想成为一名成功的程序员,你需要了解一些基础知识,包括变量作用域。
  • 这是你的第一个 java 程序吗?

标签: java swing scope visibility jbutton


【解决方案1】:

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

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

    }
}

【讨论】:

猜你喜欢
  • 2011-09-02
  • 2019-11-04
  • 2015-08-17
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 2019-12-09
相关资源
最近更新 更多