search

Home  >  Q&A  >  body text

java - 为什么长方形没有显示在GUI里?

求大神帮个忙,为什么长方形没有显示在GUI里?哪里出错了?

public class SelectSeat {
    
    static JFrame frame;

    public JPanel createContentPane() throws IOException
    {
        
        JPanel totalGUI = new JPanel();
        RectDraw rect= new RectDraw();
        rect.setPreferredSize(new Dimension(30,25)); 
        totalGUI.setLayout(null);
        totalGUI.setBackground(Color.WHITE);
        totalGUI.add(rect);
        
        return totalGUI;
    }
    
        void setVisible(boolean b) {
        // TODO Auto-generated method stub
        
    }
    
    static void createAndShowGUI() throws IOException
    {

        JFrame.setDefaultLookAndFeelDecorated(true);
        frame = new JFrame("Seat Selection");
        //Create and set up the content pane.
        SelectSeat demo = new SelectSeat();
        frame.setContentPane(demo.createContentPane());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(535, 520);
        frame.setLocation(500,220);
        frame.setVisible(true);
    }
    
    private static class RectDraw extends JPanel
    {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);  
             g.drawRect(29,550,300,250);  
             g.setColor(Color.GRAY);  
             g.fillRect(20,5,330,25); 
             g.setColor(Color.BLUE);
             g.drawString("Movie Sceen", 150, 20);   
            }
        

    }

}

大家讲道理大家讲道理2893 days ago314

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-18 09:25:41

    The reason is the problem caused by totalGUI.setLayout(null);, I also thought it was strange at first

    Later I referred to this question http://stackoverflow.com/questions/12308764/java-setlayoutnull

    Solution, one is not to use setLayout(null);, use layout manager instead

    Or use one of the ideas answered in the above question to add a bound to the object you want to display to prevent the display range from being invisible to the naked eye

        public JPanel createContentPane() throws IOException {
    
            JPanel totalGUI = new JPanel();
            RectDraw rect = new RectDraw();
            rect.setPreferredSize(new Dimension(30, 25));
            totalGUI.setLayout(null);
            totalGUI.setBackground(Color.WHITE);
            totalGUI.add(rect);
            Dimension d = rect.getPreferredSize();
            rect.setBounds(10, 20, d.width, d.height);
            return totalGUI;
        }

    reply
    0
  • Cancelreply