【发布时间】:2019-10-05 16:07:50
【问题描述】:
我已经制作了游戏,并希望使用矩形而不是 jlabels 使我的 GUI 看起来更好,现在我意识到只有最后绘制的矩形显示在 GUI 上
我已经尝试过不同的布局
我的 GUI 类:
public class GUI_N
{
private Spiel spiel;
private KeyEvent e;
private String beste;
private int beste1;
private DrawingComponent[][] feld;
GUI_N(){
feld = new DrawingComponent[4][4];
spiel = new Spiel();
beste1 = 0;
beste = "Highscore: "+beste1;
JFrame g=new JFrame("2048 - Main");
g.setSize(500,500);
g.setFocusable(true); //wichtig für KeyListener
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int i = 0;
int j = 0;
int h = 0;
int l = 0;
while(i<4)
{
while(j<4)
{
if(i==0){
h = 50;
}else if(i==1){
h = 100;
}else if(i==2){
h = 150;
}else if(i==3){
h = 200;
}
if(j==0){
l = 50;
}else if(j==1){
l = 100;
}else if(j==2){
l = 150;
}else if(j==3){
l = 200;
}
feld[i][j] = new DrawingComponent(l,h,50,50);
feld[i][j].setBounds(l,h,50,50);
j++;
}
j=0;
i++;
}
i = 0;
j = 0;
while(i<4)
{
while(j<4)
{
g.add(feld[i][j]);
j++;
}
j=0;
i++;
}
//g.getContentPane().setBackground(new Color(20, 40, 50));
g.setVisible(true);
}
public static void main(String[] args) {
new GUI_N();
}
}
我的矩形类:
public class DrawingComponent extends JComponent
{
private Graphics2D g2;
private int wert;
private int x;
private int y;
private int w;
private int h;
public DrawingComponent(int px,int py,int pw,int ph)
{
x=px;
y=py;
w=pw;
h=ph;
}
public void paintComponent(Graphics g)
{
g2 = (Graphics2D) g;
Rectangle rect1 = new Rectangle(x,y,w,h);
g2.setColor(Color.RED);
g2.fill(rect1);
}
public void setWert(int x)
{
wert = x;
}
public int getWert()
{
return wert;
}
}
正如我所说,只显示最后绘制的矩形。
我如何做到这一点?
【问题讨论】:
-
1) 不要忘记在
paintComponent(...)方法上调用super.paintComponent(g),这样就不会破坏绘制链。 2) 给你的变量起有意义的名字(g会混淆JFrame的名字,例如将其更改为frame,因为g经常用于Graphics对象。3)不要使用 "魔术数字”(即创建一个名为ROWS = 4和COLS = 4的常量,以便您的while-loops更易于理解。4)不要设置任何组件的边界,使用正确的Layout Managers -
5) 小心命名变量
x和y,因为你可能会遇到一个奇怪、有趣但压力很大的behavior 6) 不需要有2 个嵌套的while-loops块,您可以在它们的第一个块的j++之前添加g.add(feld[i][j]);。并且不要忘记将您的程序放在 EDT 上,请参阅 this answer 上的第 2 点