![](/img/trans.png)
[英]Java Swings GUI, changing the display based on which button is clicked. What is the ideal way to implement this?
[英]Which button has clicked. Java,Netbeans
我用Netbeans在Java中制作了一個應用程序。 在Jframe表單中,我使用四個按鈕。 我需要知道其中哪個已被用戶點擊。 誰能幫助我? 謝謝
public class Color extends javax.swing.JFrame implements ActionListener {
public Color() {
initComponents();
/////////////////////////////////
//Register a listener for the buttons.
up_button.addActionListener(this);
down_button.addActionListener(this);
left_button.addActionListener(this);
right_button.addActionListener(this);
}
private int k=1;
public void actionPerformed(ActionEvent e) {
k=k+1;
if (k==1)
{
image.setIcon(createImageIcon("color1"
+ e.getActionCommand()
+ ".PNG"));
}
else ... }
private void up_buttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void down_buttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Color().setVisible(true);
}
});
}
您可以在ActionEvent
上調用getSource
來找出事件的來源。 這將是按鈕之一。
我需要知道其中哪個用戶已點擊
只需實現actionPerformed
方法並在ActionEvent
變量上調用getSource()
即可知道單擊了哪個按鈕:
public void actionPerformed(ActionEvent e){
if(e.getSource() == up_button){
//up_button clicked
}
}
您也可以將監聽器直接添加到按鈕中:
up_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Button is pressed
}
});
處理程序的ActionEvent
參數將包含對創建事件的對象(按鈕)的引用。
(繼承自EventObject)
http://docs.oracle.com/javase/7/docs/api/java/util/EventObject.html#getSource()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.