我有一个 GUI,其中左侧包含图像,右侧是包含一些标签对象的面板。我想要它,以便如果右侧面板上的对象多于无法容纳的对象,则会出现一个滚动条。
我遇到的问题是,当将大量对象添加到右侧面板时,整个框架会调整大小。
这是一些屏幕截图。第一个是我希望窗口始终保持的大小,第二个图像显示了调整大小的问题。
第二张图片:
这是包含图像面板和侧栏面板的面板的代码:
/**
* image panel - displays image and editing area
*/
ImagePanel imagePanel = null;
// Holds the labels
private LabelHolder lHolder = new LabelHolder();
/**
* handles New Object button action
*/
public void addNewPolygon() {
imagePanel.addNewPolygon(null);
}
public ContainerPanel(String imageFilename, JFrame frame) {
//setup main window panel
addComponents(imageFilename, frame);
}
public void addComponents(String imageFilename, JFrame frame) {
setLayout(new FlowLayout());
// Polygon Title
JLabel labelPanelTitle = new JLabel("<html><b>Polygons</b></html>");
labelPanelTitle.setBorder(new EmptyBorder(0, 0, 0, 150));
Font f = new Font("LabelPanel", Font.PLAIN, 24);
labelPanelTitle.setFont(f);
labelPanelTitle.setAlignmentX(CENTER_ALIGNMENT);
// Create and set up the image panel.
try {
imagePanel = new ImagePanel(imageFilename, frame, this);
} catch (Exception e1) {
e1.printStackTrace();
}
imagePanel.setOpaque(true); //content panes must be opaque
JPanel objectsPanel = new JPanel();
objectsPanel.setLayout(new BoxLayout(objectsPanel, BoxLayout.Y_AXIS));
JPanel labelHolderContainer = new JPanel();
labelHolderContainer.setLayout(new BoxLayout(labelHolderContainer, BoxLayout.Y_AXIS));
labelHolderContainer.add(lHolder);
JScrollPane scroller = new JScrollPane(labelHolderContainer);
// add the title
objectsPanel.add(labelPanelTitle);
// Add a spacer
objectsPanel.add(Box.createRigidArea(new Dimension(0,25)));
// Add all the labels
objectsPanel.add(scroller);
addNewLabel("Some Object");
addNewLabel("Some Object");
addNewLabel("Some Object");
addNewLabel("Some Object");
addNewLabel("Some Object");
addNewLabel("Some Object");
addNewLabel("Some Object");
addNewLabel("Some Object");
addNewLabel("Some Object");
addNewLabel("Some Object");
// addNewLabel("Some Object");
// addNewLabel("Some Object");
// addNewLabel("Some Object");
// addNewLabel("Some Object");
add(imagePanel);
add(Box.createRigidArea(new Dimension(10,0)));
add(objectsPanel);
}
public void addNewLabel(String labelName) {
lHolder.add(new Label(labelName, imagePanel.getCurrentColour()));
lHolder.add(Box.createRigidArea(new Dimension(10,10)));
// set new colour
imagePanel.setCurrentColour(imagePanel.getRandomColour());
}