【问题标题】:method and final modifiers方法和最终修饰符
【发布时间】:2012-09-08 17:43:42
【问题描述】:

所以,我有一个 JTextArea。我在它的输入/动作映射中添加了键盘动作。

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

这是代码的sn-p:

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);
}

我怎样才能做到这一点?

【问题讨论】:

    标签: java swing methods final


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

    【讨论】:

    • 另外,为confirm 使用Action,并考虑使用根窗格的getDefaultButton()
    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    相关资源
    最近更新 更多