gpt4 book ai didi

java - JPanels 在重叠期间闪烁

转载 作者:行者123 更新时间:2023-12-01 23:16:51 25 4
gpt4 key购买 nike

我正在尝试制作一个在屏幕顶部随机显示 JPanel 的程序。这些 JPanel 包含笑脸的 PNG BufferedImage(通过重写 PaintComponent)。不幸的是,每当我运行程序并且面板被绘制在有任何重叠的位置时,图像就会开始闪烁(似乎是尝试同时显示自己而不是合成)。我做了一些研究并尝试解决这个问题,但没有成功。我的代码如下:

public class MainScreen extends JFrame{

public MainScreen ms;
private Smiley smileyPanel;
private int randomPosition;
public AlphaComposite ac;
private Graphics2D graphicsPane;


//main method
public static void main (String[] args){
MainScreen ms = new MainScreen();
}

//this is my attempted fix to the program
protected void Paint (Graphics g){
Graphics2D graphicsPane = (Graphics2D) g;
ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
graphicsPane.setComposite(ac);

super.paint(g);
}

//this creates the main frame and also starts creating smileys at the top
public MainScreen(){
super("Main Screen Window");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);

this.setSize(500,800);
this.getContentPane().setBackground(Color.black);
this.setLayout(null);

createSmiley(); createSmiley(); createSmiley(); createSmiley(); createSmiley(); createSmiley();

this.setVisible(true);
}
//random number generator used to place an image at the top

public void setRandomPosition(){
Random generator = new Random();
randomPosition = generator.nextInt(473);
}

//this is the method to create an image at a random location at the top
public void createSmiley(){
smileyPanel = new Smiley();
this.add(smileyPanel);
setRandomPosition();
smileyPanel.setBounds(randomPosition, 0, 28, 29);
}
}

和我的其他类(class):

public class Smiley extends JPanel{

private BufferedImage smileyFace;
private Dimension smileyPosition;
private File smileyFile;

public Smiley() {
//this is the code to retrieve the smiley file
try{
smileyFile = new File("C:\\Users\\Devon\\Desktop\\smiley.png");
smileyFace = ImageIO.read(smileyFile);
}
catch (Exception e){
System.out.println("There was an error finding or reading the file \" smiley.png.\"");
}
}

//override of paintComponent method in order to display the grabbed image file onto a JPanel
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(smileyFace, 0, 0, null);
super.setBackground(null);
super.setSize(28,29);
}
}

最佳答案

  1. 绘画方法仅用于绘画。您不应该在绘画方法中设置组件的属性。

  2. 你为什么还要进行定制绘画?您可以只使用带有图标的 JLabel。

关于java - JPanels 在重叠期间闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21092627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com