2015-05-29 39 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);