【发布时间】:2022-01-11 19:46:46
【问题描述】:
我开始了一个国际象棋项目,重用一些旧代码来绘制地图,基本上所有内容都已复制粘贴。问题是方块不显示?我现在尝试修复它一段时间,但没有解决方案。这可能是三个最重要的方法和整个项目的 zip。其中一些是德语。
https://drive.google.com/file/d/1nnZHLB0Ycy04eMyYbEmduMwbGhVLZ2VB/view?usp=sharing
public SchachFrame() {
super();
contentPane = new JPanel();
setContentPane(contentPane);
setBounds(0, 0, window.width, window.height);
contentPane.setBackground(Color.darkGray);
contentPane.setVisible(true);
ge = new GameEnvironment(this);
ge.setBounds(window.width/2 - 500, window.height/2 - 500, 1000, 1000);
ge.setVisible(true);
contentPane.add(ge);
Thread gameEnvironment = new Thread(ge);
gameEnvironment.start();
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void createMap(int width, int length, GameEnvironment ge) {
map = new Spielfeld[length][width];
Spielfeld.width = 1000/width;
Spielfeld.height = 1000/length;
for(int i = 0; i < length; i++) {
for(int j = 0; j < width; j++) {
this.map[i][j] = new Spielfeld(j, i, null);
this.map[i][j].setBounds(ge.getX() + j * Spielfeld.width, ge.getY() + i * Spielfeld.height, Spielfeld.width, Spielfeld.height);
this.map[i][j].setVisible(true);
ge.add(this.map[i][j]);
}
}
}
public void paintComponent(Graphics g) {
if((this.px + this.py) % 2 == 0) {
g.setColor(Color.blue);
} else {
g.setColor(Color.cyan);
}
g.fillRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
repaint();
}
【问题讨论】:
-
setBounds()在 Swing 代码中始终是一个问题。不要使用它,使用布局管理器。 -
无需自定义绘画。只需在创建组件时设置背景。查看:stackoverflow.com/questions/6811247/… 的基本示例,展示了这种方法以及在板上拖动组件的简单逻辑。
标签: java swing jframe chess jcomponent