Add multiple Polygon objects on the same JPanel frame

后端 未结 1 914
忘掉有多难
忘掉有多难 2021-01-23 04:32

So I have a DrawStar class that draws a star using Polygon like that:

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    int[] cX =         


        
1条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 05:25

    I reproduce your problem. It was Layout problem. By default JFrame has BorderLayout with CENTER alignment. You should change your layout and screen size.

    JFrame starsframe = new JFrame();
    starsframe.setTitle("Random stars...");
    starsframe.setLayout(new GridLayout( 1,2));// Use gridLayout
    DrawStar star1 = new DrawStar(300, 200, Color.red);
    starsframe.add(star1);
    DrawStar star2 = new DrawStar(400, 300, Color.blue);
    starsframe.add(star2);
    
    starsframe.setSize(1000,700);// Increase the screen size.
    starsframe.setLocationRelativeTo(null);
    starsframe.setVisible(true);
    starsframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    

    To see the two stars I used GridLayout(1,2) and bigger setSize(1000, 700). But it is not optimum solution. You should get the x, y dynamically with corresponding to Screen Size using getWidth() and getHeight() method.

    0 讨论(0)
提交回复
热议问题