下面是我的代码,要在点击按钮在文本中显示按钮名称
public class text
{
private JFrame frame;
private JTextField textField;
private JButton button;
public void go()
{
frame = new JFrame();
textField = new JTextField();
button = new JButton("button");
frame.add(textField, BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
button.addActionListener(new ButtonListener());
frame.pack();
frame.setVisible(true);
}
public void setText(String str){
textField.setText(str);
}
public static void main(String[] args)
{
text t = new text();
t.go();
}
}
class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e)
{
text t = new text();
t.setText(e.getActionCommand());
}
}
------解决方案--------------------
- Java code
import java.awt.BorderLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JTextField;import javax.swing.JButton;public class Text{ private JFrame frame; private JTextField textField; private JButton button; public void go() { frame = new JFrame(); textField = new JTextField(); button = new JButton("button"); frame.add(textField, BorderLayout.NORTH); frame.add(button, BorderLayout.CENTER); button.addActionListener(new ButtonListener()); frame.pack(); frame.setVisible(true); } public void setText(String str){ textField.setText(str); } public static void main(String[] args) { Text t = new Text(); t.go(); } private class ButtonListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { setText(e.getActionCommand()); } }}