【问题标题】:Why my objects doesn't show up on JPanel/Java为什么我的对象没有出现在 JPanel/Java 上
【发布时间】:2020-11-21 15:30:57
【问题描述】:

我试图在 JPanel 上显示 2 个对象坦克,坦克使用 ImageIcon 获取图像。 JPanel 出现了,但我的坦克没有。我找不到我错在哪里。我的一个朋友把代码发给我,他可以显示坦克,但我的电脑无法显示。

我的坦克类获取图像

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";
}

}

我的班级画图

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);
}

我的主要课程

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);
}

}

【问题讨论】:

    标签: java swing jframe jpanel


    【解决方案1】:
    JPanel pan = new JPanel();
    DrawTanks tanks = new DrawTanks();
    this.add(tanks);
    

    为什么要创建“pan”对象?

    默认情况下,JPanel 使用符合面板大小的 FlowLayout。

    在您使用的 DrawTanks 类中:

    setPreferredSize(new Dimension(100,200));
    

    随机设置面板的大小。

    然后你创建坦克:

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

    每个水箱的位置在面板的首选尺寸之外。所以坦克可能是涂漆的,但它们在面板的边界之外,所以你看不到它们。

    解决办法:

    1. 摆脱“平移”窗格,只需将 DrawTanks 面板直接添加到框架中
    2. 为您的 DrawTanks 提供一个合理的首选尺寸,以便可以绘制添加到其中的所有组件。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多