Java 方法和最终修改器
所以,我有一个区域。我已经将键盘动作添加到它的输入/动作图中 按enter键时,应该创建JDialog及其内容。我需要将keyListener添加到它将包含的按钮中,但我不能,因为该按钮没有最终修改器。如果我将其设置为final,则无法编辑其属性 下面是一段代码:Java 方法和最终修改器,java,swing,methods,final,Java,Swing,Methods,Final,所以,我有一个区域。我已经将键盘动作添加到它的输入/动作图中 按enter键时,应该创建JDialog及其内容。我需要将keyListener添加到它将包含的按钮中,但我不能,因为该按钮没有最终修改器。如果我将其设置为final,则无法编辑其属性 下面是一段代码: class blabla extends JTextArea { getInputMap.put(KeyStroke.getKeyStroke("ENTER"), "pressedEnter"); getActionMap.put("
class blabla extends JTextArea
{
getInputMap.put(KeyStroke.getKeyStroke("ENTER"), "pressedEnter");
getActionMap.put("pressedEnter", new AbstractAction()
{
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
JDialog dialog;
JButton confirm;;
//JDialog
dialog = new JDialog(Main.masterWindow, "newTitle", true);
dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
dialog.addWindowListener(new WindowAdapter()
{
public void windowActivated(WindowEvent e)
{
//this doen't work, it asks me to declare confirm as final
//and I have to request focuse here due to Java bug
confirm.requestFocus();
}
});
//JButton for confirming
confirm = new JButton(lang.getString("ok"));
confirm.setAlignmentX(Component.CENTER_ALIGNMENT);
confirm.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
//this doen't work, it asks me to declare confirm as final
confirm.doClick();
}
}
});
dialog.add(confirm);
dialog.pack();
dialog.setLocationRelativeTo(Main.masterWindow);
dialog.setVisible(true);
}
我怎样才能做到这一点?- 选项1:确认类字段
- 选项2:您可以创建一个伪final JButton变量,
并传入confirm引用,然后在内部类中处理该变量final JButton finalConfirm=confirm
- 选项3:不要为密钥绑定的抽象操作使用匿名内部类,而是使用带有构造函数的私有内部类来获取JButton实例