JPanel setBackground(Color.BLACK) does nothing

前端 未结 6 1107
不知归路
不知归路 2021-01-04 12:29

I have the folowing custom JPanel and I have aded it to my frame using Netbeans GUI builder but the background won\'t change! I can see the circle, drawing with g.fillOval()

6条回答
  •  逝去的感伤
    2021-01-04 12:49

    I just tried a bare-bones implementation and it just works:

    public class Test {
    
        public static void main(String[] args) {
                JFrame frame = new JFrame("Hello");
                frame.setPreferredSize(new Dimension(200, 200));
                frame.add(new Board());
                frame.pack();
                frame.setVisible(true);
        }
    }
    
    public class Board extends JPanel {
    
        private Player player = new Player();
    
        public Board(){
            setBackground(Color.BLACK);
        }
    
        public void paintComponent(Graphics g){  
            super.paintComponent(g);
            g.setColor(Color.red);
            g.fillOval(player.getCenter().x, player.getCenter().y,
                 player.getRadius(), player.getRadius());
        } 
    }
    
    public class Player {
    
        private Point center = new Point(50, 50);
    
        public Point getCenter() {
            return center;
        }
    
        private int radius = 10;
    
        public int getRadius() {
            return radius;
        }
    }
    

提交回复
热议问题