首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

JTextField setText 有关问题

2012-03-03 
JTextFieldsetText 问题下面是我的代码,要在点击按钮在文本中显示按钮名称public class text{private JFra

JTextField setText 问题
下面是我的代码,要在点击按钮在文本中显示按钮名称
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());        }    }} 

热点排行