【发布时间】:2018-04-12 08:09:30
【问题描述】:
我的代码的问题是我的图像只获得了JFrame 的开始大小 - 但我希望它在每次用户更改窗口大小时改变大小。
图像大小还应该与JFrame 大小或其JPanel 相关吗?如果是这样,我将如何实现?
这是我的代码:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class MainFrame extends JFrame {
private JPanel card1;
private JPanel principalPanel,centerPanel;
private BufferedImage image;
public MainFrame() {
setSize(800,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
URL url = null;
try {
url = new URL("https://i.stack.imgur.com/7bI1Y.jpg");
} catch (MalformedURLException e) {
}
try {
image = ImageIO.read(url);
} catch (IOException e) {
System.out.println("Can not find image");
}
Image scaledImage = image.getScaledInstance(this.getWidth(),
this.getHeight(),Image.SCALE_SMOOTH);
card1 = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(scaledImage,0,0,this);
}
};
centerPanel = new JPanel();
centerPanel.setLayout(new CardLayout());
centerPanel.add(card1,"1");
principalPanel = new JPanel();
principalPanel.setLayout(new BorderLayout());
principalPanel.add(centerPanel,BorderLayout.CENTER);
setContentPane(principalPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame();
}
});
}
}
【问题讨论】:
-
是的,@JuniorDev to hotlink 的意思是使用链接来检索项目中的图像。但请在此问题获得更多否决或关闭(或两者)之前创建一个适当的minimal reproducible example(阅读链接),并且不要忘记正确缩进。 Here 是一个如何热链接图像的示例(以及一个好的 MCVE 示例(这意味着您可以复制粘贴代码并查看相同的输出而无需执行任何操作,只需单击“运行”),您应该创建一个以及)
-
是的,我看到下次我会写一个可以理解的最小代码来总结这个问题@Andrew Thompson,再次感谢你