2013-03-20 56 views
0

這是我的代碼,我想知道如果我可以添加新的按鈕到我的網格佈局每次我點擊一個已經存在的按鈕實例框架。是否可以通過動作監聽器爲框架創建新的按鈕?

public class Board { 

     public static void main(String[] args) { 
      JButton[] button = new JButton[40]; 
      int i = 0; 
      JFrame frame = new JFrame(); 
      frame.setLayout(new GridLayout(20, 20, 15, 15)); 
      while (i < 40) { 
       button[i] = new JButton("button" + i); 
       button[i].addActionListener(new Action()); 
       frame.add(button[i]); 
       i++; 
      } 
      frame.setSize(700, 700); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      frame.setVisible(true); 
     } 

     static class Action implements ActionListener{ 
      @Override 
      public void actionPerformed (ActionEvent e){ 


      } 
     } 
    } 
+2

請參閱本【答案】(http://stackoverflow.com/questions/6988317/dynamically -add組件到一個-的JDialog/6988341#6988341)。 – mre 2013-03-20 23:53:54

+1

是的............ – MadProgrammer 2013-03-20 23:54:01

回答

3

該解決方案相當簡單。

你需要做的就是思考這個問題。首先,你有一堆static的引用,這些引用並不是必需的,並且爲你提供很少的好處。

現在,已經說了。您Action需要一些方法來知道在哪裏添加按鈕。爲了做到這一點,Action需要的按鈕添加到容器的參考...

import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 

public class Board { 

    public static void main(String[] args) { 
     new Board(); 
    } 

    public Board() { 
     JButton[] button = new JButton[40]; 
     int i = 0; 
     JFrame frame = new JFrame(); 
     frame.setLayout(new GridLayout(20, 20, 15, 15)); 
     Action action = new Action(frame); 
     while (i < 40) { 
      button[i] = createButton(i); 
      button[i].addActionListener(action); 
      frame.add(button[i]); 
      i++; 
     } 
     action.setCount(i); 
     frame.setSize(700, 700); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 

    public JButton createButton(int index) { 

     return new JButton("button" + index); 

    } 

    public class Action implements ActionListener { 

     private JFrame frame; 
     private int count; 

     public Action(JFrame frame) { 
      this.frame = frame; 
     } 

     public void setCount(int count) { 
      this.count = count; 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      JButton btn = createButton(count); 
      btn.addActionListener(this); 
      frame.add(btn); 
      frame.revalidate(); 
      count++; 
     } 
    } 
} 
+0

+1,你的答案比我的答案要全面得多。 – syb0rg 2013-03-21 00:04:42

+0

@ syb0rg你的答案几乎是有效的,它只是錯過了如何將新創建的按鈕放到OP的UI – MadProgrammer 2013-03-21 00:09:42

+0

謝謝你的答案。他們幫助了我很多。 – 2013-03-21 00:18:07