I'm writing a small "Game" in Java, in which I am using a JPanel as the main rendering screen. I've also included a JComboBox above the rendering-JPanel for dropdown-options. But when I try to expand the JComboBox it gets overdrawn from the JPanel.
I've tried setComponentZOrder() but this only made the Component eat each other in the LayoutManager. And JLayeredPane didn't seem to work either.
How can I make a "realtime redered" JPanel not overdraw overlapping components?
Simplified example:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JPanel renderScreen = new JPanel();
Thread drawingThread = new Thread(() -> {
while (true) {
Graphics graphics = renderScreen.getGraphics();
graphics.setColor(Color.MAGENTA);
graphics.fillRect(0, 0, renderScreen.getWidth(), renderScreen.getHeight());
try {Thread.sleep(5);} catch (InterruptedException ie) {}
}
});
frame.add(renderScreen, BorderLayout.CENTER);
JComboBox<String> dropdown = new JComboBox<>(new String[]{"Hello", "StackOverflow", "please", "help"});
frame.add(dropdown, BorderLayout.NORTH);
frame.setComponentZOrder(renderScreen,1);
frame.setComponentZOrder(dropdown,0);
frame.setVisible(true);
drawingThread.start();
}
This is the result:

Your code is breaking several Swing rules, including:
Instead,
super.paintComponent(g)method in your paintComponent override so that housekeeping painting can be doneFor example