【发布时间】:2020-09-13 05:55:21
【问题描述】:
我正在编写一个“图像查看器”应用程序,其中包含一个包含图像的中心区域,以及它周围的工具栏等。
我选择了一个 GridBagLayout 以获得我需要的灵活性,但是一旦主窗口缩小,而不是让滚动条出现在图像周围,整个滚动窗格就会折叠到 0x0px 区域。
请在下面找到一个最小代码来说明这一点。尝试将尺寸保留为 500x500,并通过向内拖动其中一个角将窗口缩小几个像素:
import javax.swing.*;
import java.awt.*;
public class ScrollTest3 {
private static final int IMG_WIDTH = 500; // 50 or 500 or 2000
private static final int IMG_HEIGHT = 500; // 50 or 500 or 2000
private static GridBagConstraints getScrollPaneConstraints() {
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.weightx = 1;
c.weighty = 1;
// With the next line, shrinking the window makes scrollbars appear ok,
// ... but making it larger causes the scrollpane to stick at the top left
// Without the next line, enlarging the window keeps image centered,
// ... but making it smaller causes the scrollpane to collapse
//c.fill = GridBagConstraints.BOTH;
return c;
}
public static void addComponentsToPane(Container container) {
container.setLayout(new GridBagLayout());
// Add top bar
container.add(new JLabel("This would be a top bar with information"), new GridBagConstraints());
// Prepare main image panel
JPanel imagePanel = new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
// Image replaced by a shape for demonstration purpose
g2d.drawOval(0, 0, IMG_WIDTH, IMG_HEIGHT);
}
public Dimension getMinimumSize() {
return new Dimension(IMG_WIDTH, IMG_HEIGHT);
}
public Dimension getPreferredSize() {
return new Dimension(IMG_WIDTH, IMG_HEIGHT);
}
public Dimension getMaximumSize() {
return new Dimension(IMG_WIDTH, IMG_HEIGHT);
}
};
JScrollPane scrollableImagePanel = new JScrollPane(imagePanel);
container.add(scrollableImagePanel, getScrollPaneConstraints());
}
private static void limitAppSize(JFrame frame) {
frame.pack();
Dimension preferred = frame.getSize();
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
Rectangle bounds = env.getMaximumWindowBounds();
preferred.width = Math.min(preferred.width, bounds.width);
preferred.height = Math.min(preferred.height, bounds.height);
frame.setSize(preferred);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("ScrollTest3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
limitAppSize(frame);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
}
正如您在注释掉的行中看到的那样,可以通过为“填充”字段指定 GridBagConstraints.BOTH 来“修复”它,但随后较小的图像(尝试使用 50x50)不再居中:-(
有没有办法指定:
- 如果图像小于显示区域,则应居中
- 如果图像大于显示区域,滚动窗格应填满整个显示区域
?
【问题讨论】:
标签: java swing window jscrollpane gridbaglayout