900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > java怎样调用图像做按钮_swing-Java:使用图像作为按钮

java怎样调用图像做按钮_swing-Java:使用图像作为按钮

时间:2024-01-15 23:06:36

相关推荐

java怎样调用图像做按钮_swing-Java:使用图像作为按钮

swing-Java:使用图像作为按钮

我想将图像用作Java中的按钮,而我尝试这样做:

BufferedImage buttonIcon = ImageIO.read(new File("buttonIconPath"));

button = new JButton(new ImageIcon(buttonIcon));

但这仍然显示图像后面的实际按钮,我只想将图像用作按钮,我该怎么做?

3sdmx asked -01-02T19:48:12Z

9个解决方案

28 votes

像这样删除边框:

button.setBorder(BorderFactory.createEmptyBorder());

然后还有内容1:

button.setContentAreaFilled(false);

1:来自@ 3sdmx添加到问题中的解决方案

jzd answered -01-02T19:48:39Z

9 votes

建议将“图像”设置为标签,并将鼠标侦听器添加到标签以检测点击。

例:

ImageIcon icon = ...;

JLabel button = new JLabel(icon);

button.addMouseListener(new MouseAdapter() {

@Override

public void mouseClicked(MouseEvent e) {

... handle the click ...

}

});

thotheolh answered -01-02T19:49:04Z

1 votes

buttonIcon.setBorder(newEmptyBorder(0,0,0,0));

StanislavL answered -01-02T19:49:23Z

1 votes

button.setBorderPainted( false );

camickr answered -01-02T19:49:39Z

1 votes

通过将contentAreaFilled属性设置为False,可以在netbeans中轻松完成此操作

unleashed answered -01-02T19:49:59Z

1 votes

BufferedImage buttonIcon = ImageIO.read(new File("myImage.png"));

button = new JButton(new ImageIcon(buttonIcon));

button.setBorderPainted(false);

button.setFocusPainted(false);

button.setContentAreaFilled(false);

Vladimir answered -01-02T19:50:14Z

1 votes

只是写这个

button.setContentAreaFilled(false);

Adham Gamal answered -01-02T19:50:34Z

0 votes

据我所知,没有简便的方法,您将需要重写JButton类的“ paintComponent”方法来修饰图像,如果您只想显示图像并表现得像按钮,则可以添加 一个JPanel绘制图像(clicky)并添加一个MouseListener / MouseAdapter来处理“ mousePressed”事件

Harima555 answered -01-02T19:50:55Z

0 votes

我按照以下步骤操作,可以成功创建“ ImageButton”。

创建Border

添加了动作监听器

设置图像图标(请注意,我已将Border图标放置在src \ main \ resources文件夹中,并使用类加载器加载了)。 项目结构如下。

设置一个空的Border

禁用内容区域填充

禁用对焦能力

添加到内容窗格

PFB对我有用的代码

JButton btnNewButton = new JButton("");

btnNewButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

System.out.println("Info clicked");

}

});

String iconfilePath = this.getClass().getClassLoader().getResource("info.png").getFile();

btnNewButton.setIcon(new ImageIcon(iconfilePath));

btnNewButton.setBounds(10, 438, 39, 31);

btnNewButton.setBorder(BorderFactory.createEmptyBorder());

btnNewButton.setContentAreaFilled(false);

btnNewButton.setFocusable(false);

contentPane.add(btnNewButton);

上面的代码产生的输出按钮如下

sunil answered -01-02T19:51:54Z

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。