我正在构建一个 Java 应用程序。 GameView 有一个 BoardView,其中包含多个 PawnView(在示例中只有一个)。
例子:
public class GameView extends Frame
{
public GameView()
{
AWTUtilities.setWindowOpaque(this, false);
this.setUndecorated(true);
this.setLayout(null);
this.setResizable(false);
this._boardview = new BoardView();
int x = 0;
int y = 0;
PawnView pv = new PawnView();
this._boardview.AddPawn(pv, 10, 10);
this._boardview.MovePawn(pv, 20, 10);
}
}
public class BoardView extends JPanel
{
public BoardView()
{
this.setOpaque(false);
RepaintManager.currentManager(null).setDoubleBufferingEnabled(true);
this.setLayout(null);
}
@Override
public void update(Graphics g)
{
paint(g);
}
public void AddPawn(PawnView pawnview, int x, int y)
{
this.add(pawnview);
pawnview.setLocation(x, y);
}
public void MovePawn(PawnView pawnview, int x, int y)
{
pawnview.setLocation(x, y);
//this.repaint();
}
}
public class PawnView extends JLabel
{
public PawnView()
{
this.setOpaque(false);
RepaintManager.currentManager(null).setDoubleBufferingEnabled(true);
this.setLayout(null);
}
}
最初一切看起来都很棒(没有 MovePawn):
http://dl.dropbox.com/u/7438271/1.png
当我调用 MovePawn 时,它看起来像:
http://dl.dropbox.com/u/7438271/2.png
我尝试调用 this.revalidate()
、this.updateUI()
、this.repaint()
、this .paintImmediately()
以各种形式出现,但它们都使情况变得更糟:整个 JPanel 都变成了白色背景。
我还尝试重写 JPanel 的 paintComponent 函数,同样没有效果。
这只发生在 Mac OS X(完全更新)上,但我在 Windows 中也遇到了一些重绘问题。
有人可以帮忙吗?
最佳答案
您的代码不可运行,
1) 不要将 AWT Frame 与 Swing JComponents 混合使用,不确定(从未测试过)但我认为 AWTUtilities仅针对 Swing JComponent,则
public class GameView extends Frame
可能是
public class GameView extends JFrame
2)
this._boardview = new BoardView();
必须是
BoardView _boardview = new BoardView();
3) 为什么有代码行,
RepaintManager.currentManager(null).setDoubleBufferingEnabled(true);
我看到用于打印的代码 where is for faster printing turn double buffering off, but value currentManager(null)
, simply doesn't make any sense
4) 不要使用public void update(Graphics g)
,这个方法在API内部使用,使用paintComponent
代替
5) 使用 JComponents
移动使用 Swing Timer调用 repaint()
6) JLabel默认透明移除 this.setOpaque(false);
7) JLabel还没有实现任何LayoutManager , 删除 this.setLayout(null);
关于java - 在 JPanel 重绘上更改位置 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9743529/