Draw a JButton to look like a JLabel (or at least without the button edge?)

前端 未结 5 1438
野的像风
野的像风 2020-12-14 18:43

I\'ve got a JButton that for various reasons I want to act like a button, but look like a JLabel. It doesn\'t actually have to be a JLabel under the hood, I just don\'t wan

相关标签:
5条回答
  • 2020-12-14 18:51

    Set the background color to transparent, and the border to an EmptyBorder instance.

    E.g.

       JButton button = new JButton();
       button.setBackground(null);
       button.setOpaque(false);
       button.setBorder(new EmptyBorder());
    

    The text will still move up and down as you click the button, and the button can still be "armed" by clicking, holding, and "disarmed" by moving the mouse out of the button area.

    If you don't want this behaviour, then you probably don't want to use a button, and use a real label instead.

    0 讨论(0)
  • 2020-12-14 18:53
     setContentAreaFilled(false);
     setBorderPainted(false);
     setOpaque(false);
    

    This three lines do the trick.

    0 讨论(0)
  • 2020-12-14 18:55
    button.setBorderPainted( false );
    button.setContentAreaFilled( false ); // ?
    
    0 讨论(0)
  • 2020-12-14 18:57

    You will want to do the following:

            setFocusPainted(false);
            setMargin(new Insets(0, 0, 0, 0));
            setContentAreaFilled(false);
            setBorderPainted(false);
            setOpaque(false);
    

    You may want to exclude setFocusPainted(false) if you want it to actually paint the focus (e.g. dotted line border on Windows look and feel).

    I have used the above code in cases where I have wanted an "icon only" button.

    0 讨论(0)
  • 2020-12-14 19:08

    Might it actually be easier just to add a mouse listener to a JLabel? You could adjust the colors on mousePressed and mouseReleased, and do your action processing on mouseClicked?

    0 讨论(0)
提交回复
热议问题