1

I trying to draw a rectangle in JPanel but the rectangle not showing. What did I missed ?

Here is what I have tried so far.

public class selectSeat extends JFrame {

    JPanel panel = new JPanel();

    public static void main(String[] args) {
         selectSeat frameTabel = new selectSeat("","","");
    }

    public selectSeat(String title, String day, String time)
    {
        super("Select Seat");
        setSize(350,350);
        setLocation(500,280);
        panel.setLayout(null);
        RectDraw rect= new RectDraw();
        panel.add(rect);

        getContentPane().add(panel);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

    }

    private static class RectDraw extends JPanel
    {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);  
             g.drawRect(230,80,10,10);  
             g.setColor(Color.RED);  
             g.fillRect(230,80,10,10);  
            }

        public Dimension getPreferredSize() {
            return new Dimension(50, 20); // appropriate constants
          }


    }

}
  • 1
    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](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson May 16 '16 at 04:59

2 Answers2

2

You're drawing the rectangle, but it's located at 280, 80, which is way outside the confines of your visible JPanel. Understand that the drawing location is relative to the coordinates within the JPanel itself.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

Noticed that you are using Absolute layout (null layout). Component.setbounds are needed in order to position the object in place.

public Test(String title, String day, String time)
{
    super("Select Seat");
    setSize(350,350);
    setLocation(500,280);
    panel.setLayout(null);
    RectDraw rect= new RectDraw();
    rect.setBounds(0, 0, 100, 100);
    panel.add(rect);

    getContentPane().add(panel);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

}

Check out the details: https://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html

Note: Try Ctrl+Shift+F1 to get debug message from AWT as well.

dcwhcdhw
  • 59
  • 1
  • 2
  • *"Noticed that you are using Absolute layout (null layout)."* Which they shouldn't be using, and you should not be encouraging. That is, unless you are both capable of, and willing to, fix the next ten problems that causes. – Andrew Thompson May 16 '16 at 05:00