【问题标题】:Catch Jbutton pressed not by label抓住 Jbutton 不是按标签
【发布时间】:2014-02-03 04:59:00
【问题描述】:

我会通过监听器捕捉到按下的按钮,但不会捕捉到其中的文本,因为我的按钮只有背景图像。

此代码通过插入 jbutton 构造函数中的标签捕获它,但我不想显示此标签。 因此,或者我找到一种方法来隐藏按钮上的标签,或者我不插入标签并通过其他手柄捕获按钮。

class ButtonListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

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

【问题讨论】:

  • 您已经在获取源对象 (b)。你还需要什么?

标签: java swing user-interface


【解决方案1】:

使用setActionCommand() 避免按钮文本的默认操作命令。

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

public void actionPerformed(ActionEvent ae) {
  String actionCommand = ae.getActionCommand();
  if (actionCommand.equals("myButtonCommand")) {
    // do something...
  }
}

【讨论】:

    【解决方案2】:
    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());
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 2021-09-03
      相关资源
      最近更新 更多