gpt4 book ai didi

Java Swing 从文件选择器加载图像不显示

转载 作者:行者123 更新时间:2023-11-30 10:56:24 25 4
gpt4 key购买 nike

这是一个类作业。我应该加载一个文件并将其显示在我的 Swing 应用程序上。

我按照笔记中的过程进行操作,但它们含糊不清,我还使用了其他 stackoverflow 帖子,但我无法使其正常工作。当我加载图像时,程序不会崩溃,但不会显示任何内容。

-加载图像后是否必须重新绘制或刷新文件?我试过了,但没有用。我究竟做错了什么?重绘方法有注释。

import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Part1 {

public static File selectedFile;

public static void main(String[] args) {
JFrame frame = buildFrame();
JButton button = new JButton("Select File");
frame.add(button);

button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
selectedFile = fileChooser.getSelectedFile();
CardImagePanel image = new CardImagePanel(selectedFile);
frame.add(image);
// frame.repaint();
}
}
});
}

private static JFrame buildFrame()
{
JFrame frame = new JFrame();
frame.setSize(1000,1000);
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
return frame;
}
}

class CardImagePanel extends JPanel {
private BufferedImage image;

public CardImagePanel(File newImageFile)
{
try {
image = ImageIO.read(newImageFile);
} catch (IOException e){
e.printStackTrace();}
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 500, 500, this);
}
}

最佳答案

如前所述,您需要在添加新组件后调用 frame.revalidate();

您还应该调用 image.setPreferredSize(new Dimension(500, 500)); 或类似方法以确保您的图像不小。

关于Java Swing 从文件选择器加载图像不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33025491/

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