如何在Java Swing中将图像用作按钮

时间:2013-03-01 14:15:06

标签: java swing jbutton jlabel imagebutton

我正在使用netbeans来创建一个项目应用程序,我正在尝试将一个自定义图像文件作为一个按钮,我听到某处将其设置为标签,但我对此很新,所以我需要深入回答如何做到这一点。该网站不会让我发布按钮的图像,因为我只是新的但按钮是三角形的形状。

1 个答案:

答案 0 :(得分:4)

使用方法implemented in API and to remove Borders and Background from JButton

e.g。

enter image description here enter image description here

来自代码

import java.awt.Insets;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class MyToggleButton extends JFrame {

    private static final long serialVersionUID = 1L;
    private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
    private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
    private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");

    public MyToggleButton() {
        final JButton toggleButton = new JButton();
        toggleButton.setBorderPainted(false);
        toggleButton.setBorder(null);
        toggleButton.setFocusable(false);
        toggleButton.setMargin(new Insets(0, 0, 0, 0));
        toggleButton.setContentAreaFilled(false);
        toggleButton.setIcon((errorIcon));
        toggleButton.setSelectedIcon(infoIcon);
        toggleButton.setRolloverIcon((infoIcon));
        toggleButton.setPressedIcon(warnIcon);
        toggleButton.setDisabledIcon(warnIcon);
        add(toggleButton);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                MyToggleButton t = new MyToggleButton();
            }
        });
    }
}