gpt4 book ai didi

java - JPanel 不显示图像?

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:59 25 4
gpt4 key购买 nike

我正在尝试使用 JPanel 显示图像。我有这个代码:

package training;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.plaf.SliderUI;

public class Training extends JPanel {
public static BufferedImage image;
double maxw, maxh;
double w, h, ratio;

public Training () {
super();
try {
image = ImageIO.read(new File("src/training/P.jpg"));

}
catch (IOException e)
{
//Not handled.
}
maxw = 750;
maxh = 600;
w = image.getWidth();
h = image.getHeight();

if (w > h) {
if (w > maxw) {
ratio = maxw / w;
h = h * ratio; // Reset height to match scaled image
w = w * ratio;
}

}
if (w <= h) {
if (h > maxh) {
ratio = maxh / h;
w = w * ratio; // Reset height to match scaled image
h = h * ratio;
}

}
}

public void paintComponent(Graphics g)
{
Image i = image.getScaledInstance((int)w, (int)h,Image.SCALE_SMOOTH);
g.drawImage(i, 0, 0, null);
repaint();
}

public static void main(String[] args) {

System.out.println("User dir: " + System.getProperty("user.dir"));
JPanel p = new JPanel();
JFrame f = new JFrame("Window");

f.setSize(1000, 600);
f.add(p);
p.add(new Training());
p.setSize(750, 600);
f.setVisible(true);
p.setVisible(true);
}
}

以前,当我使用 f.add(new Training()); 直接在框架上绘制时,它会起作用。无需先创建 JPanel。窗框上显示的是当时的画面。

如何让 JPanel 正确显示我的图像?

最佳答案

诀窍是将您的图片加载到“JLabel”中。您不能将图像直接放置到“JPanel”上:

import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;

public class Main extends JPanel {
public static BufferedImage image;
double maxw, maxh;
double w, h, ratio;

public Main () {
super();
try {
image = ImageIO.read(new File("src/training/P.jpg"));;
JLabel l = new JLabel(new ImageIcon(image));
add(l);
}
catch (IOException e)
{
//Not handled.
}
maxw = 750;
maxh = 600;
w = image.getWidth();
h = image.getHeight();

if (w > h) {
if (w > maxw) {
ratio = maxw / w;
h = h * ratio; // Reset height to match scaled image
w = w * ratio;
}

}
if (w <= h) {
if (h > maxh) {
ratio = maxh / h;
w = w * ratio; // Reset height to match scaled image
h = h * ratio;
}

}
}

public void paintComponent(Graphics g)
{
Image i = image.getScaledInstance((int)w, (int)h,Image.SCALE_SMOOTH);
g.drawImage(i, 0, 0, null);
repaint();
}

public static void main(String[] args) {

System.out.println("User dir: " + System.getProperty("user.dir"));
JFrame f = new JFrame("Window");
JPanel p = new Main();
f.setSize(1000, 600);
p.setSize(750, 600);
f.add(p);
f.setVisible(true);
}
}

关于java - JPanel 不显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49475048/

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