2010-05-25 128 views
0

我在JFrame窗口上有多個面板。我將每次都以不同的方式填充每個面板。例如: 我啓動GUI :(圖像中心面板,右側面板,底部面板)。中央面板上有20個按鈕,右側面板上有10個按鈕,底部面板上有3個。java檢測點擊按鈕

第二次啓動GUI(同樣的gui)。中央面板有50個按鈕,右側面板有12個按鈕,底部有3個。

所以每次都有一個隨機數的按鈕,不可能全部都是唯一命名的。 鑑於我沒有每個按鈕的唯一名稱(只是一個列表),我想知道哪些按鈕是根據它們所屬的面板點擊的。那可能嗎?

+0

爲什麼這麼多按鈕?這給我帶來了糟糕的用戶界面味道。也許如果你給了我們更多關於你想要完成的事情的線索。如果按鈕足夠重要,可以在屏幕上顯示,他們可能應該被命名爲變量。 – I82Much 2010-05-25 03:37:57

回答

3

不知何故按鈕正在創建;假設您以某種方式將它們編號,以便您稍後可以檢索。

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 
import java.util.List; 
import java.util.ArrayList; 
import javax.swing.JButton; 


public class ButtonTest extends JFrame implements ActionListener { 

    public ButtonTest() { 
     super(); 
     initGUI(); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setVisible(true); 
    } 

    private final List<JButton> buttons = new ArrayList<JButton>(); 
    private static final int NUM_BUTTONS = 20; 

    public void initGUI() { 
     JPanel panel = new JPanel(); 
     for (int i = 0; i < NUM_BUTTONS; i++) { 
      String label = "Button " + i; 
      JButton button = new JButton(label); 
      button.setActionCommand(label); 
      button.addActionListener(this); 
      buttons.add(button); 
      panel.add(button); 
     } 
     getContentPane().add(panel); 
    } 

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

    public void actionPerformed(ActionEvent e) { 
     String actionCommand = ((JButton) e.getSource()).getActionCommand(); 
     System.out.println("Action command for pressed button: " + actionCommand); 
     // Use the action command to determine which button was pressed 
    } 


} 
1

ActionEvent有一個getSource()方法,該方法將作爲被點擊的按鈕的引用。如果需要,您可以檢查按鈕的操作命令。

1

如果您想知道哪個面板包含該按鈕,請嘗試在JButton本身上調用getParent()。按照camickr的建議,要找出哪個按鈕被點擊,請在ActionEvent上使用getSource()