2013-05-06 52 views
0

我在这里要做的是每次按下按钮并选择一个图像时,标签的文本都会变为该图像的路径。更改在ActionListener后声明的标签文本

这里是我的代码:

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所以我不能更改文本。

+0

您需要在**之前创建一个标签**,您可以更改它。 – 2013-05-06 18:04:46

+3

停止使用'setBounds'并开始使用布局管理器 – Reimeus 2013-05-06 18:06:17

回答

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

我没有访问变量lblNewLabel所以我不能更改文本。

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

+0

谢谢所有特别的camickr。 我所要做的只是: final JLabel lblNewLabel = new JLabel(“New label”); – 2013-05-06 22:16:53