我刚刚开始摇摆。我正在尝试制作图库应用。我正在获取手动导入的图像并显示它们。根据我在参数中输入的列数,可以计算出图像的尺寸以正确显示。但是,在经过一定数量的行之后,我想要一个可以滚动并显示其余图像的滚动条。
图像可以按照我的意愿正确显示,但是我尝试实现滚动条,但是它没有出现。
您能告诉我我的代码有什么问题吗?
GUI(String title, int width, int height, int columns) {
this.frame = new JFrame();
this.frameWidth = width;
this.columns = columns;
// set Frame's size
frame.setSize(width, height);
// set Frame's action on close button clicked
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set Frame's title
frame.setTitle(title);
frame.setResizable(false);
// set Frame's position at screen's center
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width / 2 - frame.getSize().width / 2, (dim.height / 2 - frame.getSize().height / 2));
panel = new JPanel();
frame.setLayout(new GridLayout());
this.scrollBar = new JScrollPane();
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollBar, BorderLayout.EAST);
displayImages();
frame.setContentPane(panel);
}
displayImages():
private void displayImages() {
for (File currentImage : getImagesList()) {
// 5 is flowlayout's default borders
// 2 because we got left and right borders
int totalBorders = (columns * 5) * 2;
int buttonWidth = (frameWidth - totalBorders) / columns;
ImageIcon image = new ImageIcon(new ImageIcon(currentImage.getAbsolutePath()).getImage().getScaledInstance(buttonWidth - 20, buttonWidth - 50, Image.SCALE_DEFAULT));
JButton button = new JButton(currentImage.getName());
button.setPreferredSize(new Dimension(buttonWidth, buttonWidth));
button.setIcon(image);
button.setHorizontalTextPosition(AbstractButton.CENTER);
button.setVerticalTextPosition(AbstractButton.BOTTOM);
button.addActionListener(e -> onImageClicked(currentImage.getName()));
panel.add(button);
}
}
谢谢,问候
答案 0 :(得分:1)
panel = new JPanel();
frame.setLayout(new GridLayout());
this.scrollBar = new JScrollPane();
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollBar, BorderLayout.EAST);
displayImages();
frame.setContentPane(panel);
上面的代码大部分是错误的。您需要:
基本代码应类似于:
//panel = new JPanel( new GridLayout(0, 1) );
layout = new GridLayout(0, 1);
panel = new JPanel( layout );
displayImages();
//frame.setLayout(new GridLayout());
this.scrollBar = new JScrollPane(panel);
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.add(scrollBar, BorderLayout.EAST);
//displayImages();
//frame.setContentPane(panel);
此外,也无需考虑面板上每个组件的尺寸。 GridLayout将使所有按钮的大小相同。
编辑:
当您想增加GridLayout中的列时,只需执行以下操作:
layout.setColumns( layout.getColumns() + 1 );
panel.revalidate(); // this invokes the layout manager
//panel.repaint(); // sometimes needed to force repainting of panel.