How do I make my custom Swing component visible?

后端 未结 2 532
孤城傲影
孤城傲影 2020-12-11 23:48

I have no idea why it won\'t show. First I create an instance of the component and then add it to a certain element in a two-dimensional JPanel array. Then I loop through th

2条回答
  •  猫巷女王i
    2020-12-12 00:23

    In the past, I have solved this by extending JPanel instead of JComponent. I found an good example here. Here's an adaptation of it which will draw a box:

    public class Box extends JPanel {
      Color color;
    
      public Box (Color c, int w, int h) {
        color = color;
        setSize(w, h);
      }
    
      @Override
      public void paintComponent(Graphics g) {
        g.setColor(color);
        g.drawOval(0, 0, getWidth(), getHeight());
     }
    
     ...
    

    This isn't exactly like your code above, but hopefully it'll get you started in the right direction!

    A quick note (original response): the example above View is a JFrame which is never made visible. Instead, the class variable gameWindow is used. It would be good practice to make the top-level class the visible window.

提交回复
热议问题