2015-05-29 81 views
0

獲得價值,我想點擊一個按鈕,並有一個彈出窗口,在這裏我可以輸入一個字符串,該字符串將在標籤輸出,但我不能設法返回字符串。的Java Swing,從ActionListener的

JButton btnName = new JButton("Name"); 
    btnName.addActionListener(new ActionListener() { 
     String name; 
     public void actionPerformed(ActionEvent e) { 
      name = JOptionPane.showInputDialog("enter your name"); 
     } 
    }); 
    btnName.setBounds(10, 11, 89, 23); 
    frame.getContentPane().add(btnName); 
    JLabel lblPerson = new JLabel(name); 
    lblPerson.setFont(new Font("Tahoma", Font.PLAIN, 36)); 
    lblPerson.setBounds(10, 188, 414, 63); 
    frame.getContentPane().add(lblPerson);` 

我不知道如何從ActionListener的類返回字符串名稱,所以我顯然有在行錯誤10.

+0

Java的圖形用戶界面在不同的地區使用不同的PLAFs在不同的操作系統」,屏幕大小,屏幕分辨率等工作。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –

回答

2

只需使用JLabel.setText

public void actionPerformed(ActionEvent e) { 
     name = JOptionPane.showInputDialog("enter your name"); 
     lblPerson.setText(name); 
    } 

另一種方式你可以做到這一點是通過在你的類中創建(抽象)Action內部類,你使用JButton.setAction(MyAction);