My goal is to have a window with 2 panels in different colors in the background. They each cover a specific percentage of the screen and this changes periodically. I did this by creating a JSplitPane
. But now I want to add a JLabel
showing some data in front of all of this in the middle of the screen. How would I do this?
Considering your description, I prefer using a paintComponent
approach. You just paint 2 rectangles on the background of components and still positioning components as usual, as simple as this:
JFrame f = new JFrame();
f.setPreferredSize(new Dimension(600, 600));
f.pack();
f.setLayout(new BorderLayout());
JPanel p = new JPanel(new FlowLayout()) {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int perc = (int)((float)getWidth()*0.3f); // set % to fill
g.setColor(Color.RED);
g.fillRect(0, 0, perc, g.getClipBounds().height);
g.setColor(Color.BLUE);
g.fillRect(perc, 0, getWidth()-perc, getHeight());
}
};
f.add(p);
p.add(new JButton("test"));
f.setVisible(true);
My example does it on a JPanel
but it can be done directly on JFrame
and then puts a JButton
over it using a FlowLayout
. Here is the result: