方法和最终修饰符

时间:2012-09-16 00:22:13

标签: java swing methods final

所以,我有一个JTextArea。我已经为它的输入/动作地图添加了键盘动作。

在输入按下时,应该创建JDialog及其内容。我需要将keyListener添加到它将包含的按钮中,我不能,因为该按钮不是最终修饰符。如果我把它设置为final,我就无法编辑它的属性。

以下是代码片段:

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 个答案:

答案 0 :(得分:3)

  • 选项1:确认一个类字段。
  • 选项2:您可以创建一个虚拟的最终JButton变量final JButton finalConfirm = confirm;并传入确认引用,然后在内部类中处理此变量。
  • 选项3:不要为Key Binding的AbstractAction使用匿名内部类,而是使用带有JButton实例的构造函数的私有内部类。