1

我编写了这个尝试创建自定义 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);
    }
}
4

2 回答 2

3

在这里查看button.setBorderPainted(false) 更多关于 JButton 的信息

于 2012-06-22T18:48:03.823 回答
0

实际上,我在我的 Netbeans IDE 上测试了您的代码,并且没有您想要的边框,仅使用button.setBorder(null);orbutton.setBorderPainted(false);或,both of them但我认为您应该确保您的原始图像本身没有任何边框

于 2012-06-22T19:00:57.047 回答