JButton背景图片

您好我正在尝试为JButton实现Action侦听器,代码如下所示:

ImageIcon imageForOne = new ImageIcon(getClass().getResource("resources//one.png")); one = new JButton("",imageForOne); one.setPreferredSize( new Dimension(78, 76)); one.addActionListener(myButtonHandler); 

使用上面的JButton它看起来很好 按钮1见下图

当我为按钮添加特定值时,例如

 ImageIcon imageForOne = new ImageIcon(getClass().getResource("resources//one.png")); //Check this one = new JButton("one",imageForOne); one.setPreferredSize( new Dimension(78, 76)); one.addActionListener(myButtonHandler); 

它看起来像下图

检查按钮1

有什么办法可以避免这种情况并设定价值。

感谢您的帮助。

就个人而言,我将使用Action API 。

它将允许您定义操作命令的层次结构(如果这是您想要的)以及定义对命令的自包含响应。

你可以…

 public class OneAction extends AbstractAction { public OneAction() { ImageIcon imageForOne = new ImageIcon(getClass().getResource("resources//one.png")); putValue(LARGE_ICON_KEY, imageForOne); } public void actionPerfomed(ActionEvent evt) { // Action for button 1 } } 

然后你只需使用按钮……

 one = new JButton(new OneAction()); one.setPreferredSize( new Dimension(78, 76)); 

例如…

我将使用适配器模式,而不是确定在动作侦听器中单击的按钮:

 one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { handleClick("one"); } }); 

handleClick仍然是所有按钮的处理程序。

我想获得该值并将其用于动作侦听器。

您可以使用action命令:

 one.setActionCommand("1"); 

但是,最好使用要插入显示组件的实际文本。 然后,您可以使用以下代码在所有按钮上共享ActionListener:

 ActionListener clicked = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String text = e.getActionCommand() // displayComponent.appendText(text); } }; one.addActionListener(clicked); two.addActionListener(clicked);