我已经在文本字段中添加了一个动作监听器。当按下btnReadString(按钮读取字符串)时,程序应读取文本字段上的内容并显示在JPanel上。但面板上没有任何显示。
stringTextField.addActionListener(new ActionListener() {
public void stringTextField (java.awt.event.ActionEvent e) {
if(e.getSource()==btnReadString) //when the button is pressed
{
String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
textPane.setText(stringParameter);//the JPanel is set to what is on the string.
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
最佳答案
您已将ActionListener
添加到文本字段。因此,事件源永远不会成为按钮,因此代码也永远不会执行。您想要的是将ActionListener
添加到JButton
。
同样,actionPerformed()
在那里也是有原因的。您所有的“操作”代码都在此方法内。
因此,您的代码应如下所示:
btnReadString.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String stringParameter = stringTextField.getText();
textPane.setText(stringParameter);
}
});