gpt4 book ai didi

java - 如何使JFrame内JPanel内JLabel内的BufferedImage正确刷新?

转载 作者:行者123 更新时间:2023-11-30 03:47:41 26 4
gpt4 key购买 nike

这是我的代码:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.*;

public class FlatShadingDemo {

static BufferedImage myPicture;
static JLabel pic;
static int width = 800;
static int height = 450;
static Random r = new Random();

private static void initialise() {
JFrame frame = new JFrame("Flat shading demo");

JPanel layout = new JPanel();
layout.setLayout(new BoxLayout(layout,BoxLayout.Y_AXIS));
frame.getContentPane().add(layout);

myPicture = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

pic = new JLabel(new ImageIcon(myPicture));

JButton button = new JButton("Refresh");
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
render();
}
}
);

layout.add(pic);
layout.add(button);

frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
initialise();

render();

}

public static void render() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
myPicture.setRGB(x, y, new Color(r.nextInt(256),r.nextInt(128),r.nextInt(25)).getRGB());
}
}
}
}

当我运行它时,会生成并显示图像。当我单击“刷新”时,在调整窗口大小之前不会发生任何情况。我需要刷新 myPicture、pic、layout 和frame 中的哪一个,其函数名称是什么?我对 Swing 和图形完全陌生,因此我们将不胜感激。

最佳答案

更改:

public void actionPerformed(ActionEvent e) {
render();
}

致:

public void actionPerformed(ActionEvent e) {
render();
pic.repaint();
}

Component.repaint()的详细信息是:

Repaints this component.

If this component is a lightweight component, this method causes a call to this component's paint method as soon as possible. Otherwise, this method causes a call to this component's update method as soon as possible.

关于java - 如何使JFrame内JPanel内JLabel内的BufferedImage正确刷新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25217416/

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