简体   繁体   中英

Why my objects doesn't show up on JPanel/Java

I am trying to display 2 objects Tank on JPanel, the tank gets image with ImageIcon. The JPanel shows up but my Tanks do not. I cannot find where am i wrong. A friend of mine send me the code that he can display tanks but i cannot display it with my computer.

My Tank class to get image

public class Player extends Tank {
private Image img;

public Player(int x, int y){
    super(x, y);
    ImageIcon ii = new ImageIcon("src/TankD.gif");
    img = ii.getImage();
}

public Image getImg() {
    return img;
}
public String toString() {
    return "This is player tank";
}

}

My class to draw image

public class DrawTanks extends JPanel{  // DRAW IMAGE

private ArrayList<Tank> list = new ArrayList<>();
private Tank a;
public DrawTanks() {
    Tank t1 = new Player(100, 200);
    Tank t2 = new Bot(200, 100);
    a = t1;
    list.add(t1);
    list.add(t2);
    setPreferredSize(new Dimension(100,200));
    setLocation(new Point(200, 200));

}

@Override
public void paintComponent(Graphics g){
    for (Tank i: list)
        g.drawImage(i.getImg(), i.getX(), i.getY(), null);
}

My main class

public class Window extends JFrame{
public static void main(String[]args){
    Window win = new Window();
}
public Window(){
    JPanel pan = new JPanel();
    DrawTanks tanks = new DrawTanks();
    this.add(tanks);
    this.setTitle("Tank");
    this.setSize(900,900);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

}

JPanel pan = new JPanel();
DrawTanks tanks = new DrawTanks();
this.add(tanks);

Why are you creating the "pan" object?

By default a JPanel uses a FlowLayout which respects the panels size.

In your DrawTanks class you use:

setPreferredSize(new Dimension(100,200));

to randomly set the size of the panel.

But then you create the tanks:

Tank t1 = new Player(100, 200);
Tank t2 = new Bot(200, 100);

where the location of each tank is outside the preferred size of the panel. So the tanks are probably painted but they are outside the bounds of the panel so you can't see them.

The solution:

  1. get rid of the "pan" pane and just add your DrawTanks panel directly to the frame
  2. give your DrawTanks a reasonable preferred size so all components added to it can be painted.

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