我有一个可能很容易解决的问题。我使用 Intellij Idea 构建了一个 GUI 表单。现在我正在尝试更改 imageLabel JLabel 的 imageIcon。
我不太明白为什么,但是当我使用 JLabel.setIcon() 时,它既不抛出异常也不显示图像。我不知道有什么问题。这看起来是一个非常简单的命令。
(我添加了 ico.getImage().flush(); 行,因为当我在周围搜索时,人们说你必须在显示图像之前刷新图像。我实际上不知道该行的作用。)
感谢您的帮助。
public class App
{
private JPanel mainPanel;
private JPanel imagePanel;
private JPanel optionsPanel;
private JPanel palletesPanel;
private JPanel buttonsPanel;
private JPanel originalPalletePanel;
private JPanel newPalletePanel;
private JLabel originalPalleteLabel;
private JLabel newPalleteLabel;
private JPanel leftButtonsPanel;
private JPanel rightButtonsPanel;
private JButton previewButton;
private JButton revertButton;
private JButton convertImageButton;
private JButton matchPalleteButton;
private JLabel originalPalleteImageLabel;
private JLabel newPalleteImageLabel;
private JLabel imageLabel;
public static void main(String[] args)
{
App app = new App();
JFrame frame = new JFrame("Pixel Pigeon");
frame.setContentPane(new App().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
pigeon pigey = new pigeon();
try
{
app.loadImage(frame, app);
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
private void loadImage(JFrame frame, App app) throws IOException
{
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION)
{
BufferedImage img = ImageIO.read(chooser.getSelectedFile());
ImageIcon ico = new ImageIcon(img);
ico.getImage().flush();
app.imageLabel.setIcon(ico);
}
}
}
最佳答案
那一小段代码存在很多问题。删除许多冗余组件后,对类的引用不明显,修复了 NullPointerException 的两个实例,删除了刷新图像的调用,并通过新创建的 修复了问题>App()
已经存在,它“有效”。但它仍然很糟糕,我建议扔掉这些东西,然后重新开始引用 JavaDocs 来研究随机人们推荐的东西,以及 Java 教程来了解 GUI 开发的基础知识。
所以这是“固定”代码:它将加载图像,但随后需要拉伸(stretch) GUI 以使图像可见。
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.ImageIO;
public class App {
private JPanel mainPanel = new JPanel();
private JLabel imageLabel = new JLabel();
public static void main(String[] args) {
App app = new App();
JFrame frame = new JFrame("Pixel Pigeon");
app.mainPanel.add(app.imageLabel);
frame.setContentPane(app.mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
try {
app.loadImage(frame, app);
}
catch(java.io.IOException e) {
e.printStackTrace();
}
}
private void loadImage(JFrame frame, App app) throws IOException {
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
BufferedImage img = ImageIO.read(chooser.getSelectedFile());
ImageIcon ico = new ImageIcon(img);
app.imageLabel.setIcon(ico);
}
}
}
关于Java Swing JLabel.setIcon() 没有按我期望的方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61091516/