在按钮上方的东西?这叫什么?

时间:2014-10-07 00:49:33

标签: java user-interface

我只想要一个普通的JButton,如下所示:

JButton buttonWCRoss = new JButton("Button out");

但是按钮上的图像和文字" Imaged Button"。我该怎么做?

谢谢

4 个答案:

答案 0 :(得分:3)

我会扩展JBUtton并覆盖它的paintComponent方法,在你的十字架中绘图:

  JButton button = new JButton("Cross Out Button") {
     @Override
     protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
              RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(new Color(255, 0, 0, 150));
        g2.setStroke(CROSS_STROKE);
        int x1 = 4;
        int y1 = x1;
        int x2 = getWidth() - x1;
        int y2 = getHeight() - y1;

        g2.drawLine(x1, y1, x2, y2);
        g2.drawLine(x1, y2, x2, y1);
     }
  };

您可能希望使用半透明的颜色(正如我上面所做的那样),以便文本显示出来。不要忘记设置RenderingHints来摆脱锯齿状。

CROSS_STROKE是我在测试程序中声明的常量,一个BasicStroke对象:

   protected static final Stroke CROSS_STROKE = new BasicStroke(5, 
                   BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);

答案 1 :(得分:2)

您可以延长JButton

public class CrossButton extends JButton {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(!isEnabled()) {
            g.setColor(Color.BLACK);
            g.drawLine(0, 0, getWidth(), getHeight());
            g.drawLine(0, getHeight(), getWidth(), 0);
        }
    }
}

然后使用setEnabled(boolean)绘制十字架。我假设您想要删除禁用的按钮。

未经测试但应该可以正常工作。经过测试和工作。

答案 2 :(得分:2)

阅读How to Decorate Components With the JLayer Class上的Swing教程中的部分。使用此类,您可以在不扩展组件的情况下对组件进行任何类型的自定义绘制。

答案 3 :(得分:0)

您可以使用.setText("")方法更改按钮顶部的文字,如果这是您要求的内容。另外还有.setFont(新字体(" Arial",Font.Plain,40))作为示例,用于更改按钮内的字体。