2014-01-14 46 views
0

我會聽到按鈕按下按鈕,但不是由它裏面的文本,因爲我只有背景圖像的按鈕。抓住Jbutton不按標籤

此代碼通過插入jbutton構造函數中的標籤捕獲它,但我不想顯示此標籤。 因此,或者我找到一種方法來隱藏按鈕上的標籤,或者我不插入標籤並通過其他一些手柄來捕獲按鈕。

class ButtonListener implements ActionListener { 

    @Override 
    public void actionPerformed(ActionEvent e) { 

    JButton b = (JButton)e.getSource(); 
    JOptionPane.showMessageDialog(null,"È stato premuto"+b.getActionCommand()); 
    } 
} 
+0

您已經獲得源對象('B')。你還需要什麼? –

回答

3

使用setActionCommand()來避免按鈕文本的默認動作命令。

JButton myButton = new JButton(); 
myButton.setActionCommand("myButtonCommand"); 

public void actionPerformed(ActionEvent ae) { 
    String actionCommand = ae.getActionCommand(); 
    if (actionCommand.equals("myButtonCommand")) { 
    // do something... 
    } 
} 
0
ImageIcon ic=new ImageIcon("C:/image.png"); 
JButton btn=new JButton(ic); 
btn.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent ae) { 
     JButton b = (JButton)ae.getSource(); 
     JOptionPane.showMessageDialog(null,"È stato premuto"+b.getActionCommand()); 
    } 
});