【问题标题】:Margin for Custom JButton - Java自定义 JButton 的边距 - Java
【发布时间】:2013-04-18 11:24:31
【问题描述】:

我通过扩展 Jbutton 为我的应用程序创建了一个自定义按钮,并且我已经让它按照我想要的方式绘制,但由于某种原因,即使我在构造函数中调用 setMargin(),按钮也有 0边距,像这样:

我的代码有什么地方做错了吗?标准 JButton 有边距,而我的自定义按钮没有边距是怎么回事?

我的按钮的java代码:

public class CToolbarButton extends JButton
{
        private static final Dimension SIZE = new Dimension(48, 48);

        private static final int MARGIN_VAL = 50;
        private static final Insets MARGIN = new Insets(MARGIN_VAL, MARGIN_VAL, MARGIN_VAL, MARGIN_VAL);

        private static final Color FILL_NORM = Color.GRAY;
        private static final Color FILL_ACTIVE = new Color(FILL_NORM.getRed()-25, FILL_NORM.getGreen()-25, FILL_NORM.getBlue()-25);

        private static final Color BORDER_NORM = Color.BLACK;
        private static final Color BORDER_ACTIVE = Color.YELLOW;

        public CToolbarButton()
        {
                super();
                setContentAreaFilled(false);
                setFocusable(false);
                setMargin(MARGIN);
        }

        @Override
        public void paintComponent(Graphics g)
        {
                if (getModel().isArmed())
                {
                        g.setColor(FILL_ACTIVE);
                }
                else
                {
                        g.setColor(FILL_NORM);
                }
                g.fillRect(0, 0, getWidth(), getHeight());
        }

        @Override
        public void paintBorder(Graphics g)
        {
                if (getModel().isArmed())
                {
                        g.setColor(BORDER_ACTIVE);
                }
                else
                {
                        g.setColor(BORDER_NORM);
                }
                g.drawRect(0, 0, getWidth(), getHeight());
        }

        @Override
        public boolean contains(int x, int y)
        {
                return (x >= 0 &&
                                x <= getWidth() &&
                                y >= 0 &&
                                y <= getHeight());
        }

        @Override
        public Dimension getPreferredSize()
        {
                return SIZE;
        }

        @Override
        public Dimension getMinimumSize()
        {
                return SIZE;
        }

        @Override
        public Dimension getMaximumSize()
        {
                return SIZE;
        }
}

【问题讨论】:

  • “我通过扩展 Jbutton 为我的应用程序创建了一个自定义按钮,” 为什么?它有什么按钮特性,超越了 Swing JButton 的特性? “我可以按照我想要的方式进行绘画,但是..” 让我毫不惊讶地给我涂上“但是”的颜色。
  • 因为我想自定义绘制它,而我不知道如何在不创建子类的情况下做到这一点......
  • 什么样的自定义绘画?具体点..
  • 我想像 Photoshop 或 Paint 那样绘制按钮,点击时使用图标或阴影
  • 没有 Photoshop,但在 MS Paint 中没有任何部分按钮无法使用带有适当图标的标准 JButton 完成。

标签: java swing user-interface jbutton


【解决方案1】:

我不会尝试覆盖按钮的绘制方法,而是使用图像来模拟按钮的不同外观。

【讨论】:

    猜你喜欢
    • 2013-07-19
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多