【发布时间】:2015-02-23 22:38:51
【问题描述】:
我是一名新手编码员,当我在处理一个包含 JFrame、JPanel 和 JLabel 的项目时,我遇到了一些奇怪的问题,即 JLabel 出现在两个地方,我将它设置为在顶部 -框架的左角,而不是它应该在的位置。
这是代码的基本大纲:
import java.awt.event.*; // for key listener
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import javax.swing.*;
import java.util.Random;
public class Game extends JFrame {
JFrame Game;
JLabel label;
GamePanel panel; // GamePanel class is the panel class that extends JPanel
public Game(String title) {
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(420 + 110,420 + 220);
this.setLocationRelativeTo(null);
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
this.setResizable(false);
label = new JLabel("Score : " + score);
label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
label.setAlignmentY(JLabel.CENTER_ALIGNMENT);
panel = new GamePanel(..appropriate variables);
this.add(panel);
this.add(label);
this.add(Box.createRigidArea(new Dimension(0,50)));
panel.setFocusable(true);
panel.addKeyListener(new KeyHandler());
}
// some variables..
class KeyHandler extends KeyAdapter {
public void keyPressed(KeyEvent e)
{
int keycode = e.getKeyCode();
switch(keycode) {
//cases for arrow keys, which will update the variable that panel uses
}
//some other tasks for the game..
panel.updateVariables(...appropriate variables to update);
panel.repaint();
label.setText("Score : " + score);
}
}
public static void main(String [] args) {
Game me = new Game("GAME");
me.setVisible(true);
}
}
所以问题的总结是,每当 setText 实际更新标签时,标签似乎出现在两个地方:JFrame 的左上角和我指定它显示的位置。有趣的是,左上角的“buggy”标签也会随着真实标签的更新而更新。
提前致谢!
编辑:这是 GamePanel 的布局。
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.BasicStroke;
public class GamePanel extends JPanel
{
// some variables..
// setXxx methods for corresponding variables
void drawCursor(int x, int y)
{
//draws thicker rectangle around the selected position
//uses setStroke, setColor, and draw(Rectangle)
}
public void paintComponent( Graphics g )
{
Graphics2D g2 = (Graphics2D) g;
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
switch(gameGrid[j][i]) { // I have an array grid[][] that has information of which color goes into the specific position of the grid
// each case will setColor the corresponding color and use g2.fill(new Rectangle(...));
case 0:
g2.setColor(...);
g2.fill(new Rectangle(...));
break;
// and so on
}
g2.setColor(Color.BLACK);
g2.draw(new Rectangle(50 + (j * 420/size), 50 + (i * 420/size), 420/size,420/size));
}
}
drawCursor(x, y);
}
}
【问题讨论】:
-
将组件(标签、面板等)添加到框架的代码在哪里?
-
@MarsAtomic 哎呀,忘了在这里复制它。它位于构造函数的末尾。我的错。我编辑了它应该在的地方。
-
GamePanel覆盖paint或paintComponent但没有调用super.paintXxx -
@MadProgrammer 我对 java 还是很陌生,所以你介意解释一下它覆盖
paintComponent但不调用super.paintXxx是什么意思吗? -
向我们展示
GamePanel...您所描述的可以通过在执行自定义绘画时打破绘画链来实现
标签: java swing jframe jpanel jlabel