java - 方法和最终修饰符

标签 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:确认类字段。
  • 选项 2:您可以创建一个虚拟的最终 JButton 变量,final JButton finalConfirm = confirm; 并传入确认引用,然后在内部类中处理这个变量。
  • 选项 3:不要为您的 Key Binding 的 AbstractAction 使用匿名内部类,而是使用带有采用 JButton 实例的构造函数的私有(private)内部类。

关于java - 方法和最终修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12443493/

相关文章:

java - Jersey 记录过滤器

java - 使用slick 2D导出eclipse项目时的一些问题

c# 不能声明具有相同参数的静态和非静态方法?

c# - 显示给定行执行次数的 C++ 报告工具

java - 异常处理正确结束后,切换代码在永无止境的循环中执行。

java - 删除 jtable 中未使用的行(空行)?

java - JFrame 仅在首次创建时显示组件

java - JFileChooser 在 Linux 下不是模态的

java - 如何在方法声明上使用 @around spring aop 注释?

java - 打印 1-20 的数组,跨度为 10 的两个方法代码