简体   繁体   中英

Why can't I draw in a JPanel?

public void display() {

    pan.repaint();
    fen.add(pan);
    fen.addKeyListener(this);
    fen.setResizable(false);
    fen.setTitle("Le Jeu 2D");
    img.setText("Coucou");
    pan.add(img);
    pan.repaint();
    pan.setBackground(Color.yellow);
    fen.setVisible(true);
    fen.setSize(480, 272);
    pan.repaint();
    fen.revalidate();

}

public void paintComponent(Graphics g) {

    System.out.println("zzz");
    pan.paint(g);
    g.setColor(Color.red);
    g.drawRect(10, 10, 10, 10);
}

It doesn't draw anything. Why? I have defined the paint component method, so I don't understand why. Edit: I edited my code, please take a look

You don't create an instance of your Game class and don't add it to the JFrame .

Here is the Game panel which you are painting on:

Game.java

public class Game extends JPanel {
    @Override
    public final void paintComponent(final Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.red);
        g.drawRect(10, 10, 10, 10);
    }

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(300, 300);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }

    @Override
    public Dimension getMaximumSize() {
        return new Dimension(300, 300);
    }
}

You then need to create an instance of this Game panel and add it to your JFrame:

GameFrame.java

public class GameFrame extends JFrame {
    public GameFrame() {
        setLocationRelativeTo(null);
        setResizable(false);
        setTitle("2D Game");
        Game game = new Game();
        setContentPane(game);
        pack();
        setVisible(true);
    }
}

Then when you create an instance of the JFrame:

Example.java

public class Example {
    public static void main(String[] args) {
        new GameFrame();
    }
}

The panel will be added, and painted:

在此处输入图片说明

You never create an instance of the Game class and you never add the Game class to the frame. Even if you did create an instance the size would still be (0, 0) so there would be nothing to paint.

Basically the whole structure of your code is wrong.

I suggest you start over and start with the demo code found in the Swing tutorial on Custom Painting .

The basic structure of your code seems weird. You could instantiate a JFrame in your main control class , ie. it should be GAME class in this case. Then you can create a new JPanel class and add its object into the JPanel object. Within the JPanel class, you can create all the elements you need and set corresponding parameters. You could also add the event listener in an inner class or a separate class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM