【问题标题】:Change a label text that it's declared after my ActionListener更改在我的 ActionListener 之后声明的标签文本
【发布时间】:2013-04-30 13:07:21
【问题描述】:

我在这里尝试做的是,每次我按下按钮并选择图像时 标签的文本更改为该图像的路径。

这是我的代码:

public Frame() {
    setAlwaysOnTop(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 640, 480);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnNewButton = new JButton("Select image");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) 
        {
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Image", "jpg", "jpeg");
            final JFileChooser fc = new JFileChooser();
            filec.setAcceptAllFileFilterUsed(false);
            filec.addChoosableFileFilter(filter);
            filecc.showDialog(Frame.this, "Select an image");
            File pathh = fc.getSelectedFile();
            String pathhs;
            pathhs = pathh.getPath();
            System.out.println("The path is: " + pathhs);   
            lblNewLabel.setText(pathhs) <--the problem 

        }
    });
    btnNewButton.setBounds(25, 408, 165, 23);
    contentPane.add(btnNewButton);


    JLabel lblNewLabel = new JLabel("New label");
    lblNewLabel.setForeground(Color.BLACK);
    lblNewLabel.setBackground(Color.BLUE);
    lblNewLabel.setBounds(10, 68, 266, 234);
    contentPane.add(lblNewLabel);       
}

问题出在这里:

                String pathhs;
                pathhs = pathh.getPath();
                System.out.println("The path is: " + pathhs);   
                lblNewLabel.setText(pathhs) <--the problem 

我无权访问变量lblNewLabel,因此无法更改文本。

【问题讨论】:

  • 你需要创建一个标签之前你可以改变它。
  • 停止使用setBounds,开始使用布局管理器

标签: java swing awt label actionlistener


【解决方案1】:

您可以从匿名类引用局部变量,只要它们在定义匿名类之前已使用final 修饰符声明即可。

所以,我会将您的代码修改为:

JButton btnNewButton = new JButton("Select image");
btnNewButton.setBounds(25, 408, 165, 23);
contentPane.add(btnNewButton);


final JLabel lblNewLabel = new JLabel("New label");
btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) 
    {
        // Your actionPerformed implementation...
    }
});

lblNewLabel.setForeground(Color.BLACK);
lblNewLabel.setBackground(Color.BLUE);
lblNewLabel.setBounds(10, 68, 266, 234);
contentPane.add(lblNewLabel);       

【讨论】:

    【解决方案2】:

    我无权访问变量 lblNewLabel,因此我无法更改文本。

    将标签定义为类变量而不是局部变量,则匿名内部类可以访问该变量。

    【讨论】:

    • 特别感谢大家camickr。我所要做的就是:final JLabel lblNewLabel = new JLabel("New label");
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多