简体   繁体   中英

Put a JLabel over two JButtons

Okay so before you ask, yes I'm not using any Layout Manager. No, that doesn't make this bad design (as I've seen people in here saying because someone simply didn't use one). The thing is i want the label to always (and I mean always) show over the two buttons (over the gap left by them which makes it impossible to put it as an Icon or a text on the JButton ).

JFrame frame = new JFrame("ColorTap");
private void init() {

    JButton jb1 = new JButton(""), jb2 = new JButton("-");
    JLabel label = new JLabel("TEXT HERE");
    label.setForeground(Color.white);
    label.setFont(new Font("Arial Bold",Font.ITALIC,30));
    label.setBounds(60,249,200,100);
    frame.setLayout(null);
    jb1.setBounds(0, 0, 300,298);
    jb2.setBounds(0, 302, 300, 300);
    jb1.setBackground(Color.black);
    jb2.setBackground(Color.black);
    jb1.setBorderPainted(false);
    jb2.setBorderPainted(false);
    frame.add(label);
    frame.add(jb1);
    frame.add(jb2);
    frame.setResizable(false);
    frame.setSize(300, 628);
    frame.setLocation(550, 50);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

After this what's stranger to me is that the button on the bottom stays under the label and not the one on the top... HELP! Thanks

Swing is optimized to paint components in two dimensions. That is it assumes components will never overlap. Overlapping JButtons cause a problem because of the rollover effects which only cause the buttons to be painted, not the label, so the button is painted over the top of the label.

So you need to tell Swing that components do overlap so Swing can make sure components are painted in the proper ZOrder:

JPanel panel = new JPanel()
{
    @Override
    public boolean isOptimizedDrawingEnabled()
    {
        return false;
    }
};

Now you can set the layout manager of the panel and add your components to the panel and they will be painted properly.

See: How to put a JButton with an image on top of another JButton with an image? for a working example that DOES use layout managers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM