我正在尝试创建带有框架的NewCard类。如何在NewCard类的构造函数中的元素上添加Actionlisteners?我不能将Actionlistener放入构造函数中,而当将其放在外面时,对于saveButtonListener块,元素“字段”不可见。
第二个问题:class Record在try块中抛出两个异常,为什么try块会产生错误?
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());
}
});