2014-12-24 21 views
0

就像背後的故事一樣,我真的進入java並一直在觀看所有這些視頻和這樣的在線,我決定,雖然學習它是好的,如果我可以不實際使用它,它毫無意義。所以我用計算器去了。除了一件事以外,一切都進展順利。引用通過方法分配的按鈕的名稱

爲了展示我的懶惰,我做了一個接受參數的方法,並用一個簡單的方法調用來構建一個JButton。該代碼是:

public class GUI_Element_Methods{ 

private JButton button1; 
private JButton numpad[]; 


public void createButton(String buttonText, ActionListener eventMethod, boolean visible, String tooltipText){ 

    button1 = new JButton(buttonText); 
    button1.addActionListener(eventMethod); 
    button1.setVisible(visible); 
    button1.setToolTipText(tooltipText); 

} 

public JButton getButton1(){ 
    return(button1); 
} 

呼籲:

guiElement.createButton("+", asHandler, true, "Addition"); 
    add(guiElement.getButton1()); 

我的作品都很好,但我有麻煩試圖檢測一個行動是在事件處理程序的某個按鈕,因爲它們都運行這個「button1」JButton。例如,畢達哥拉斯定理,它有兩種基於你想要解決的變體,我想只用1個事件處理程序來檢測哪一個被按下。

if(event.getSource().equals()){ 
}else{ 
} 

這就是我以爲我會把它,我只是不知道如何引用方法創建的按鈕。

+0

你可能也想從'createButton'方法返回按鈕,它可能更容易呼叫者 – MadProgrammer

回答

5

你總是可以嘗試區分由獲取其actionCommand,即按下按鈕,

public void actionPerformed(ActionEvent e) { 
    String actionCommand = e.getActionCommand(); 
} 

然後,您可以比較字符串常量該字符串,看看是否有你想要的按鈕。


例如:

import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.*; 

public class NumberPad extends JPanel { 
    public static final String[][] NUMBER_TEXTS = { 
     {"7", "8", "9"}, 
     {"4", "5", "6"}, 
     {"1", "2", "3"} 
    }; 

    public NumberPad() { 
     ActionListener actionListener = new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      System.out.println("ActionCommand: " + e.getActionCommand()); 
     } 
     }; 
     setLayout(new GridLayout(3, 3)); 
     for (String[] row : NUMBER_TEXTS) { 
     for (String cell : row) { 
      JButton button = new JButton(cell); 
      button.addActionListener(actionListener); 
      add(button); 
     } 
     } 
    } 

    private static void createAndShowGui() { 
     NumberPad mainPanel = new NumberPad(); 

     JFrame frame = new JFrame("Number Pad"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 

} 
+0

感謝您的幫助,得到行動指令工作。看着你的代碼讓我想起了多維數組的存在,完全忘了這些。我應該使用數字鍵盤之一。 – WaffleMan0310

0

,您可根據ArrayList其中將包含所有JButton對象,您將創建。

將按鈕添加到它並在actionPerformed方法上進行比較。

List<JButton> btnList = new ArrayList<JButton>(); 
. . . 
btnList.add(button1); 
. . . 
void actionPerformed(...) 
for(JButton btn : btnList){ 
if(event.getSource().equals(btn)){ 
//do whatever you want with this button. 
} 
} 
+1

1)使用縮進代碼行和塊的邏輯和一致形式。縮進旨在使代碼的流程更易於遵循! 2)請使用代碼格式設置代碼和代碼片段,結構化文檔(如HTML/XML或輸入/輸出)。爲此,請選擇文本並單擊郵件發佈/編輯表單頂部的「{}」按鈕。 –