如何在JScrollPane中添加图像作为背景? 我试过了,但图片没有显示:
BufferedImage img = null;
try {
img = ImageIO.read(new File("C:\\Users\\Suraj\\Documents\\NetBeansProjects\\JavaApplication2\\src\\javaapplication2\\images\\2.jpg"));
}
catch (IOException e) {
e.printStackTrace();
}
Image imag = img.getScaledInstance(d.width, d.height, Image.SCALE_SMOOTH);
ImageIcon imageBack = new ImageIcon(imag);
FlowLayout fl = new FlowLayout();
frame.getContentPane().setLayout(fl);
fl.addLayoutComponent(null, new JLabel(imageBack));
编辑:我想在JScrollPane上添加带有背景的jlabels和jbuttons
答案 0 :(得分:2)
如果您的目标是只在JScrollPane中显示图像而不在JScrollPane中显示其他组件(例如JTable),那么您应该:
new ImageIcon(myImage)
你完成了。
如果您需要做其他事情,请更详细地描述您的问题。
例如,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
@SuppressWarnings("serial")
public class ImageInScrollPane extends JPanel {
public static final String IMAGE_PATH = "http://image.desk7.net/"
+ "Space%20Wallpapers/1422_1280x800.jpg";
private static final int PREF_W = 500;
private static final int PREF_H = 400;
public ImageInScrollPane() throws IOException {
URL imageUrl = new URL(IMAGE_PATH);
BufferedImage img = ImageIO.read(imageUrl);
Icon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);
JScrollPane scrollPane = new JScrollPane(label);
setLayout(new BorderLayout());
add(scrollPane);
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
ImageInScrollPane mainPanel = null;
try {
mainPanel = new ImageInScrollPane();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("ImageInScrollPane");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
你在评论中提问:
如果我必须添加按钮等其他对象怎么办?....我该怎么做?
在这种情况下,我创建了一个扩展JPanel的类,并通过在paintComponent方法覆盖中绘制它来在此JPanel中显示图像(如果你搜索它,你会发现很多例子,一些由我),然后将按钮/组件添加到此图像绘制JPanel,然后将此JPanel添加到JScrollPane的视口中,就像我上面的JLabel一样。