In my project, I have a display. It's code looks like this:
frame = new JFrame(title);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(width,height)); // I have it fullscreen
panel.setBorder(BorderFactory.createEmptyBorder());
panel.setLayout(new GridLayout(1,1)); // I tried this and it works like borderless/windowed fullscreen
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setUndecorated(true);
frame.setLayout(new GridLayout(1,1));
frame.getContentPane().add(panel,JLayeredPane.DEFAULT_LAYER);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setFocusable(false);
panel.add(canvas);
frame.pack();
frame.setVisible(true);
What I want to do, is when I press "~", there would appear a let's say... 50% transparent "console" window. Or just an extra layer with info like "noClip: on; x: 153,04" etc.
How should I add this in code? I tried something like JLayeredPane but it didn't seem to work. It's possible, that I didn't understand it well.
I'm not asking about listeners etc. The problem is the final methode "creating" this extra JFrame/JPanel or whatever it's needed to be.
----UPDATE----
I changed some things in my code, as Programer_Serbia suggested. Now it looks like this:
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setUndecorated(true);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(width,height));
panel.setBorder(BorderFactory.createEmptyBorder());
panel.setLayout(new GridLayout(1,1));
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setFocusable(false);
panel.add(canvas);
frame.getContentPane().add(panel);
//frame.getLayeredPane().add(panel,new Integer(0));
frame.pack();
frame.setVisible(true);
I tried using frame.getLayeredPane().add(panel,new Integer(0)) instead of frame.getContentPane().add(panel). It doesn't show anything at all. Any ideas?
There are several issues with your code.
You are calling
setSize
on the frame at the beginning, butpack()
shortly before opening, which renders the configured size useless. Especially, when you don’t add anything to the content pane, but just to the layered pane, the preferred size of the undecorated window will be zero.When you add components to the layered pane, you have to care for their size yourself. Nesting components into other components doesn’t make the job easier.
Since your example code doesn’t create any visual element, but just panels containing other panels and an empty canvas, there will be no visual indicator for success anyway.
Canvas
doesn’t play nicely with Swing components. I doubt that you can make it transparent at all.Here is a self-contained example with a (semi-)transparent popup: