各位大侠,
对按钮添加事件监听后,点击按钮想将文本框中的“123”改为“456”,可为什么没有变化呢?代码如下:
package test2;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ClickAdd extends JFrame
{
private JPanel panel;
private JButton button;
private JTextField field;
public static void main(String[] args)
{
ClickAdd frame = new ClickAdd();
frame.setVisible(true);
}
public ClickAdd()
{
init();
addActionListener();
}
private void addActionListener()
{
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
change();
}
});
}
private void init()
{
panel = new JPanel();
button = new JButton("添加");
String string = "123";
field = new JTextField(string);
panel.add(field);
panel.add(button);
this.setSize(100, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(panel);
}
private void change()
{
String string = "456";
field = new JTextField(string);
}
}
而如果把change()中的field = new JTextField(string)改成field.setText(string)就可以了呢?