Search code examples
javaswingjpanelpaintcomponent

paintComponent not visible java


I want to add this into another JPanel but it's not visible there. My other Jpanel is called bottomPanel. The paintComponent is supposed to display in the bottom Panel

 bottomPanel.setLayout(null);  
 TestPane tp = new TestPane();
 bottomPanel.add(tp);

I have extended the Jpanel.

  public class TestPane extends JPanel {
  @Override
   public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }


    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        int width = getWidth() - 100;
        int height = getHeight() - 100;
        int x = (getWidth() - width) / 2;
        int y = (getHeight() - height) / 2;
        g2d.setColor(Color.RED);
        g2d.drawRect(x, y, width, height);
        g2d.dispose();
    }

}

Solution

  • The problem starts with:

    bottomPanel.setLayout(null);
    

    Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.

    And in future, post an MCVE rather than over 300 lines of code with irrelevant additions like file I/O, tables, row sorters etc.