删除自定义按钮上的边框

时间:2012-06-22 18:41:31

标签: java swing border jbutton

我写过这个试图创建自定义JButton的小程序,但遗憾的是我无法删除边框。我以为button.setBorder(null);会删除它,但这是无效的。有谁知道如何从按钮中删除边框,所以它只是图标?非常感谢任何帮助。

我的代码如下:

package custombuttons;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CustomButtons {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        CustomButtons h = new CustomButtons();
        h.setUp();
    }

    JFrame frame;
    JPanel panel;
    JButton button;
    BufferedImage b;
    String toolTip = "Configure";

    public void setUp() {
        frame = new JFrame("Custom Buttons");
        try {
            b = ImageIO.read(CustomButtons.class.getResource("/images/config.png"));
        } catch (IOException ex) {
            Logger.getLogger(CustomButtons.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }

        Image b1 = (Image) b;
        ImageIcon iconRollover = new ImageIcon(b1);
        int w = iconRollover.getIconWidth();
        int h = iconRollover.getIconHeight();
        GraphicsConfiguration gc = frame.getGraphicsConfiguration();
        Image image = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
        Graphics2D g = (Graphics2D) image.getGraphics();
        g.drawImage(iconRollover.getImage(), 0, 0, null);
        g.dispose();

        ImageIcon iconDefault = new ImageIcon(b1);
        image = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
        g = (Graphics2D) image.getGraphics();
        g.drawImage(iconRollover.getImage(), 2, 2, null);
        g.dispose();
        ImageIcon iconPressed = new ImageIcon(b1);

        JButton button = new JButton();
        button.setIgnoreRepaint(true);
        button.setFocusable(false);
        button.setToolTipText(toolTip);
        button.setBorder(null);
        button.setContentAreaFilled(false);
        button.setIcon(iconDefault);
        button.setRolloverIcon(iconRollover);
        button.setPressedIcon(iconPressed);

        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));

        panel = new JPanel();
        panel.setOpaque(false);
        panel.add(button);
        frame.getContentPane().add(panel);
        frame.setVisible(true);
    }
}

2 个答案:

答案 0 :(得分:3)

查看button.setBorderPainted(false) more about JButton here

答案 1 :(得分:0)

实际上我在我的Netbeans IDE上测试了你的代码并没有你想要的边框 仅使用button.setBorder(null);button.setBorderPainted(false);both of them但是 我认为你应该确保你的原始图像真的没有自己的边界