Home > OS >  Swing: can't paint rectangle
Swing: can't paint rectangle

Time:12-04

I have this simple code: the JFrame adds custom Jpanel MyPanel which overrides paintComponent method to draw the rectangle. However nothing shows up on the window:

import javax.swing.*;

import java.awt.*;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestGui extends JFrame  {
    public TestGui()  {
        setLayout(new FlowLayout());

        JPanel panel = new JPanel();

        panel.add(new JLabel("H E L L O"));
        getContentPane().add(panel);

        getContentPane().add(new MyPanel());

        setSize(100, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        repaint();
        revalidate();
        setVisible(true);
    }

    class MyPanel extends JPanel {
        private int squareX = 50;
        private int squareY = 50;
        private int squareW = 20;
        private int squareH = 20;

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.RED);
            g.fillRect(squareX,squareY,squareW,squareH);
        }
    }

    public static void main(String[] args) {
        TestGui gui = new TestGui();
    }
}

CodePudding user response:

By default, an empty JPanel has a size of 0x0, so when you add it to your UI, the layout manager (in this case) honours it's request and makes it 0x0

Start by adding ...

@Override
public Dimension getPreferredSize() {
    return new Dimension(100, 100);
}

to MyPanel

Also, the repaint and revalidate calls aren't going to do anything, as the window isn't yet attached to native peer (rendering surface)

  • Related