【问题标题】:JButton showing behind iconJButton 显示在图标后面
【发布时间】:2012-07-15 20:16:55
【问题描述】:

我正在尝试创建一个扩展 JButton 的自定义按钮。它接受文本以及按钮的所需宽度和高度。构造函数根据输入的宽度和高度缩放图像按钮。但是,正如您在所附图片中看到的那样,出了点问题。

这是我的课:

class GameButton extends JButton {
    public GameButton(String text, int width, int height) {
        BufferedImage image = null;
        try {
            image = ImageIO.read(new File("Images/Other/buttonImage.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Create new (blank) image of required (scaled) size
        BufferedImage scaledImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);

        // Paint scaled version of image to new image
        Graphics2D graphics2D = scaledImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image, 0, 0, width, height, null);
        // clean up
        graphics2D.dispose();

        ImageIcon icon = new ImageIcon(scaledImage);

        setIcon(icon);
        setMargin(new Insets(0, 0, 0, 0));
        setIconTextGap(0);
        setBorderPainted(false);
        setOpaque(false);
        setBorder(null);
        setText(text);
        setSize(width, height);
    }
}

原始按钮图像仍在绘制中,看起来图像可能未正确缩放。 有什么想法吗?

谢谢!

【问题讨论】:

  • 这个answer 包含一些有用的代码。此外,您应该将水平文本位置设置为居中,以便将其绘制在图标上。
  • JButton.setContentAreaFilled(false);
  • 为什么不画“植物!”直接到缩放的图像(而不是使用按钮文本)?顺便说一句 - 请上传“plank”图片,为了尽快获得更好的帮助,请发布SSCCE

标签: java swing scale jbutton imageicon


【解决方案1】:

为按钮设置 Horizo​​ntalTextPosition

jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 2015-06-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    相关资源
    最近更新 更多