java repaint闪烁,Java Canvas repaint()闪烁

So I finally got a Canvas to work the way I want it but it flickers constantly, repaint() is run 20 times a second and the flicking does lessen when I make it run 10 times a second.

package pd.data;

import java.awt.BorderLayout;

import javax.swing.JFrame;

import javax.swing.JPanel;

import pd.areas.MainMenu;

@SuppressWarnings("serial")

public class Main extends JFrame implements Runnable {

private JPanel contentPane = new JPanel();

private Thread gameThread = new Thread(this);

public boolean running = false;

@SuppressWarnings("unused")

private int current = PDU.PD_MAIN_MENU;

private MainMenu mainmenu;

public Main() {main.setTitle("PD");

main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

main.setLocation(SPU.screenWidth / 2 - SPU.windowSize.width / 2,

SPU.screenHeight / 2 - SPU.windowSize.height / 2);

main.setResizable(false);

main.setVisible(true);

contentPane.setLayout(new BorderLayout(0, 0));

contentPane.setPreferredSize(SPU.windowSize);

main.setContentPane(contentPane);

main.pack();

mainmenu = new MainMenu();

contentPane.add(mainmenu, BorderLayout.CENTER);

this.gameThread.start();

}

@Override

public void run() {

running = true;

while (running) {

{

mainmenu.repaint();

}

try {

Thread.sleep(SPU.TSU);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

public static void main(String[] args) {

new Main();

}

}

And below is my MainMenu class:

package pd.areas;

import java.awt.Canvas;

import java.awt.Color;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.IOException;

import javax.imageio.ImageIO;

@SuppressWarnings("serial")

public class MainMenu extends Canvas{

BufferedImage img = null;

public MainMenu() {

this.setBackground(Color.BLACK);

}

public void paint(Graphics graphics){

try {

img = ImageIO.read(this.getClass().getResource(

"/image.png"));

} catch (IOException e1) {

e1.printStackTrace();

}

graphics.drawImage(img, this.getWidth() / 2 - img.getWidth()/2, 50, null);

}

}

Although the flicker is actually a nice effect, it's going to effect the whole canvas and not just the image I'm guessing, how can I fix the flicker?

解决方案

Don't use java.awt.Canvas. Use a JPanel instead.

Draw in the JPanel's paintComponent method.

Don't forget to call your super's painting method which for paintComponent would be super.paintComponent(graphics)

Never try to read in an image from within any painting method. That will slow down painting and make your program seem unresponsive. Why keep reading in the same image over and over again anyway? Read it in once and save it to a variable.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值