public void actionPerformed(ActionEvent e)
{
if (e.getSource().equals(end))
{
System.exit(0);
}
if (e.getSource().equals(time))
{
ta.append(""+new Date());
}
}我想在按下time按钮的时候,在我的TextArea(也就是那个ta)中输出一串字符,我用上面那种方法,没有输出,不知道是什么原因造成的。
{
if (e.getSource().equals(end))
{
System.exit(0);
}
if (e.getSource().equals(time))
{
ta.append(""+new Date());
}
}我想在按下time按钮的时候,在我的TextArea(也就是那个ta)中输出一串字符,我用上面那种方法,没有输出,不知道是什么原因造成的。
ta.addActionListener(this)
if (e.getSource() == time)
{
ta.append(""+new Date());
}
e.getSource()得到的是你点击对应的对象,如JTextField,JList等.
所以应该是(e.getSource() instanceof JTextField)才正确还有像你这种情况应该给每个组件设置actionCommand("xxx")这样在处理事件时这样:
if(e.getActionCommand().equals("xxx"))及下来处理事件
if (e.getSource() == time)是比较2个内存地址是否相等,即是否是同一字符串
此处应该用第二种表示,意思是你的按钮是否是内存地址中和你一开始创建的time按钮时同一个,如果是,则执行事件(这是在string比较中常见的错误)
像这样的题你应该学会这么解决。
第一. 为什么它没有显示 ta.append(""+new Date()); //System.out.println("") 测试一下。是否进来。
第二。 把ta.append(""+new Date()); 放到你认为可以执行到的地方试一下。
第三。 从网上查一下e.getSource() 的用法。
a.初始化按钮:
jButton = new JButton("连接");
b.添加事件
jButton.addActionListener(new MyButtonListener());
c.然后事件这样写:
class MyButtonListener implements ActionListener
{ public void actionPerformed(ActionEvent e)
{
String bcommand = e.getActionCommand();
if(bcommand.equals("连接"))
2.如果确认事件已经触发就是输入框没有显示出来,尝试将将组件重绘一下如:
JPanel 的updateUI()方法