您好,我正在尝试为 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 看起来不错
当我为按钮添加特定值时
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);
看起来像下图
有什么办法可以避免这种情况并设置值。
提前感谢您的帮助。
最佳答案
就我个人而言,我会使用 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));
例如……
关于java - JButton 背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17110315/