【发布时间】:2015-10-25 15:10:04
【问题描述】:
我正在尝试在 JPanel 中将图像设置为背景并将其调整为所需的大小。
这是我选择图像并将其设置为背景的 MyPanel:
public class MyPanel extends JPanel {
Image img;
public MyPanel(LayoutManager l) {
super(l);
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String sname = file.getAbsolutePath();
img = new ImageIcon(sname).getImage();
double xRatio = img.getWidth(null) / 400;
double yRatio = img.getHeight(null) / 400;
double ratio = (xRatio + yRatio) / 2;
img = img.getScaledInstance((int)(img.getWidth(null) / ratio), (int)(img.getHeight(null) / ratio), Image.SCALE_SMOOTH);
}
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, Color.WHITE, null);
}
}
这是我的框架:
public class MyFrame extends JFrame {
public MyFrame () {
initUI();
}
private void initUI() {
MyPanel pnl = new MyPanel(null);
add(pnl);
setSize(600, 600);
setTitle("My component");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MyFrame ex = new MyFrame ();
ex.setVisible(true);
}
});
}
}
问题是图像一开始没有显示。例如,当我稍微改变帧大小时,它会显示。
这样:
【问题讨论】:
-
考虑使用
g.drawImage(img, 0, 0, Color.WHITE, this); -
谢谢。它可以工作,但它会在 2 秒后显示。是不是因为处理imgae需要这么多时间?
-
是的,或多或少,有很多事情发生,第一个是缩放操作,第二个是可能将图像转换为可以更好显示的格式(颜色型号)
-
顺便说一句,为什么在 MyPanel pnl = new MyPanel(null); 内有
null
标签: java swing jcomponent