Do I actually call the paintComponent method I make when creating a rectangle in Java?

后端 未结 3 531
滥情空心
滥情空心 2021-01-21 00:49

This is my current RectangleComponent class and I add it to a panel in my main JFrame but it never appears. I thought it wasn\'t drawing so I decided to call the paintComponent

3条回答
  •  难免孤独
    2021-01-21 01:31

    Your code is a bit creative, a bit crazy, and with logic that is very hard to follow. The most unusual aspect is that it has two JFrames, one called "frame", and one the GameFrame object itself, both of which get components added, but only one of which shows. You also have many methods that return void (which if over-used increases code smell) and only add to making the code more confusing.

    For example,

    public GameFrame(char x) {
    
      // here you set up the "frame" JFrame
      frame.setSize(1024, 768);
      frame.setTitle("Game");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
      FlowLayout layout = new FlowLayout();
      createPanels(x);
      healthPanel.setLayout(layout);
      buttonPanel.setLayout(layout);
      mainPanel.setLayout(layout);
    
      // here you add content to the frame JFrame, and pack it
      frame.getContentPane().add(mainPanel);
      frame.pack();
      repaint();  // and then call repaint on the "this" JFrame?
    }
    
    public RectangleComponent getLife() {
      return life;
    }
    
    private void createHealth() {
      life = new RectangleComponent(green, healthPanel);
      death = new RectangleComponent(red, healthPanel);
    }
    
    private void createPanels(char x) {
      add(healthPanel); // now you add content to the "this" JFrame
      pack();  // and pack it
      createBar(x);
      createHealth();
      mainPanel.add(buttonPanel);
      mainPanel.add(healthPanel); // and then re-add a JPanel into a second JPanel?
      healthPanel.add(death);
      healthPanel.add(life);
      buttonPanel.add(bar.getSpell1());
      buttonPanel.add(bar.getSpell2());
      buttonPanel.add(bar.getSpell3());
      add(mainPanel); // and then re -add the mainPanel into the "this" JFrame???
    }
    

    This is all very confusing, and not likely going to work.

    Then there's your trying to call paintComponent directly and calling getGraphics on a JComponent, both of which should not be done. You will want to go through the graphics tutorials to see how to do this correctly.

    I recommend that you consider re-writing this, and first and foremost, using only one JFrame, and organizing your code better.

提交回复
热议问题