JPanel中没有显示矩形

时间:2016-05-15 16:36:03

标签: java swing jpanel

我尝试在JPanel中绘制一个矩形,但矩形未显示。我错过了什么?

这是我到目前为止所尝试的内容。

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
          }


    }

}

2 个答案:

答案 0 :(得分:2)

您正在绘制矩形,但它位于280,80,这超出了可见JP区域的范围。了解绘图位置是相对于JPanel内部的坐标。

答案 1 :(得分:1)

注意到您使用的是绝对布局(空布局)。需要Component.setbounds才能将对象放置到位。

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);

}

查看详细信息: https://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html

注意:尝试按Ctrl + Shift + F1从AWT获取调试消息。