Graphics not displaying in JLayeredPane (java swing)

I am trying to gradually create an image based on user inputs. What I'm trying to do is create a bunch of graphics and add them as layers, however I am having some problems as they will not appear. Here is the code I'm using:

public class ClassA { protected final static int dimesionsY = 1000; private static int dimesionsX; private static JFrame window; private static JLayeredPane layeredPane; public void init() { window = new JFrame("Foo"); dimesionsX = // some user input window.setPreferredSize(new Dimension(dimesionsX, dimesionsY)); window.setLayout(new BorderLayout()); layeredPane = new JLayeredPane(); layeredPane.setBounds(0, 0, dimesionsX, dimesionsY); window.add(layeredPane, BorderLayout.CENTER); ClassB myGraphic = new ClassB(); myGraphic.drawGraphic(); layeredPane.add(myGrpahic, new Integer(0), 0); window.pack(); window.setVisible(true); } } public class ClassB extends JPanel { public void drawGraphic() { repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(10, 10, 100, 100); } } 

However, my graphics do not seem to appear, and I do not understand why. I also tried adding it to JPanel , adding that JPanel in JLayeredPane , however, this did not work either.

Please can someone help me?

+6
source share
2 answers

If you add a component to JLayeredPane, it seems to add it to the zero layout using the container: you must fully specify the size and position of the component.

eg.

 import java.awt.*; import javax.swing.*; public class ClassA { protected final static int dimesionsY = 800; protected final static int dimesionsX = 1000; //!! private static JFrame window; private static JLayeredPane layeredPane; public void init() { window = new JFrame("Foo"); // !! dimesionsX = // some user input //!! window.setPreferredSize(new Dimension(dimesionsX, dimesionsY)); window.setLayout(new BorderLayout()); layeredPane = new JLayeredPane(); //!! layeredPane.setBounds(0, 0, dimesionsX, dimesionsY); layeredPane.setPreferredSize(new Dimension(dimesionsX, dimesionsY)); window.add(layeredPane, BorderLayout.CENTER); ClassB myGraphic = new ClassB(); myGraphic.drawGraphic(); myGraphic.setSize(layeredPane.getPreferredSize()); myGraphic.setLocation(0, 0); //!! layeredPane.add(myGraphic, new Integer(0), 0); layeredPane.add(myGraphic, JLayeredPane.DEFAULT_LAYER); window.pack(); window.setVisible(true); } public static void main(String[] args) { new ClassA().init(); } } class ClassB extends JPanel { public void drawGraphic() { repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(10, 10, 100, 100); } } 
+13
source

See β€œAligning Components in a Layered Panel” from Java Tutorials.

In addition, sometimes you need to set your preferred size:

layeredPane.setPreferredSize(new Dimension(width, height));

0
source

Source: https://habr.com/ru/post/900339/


All Articles