您可以缩小所有图像以使用更少的 RAM。例如,此代码将所有图像缩小到 200x200。这样,您可以在 100MB 中容纳 1000 张图像。
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.io.File;
public class Scroll extends JPanel {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
JPanel panel = new Scroll();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for(int i = 0; i < 10; i++) {
JPanel buttonPanel = new JPanel();
JRadioButton b1 = new JRadioButton("button 1");
JRadioButton b2 = new JRadioButton("button 2");
JRadioButton b3 = new JRadioButton("button 3");
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
group.add(b3);
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
BufferedImage buffer = new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffer.createGraphics();
BufferedImage image = ImageIO.read(new File("image.jpg"));
g.scale(buffer.getWidth()*1.0/image.getWidth(),
buffer.getHeight()*1.0/image.getHeight());
g.drawImage(image, 0, 0, null);
g.dispose();
JLabel imageLabel = new JLabel(new ImageIcon(buffer));
JSplitPane splitPane = new JSplitPane();
splitPane.add(imageLabel, JSplitPane.LEFT);
splitPane.add(buttonPanel, JSplitPane.RIGHT);
panel.add(splitPane);
}
JScrollPane spane = new JScrollPane(panel);
frame.add(spane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,600);
frame.setVisible(true);
}
}
如果要在图像可见时动态加载图像,则必须为每个图像使用空的 JPanel 而不是 ImageIcons,然后覆盖这些 JPanel 的绘制方法。只有当 JPanel 可见时才会调用paint 方法。因此,最简单的解决方案是始终以绘制方法从磁盘加载图像,然后将其绘制到屏幕上。
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.io.File;
public class Scroll extends JPanel {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
JPanel panel = new Scroll();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for(int i = 0; i < 10; i++) {
JPanel buttonPanel = new JPanel();
JRadioButton b1 = new JRadioButton("button 1");
JRadioButton b2 = new JRadioButton("button 2");
JRadioButton b3 = new JRadioButton("button 3");
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
group.add(b3);
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
JPanel imagePanel = new JPanel() {
{
BufferedImage image = ImageIO.read(new File("image.jpg"));
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
image.flush();
}
@Override
public void paint(Graphics g) {
try {
BufferedImage image = ImageIO.read(new File("image.jpg"));
g.drawImage(image, 0, 0, null);
image.flush();
} catch(Exception e) {
}
}
};
JSplitPane splitPane = new JSplitPane();
splitPane.add(imagePanel, JSplitPane.LEFT);
splitPane.add(buttonPanel, JSplitPane.RIGHT);
panel.add(splitPane);
}
JScrollPane spane = new JScrollPane(panel);
frame.add(spane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,600);
frame.setVisible(true);
}
}