我正在编写Java应用程序并试图绘制BufferedImage。在我的主要内容中,JFrame正在创建,JPanel正在创建并被添加到JFrame中。还有一个正在启动的线程正在重绘,但它什么也没有显示,我的System.out.println()在paintComponent中也没有被调用。我搜索了很多,但我没有找到解决我的问题。JPanel中的PaintComponent未被调用
我在做什么错,为什么错了?
我的代码:
主+主题:
public class Main extends Thread
{
public static Frame frame = new Frame();
public static void main(String[] args) throws IllegalStateException, IOException
{
frame.activePanel = new LoginPanel();
frame.add(frame.activePanel);
new Main();
}
public Main()
{
this.start();
}
@Override
public void run()
{
while(true)
{
if(Main.frame.activePanel != null)
Main.frame.activePanel.repaint();
try{Thread.sleep(15);}catch(InterruptedException e){}
}
}
}
JFrame中:
public class Frame extends JFrame
{
public JPanel activePanel = null;
public Frame()
{
super();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(this.getToolkit().getScreenSize().width/2 - 640,this.getToolkit().getScreenSize().height/2 - 400,1279,799);
this.setResizable(false);
this.setUndecorated(true);
this.setVisible(true);
}
}
和JPanel的:
public class LoginPanel extends JPanel
{
BufferedImage loginImg;
public LoginPanel() throws IOException
{
loginImg = ImageIO.read(new File("src/images/Login.PNG"));
}
@Override
protected void paintComponent(Graphics g)
{System.out.println("painting");
g.drawImage(loginImg, 0, 0, null);
}
}
对此不太确定......但如果您不覆盖paintComponent,会发生什么情况? – Frakcool
同样,我得到一个白色/灰色的窗口。可悲的是,这样我不能检查它是否被调用。 – Geosearchef
哇,哇!在处理Swing中的线程时必须小心,也不需要定期调用repaint,如果在绘制完成后添加/删除组件,则需要调用repaint。请阅读[如何在swing中使用线程](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html),您只能从[Event dispatch thread](http:/ /docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html)。 – DSquare