0

我正在尝试编写一个包含我想要更改、添加、删除等元素(特别是 JLabels 和 JButton)的 GUI。但是,Java 告诉我这些对象的所有修饰符都是无效的(final 除外),这意味着我不能在定义它们的位置之外引用这些对象。我的问题是,我该如何设置,以便以后可以操作这些元素?

如果相关,我的 GUI 是一个 JFrame,其中包含一个菜单栏、一个画布和一个面板(其中包含我想要操作的元素)。

提前感谢您的任何帮助。

4

1 回答 1

1

Java is telling me that all modifiers for these objects are invalid

From this description it would appear that you are creating components locally that need to be accessed elsewhere, for instance in an ActionListener class.

I would suggest not to create any components that that belong to the JFrame or GUI container or in a local scope e.g. main method, that may need to be accessed later. The simple example below shows how the component label1 can be accessed easily by inner class ButtonAction:

public class SwingExample extends JFrame {
    private JButton button1;
    private JLabel label1;

    public SwingExample() {
        super("SwingExample");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        button1 = new JButton("Test");
        button1.addActionListener(new ButtonAction());
        label1 = new JLabel("Swing Example", JLabel.CENTER);
        add(label1, BorderLayout.CENTER);
        add(button1, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        // don't create any locally scoped components here
        new SwingExample().setVisible(true);
    }

    class ButtonAction extends AbstractAction  {

        @Override
        public void actionPerformed(ActionEvent e) {
            label1.setText("label1 Accessed through global variable");
        }
    }
}
于 2012-10-24T16:15:30.013 回答