我正在尝试创建 NewCard 类,并实现一个框架。如何将 Actionlistener 添加到 NewCard 类构造函数中的元素?我无法将 Actionlistener 放入构造函数中,当我将其放在外面时,元素“field”对于 saveButtonListener block 是不可见的。
第二个问题:try block 中的类Record抛出两个异常,为什么try block 会产生错误?
package Interface;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import Engine.*;
class NewCard extends JFrame
{
NewCard()
{
JFrame Card = new JFrame();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setTitle("New Card");
setSize(340, 580);
setVisible(true);
Container contentPane = getContentPane();
contentPane.setLayout(null);
// Field
JTextField field = new JTextField();
contentPane.add(field);
field.setBounds(110,15,200,25);
// Button:
JButton saveButton = new JButton("Save");
powZawartosci.add(saveButton);
saveButton.setBounds(95,495,150,25);
saveButtonListener listener1 = new saveButtonListener();
saveButton.addActionListener(listener1);
}
private class saveButtonListener implements ActionListener
{
try
{
@Override
public void actionPerformed(ActionEvent event)
{
new Record(field.getText());
}
}
catch(IOException e)
{
System.out.println("IOException");
}
catch(SQLException e)
{
System.out.println("SQLException");
}
finally
{
}
}
}
最佳答案
您可以将操作监听器放入构造函数中,如下所示:
final JTextField field = new JTextField();
...
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
new Record(field.getText());
}
});
关于java - 构造函数中的 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9152954/