简体   繁体   中英

JComponent background color using null layout?

just a short question: Is it possible to add a background color to a JComponent when it is added directly onto a JFrame using null layout? The size and position of the component are set by setBounds() and i know that the background color will not be displayed using this setup. (I know you should always use layout managers, but in this case i want to prevent this).

JComponent is transparent by default, you'd either need to change its opaque state or use a JPanel

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                TestPane pane = new TestPane();
                pane.setBounds(10, 10, 100, 100);

                JFrame frame = new JFrame("Testing");
                frame.setLayout(null); // This is bad, but it proofs my point
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(pane);
                frame.setSize(200, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JComponent {

        public TestPane() {
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    setOpaque(!isOpaque());
                    repaint();
                }
            });
            setBackground(Color.BLUE);
            setBorder(new LineBorder(Color.RED));
        }

    }

}

null layouts are bad news, I don't condone them and you should avoid using them, the example above simply proves the point that it's the JComponent s opaque state which needs to be changed

Why is it frowned upon to use a null layout in SWING? is a nice read about why you should avoid using null layouts.

If you want more control, write your own.

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