【发布时间】:2015-01-25 11:26:57
【问题描述】:
为什么在 Java 中,当我尝试将窗口从屏幕一侧移动到中心时,整个 JPanel 不会自行重新绘制?
示例:当我尝试将窗口从屏幕的一侧(因此只有大约一半的窗口可见)拖动到中心时发生了这种情况:
如果我添加一个组件监听器,然后将repaint() 放在componentMoved 方法中,它会正常工作,但每次移动窗口时它都会重新绘制。
相关代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TEST extends JFrame
{
public TEST()
{
super ("TEST!");
setSize (500,400);
setLocationRelativeTo(null);
setContentPane(new MyPanel());
addComponentListener(this);
}
class MyPanel extends JPanel
{
public void paintComponent (Graphics g)
{
super.paintComponent(g);
Graphics g2d = (Graphics2D) g;
int R = (int)(Math.random()*256);
int G = (int)(Math.random()*256);
int B= (int)(Math.random()*256);
Color color = new Color(R, G, B);
g2d.setColor(color);
g2d.fillOval(0, 0, getWidth(), getHeight());
}
}
public static void main (String[] args)
{
TEST t = new TEST();
t.setVisible(true);
}
}
【问题讨论】:
-
你似乎有一个线程竞争条件,面板已被完全绘制,但更新被......覆盖了一些新的随机颜色。确保您的 UI 是在事件调度线程的上下文中创建和启动的,有关更多详细信息,请参阅Initial Threads。另外,您使用的是什么操作系统?
-
只是一个旁注:图形 g2d = (Graphics2D) g;这种情况什么也不做(当你投射 Graphics -> Graphics2D -> Graphics)
-
@Joeblade 但是,除非你有条件,否则你不能使用
Graphics2D中的所有好东西... OP没有使用... -
@MadProgrammer 是的,我只是指出,在他的演员阵容之后,他隐含地将其转换回 Graphics(因为变量 g2d 实际上是 Graphics,而不是 Graphics2D)
-
@VinceEmigh 这可以解释条带,正如 camickr 在他的回答中指出的那样,这似乎是绘画过程中的优化问题......
标签: java swing graphics jpanel paintcomponent