2012-09-16 60 views
1

所以,我有一個JTextArea。我已將鍵盤操作添加到輸入/動作映射中。方法和最終修飾符

在輸入press時,應該創建JDialog以及它的內容。而且我需要將keyListener添加到它將包含的按鈕,而我不能,因爲該按鈕不適用於最終修改器。如果我將它設置爲最終,我不能編輯它的屬性。

這裏的代碼片段:

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

我怎樣才能使這項工作?

回答

3
  • 選項1:確認一個班級字段。
  • 選項2:您可以創建一個虛擬的最終JButton變量final JButton finalConfirm = confirm;並傳入確認引用,然後在內部類中使用此變量。
  • 選項3:不要爲您的Key Binding的AbstractAction使用匿名內部類,而要使用帶有JButton實例的構造函數的私有內部類。
+1

此外,對'confirm'使用'Action',並考慮使用根窗格的getDefaultButton()。 – trashgod