我有一个方法返回一个jpanel,其布局类似于图像轮播。我已经检查过,直接应用这个代码在单个JPanel
上正常工作。但是同样的布局正在多个地方使用。因此,我想创建一个通用方法来设置此布局,并返回jPanel
。这是我写的方法:将一个Jpanel的内容添加到另一个 - Java Swings
public static JPanel loadImages(String Location) throws IOException{
JPanel ImagePanel = new JPanel();
File directory = new File(Location);
ImageIcon image;
String[] imageFiles = directory.list();
DefaultListModel model = new DefaultListModel();
JLabel lab1=new JLabel();
JCheckBox chkbox ;
ImagePanel.setLayout(new GridBagLayout());
for (int ii=0; ii<imageFiles.length; ii++) {
GridBagConstraints constraint = new GridBagConstraints();
image = new ImageIcon(imageFiles[ii]);
lab1 = new JLabel(image);
constraint.gridx = ii;
constraint.gridy =0;
ImagePanel.add(lab1,constraint);
}
for (int ii=0; ii<imageFiles.length; ii++) {
GridBagConstraints constraint1 = new GridBagConstraints();
constraint1.anchor = GridBagConstraints.SOUTH;
chkbox = new JCheckBox(imageFiles[ii]);
constraint1.gridx = ii;
constraint1.gridy =1;
ImagePanel.add(chkbox, constraint1);
}
return ImagePanel;
}
我的想法是,在所有的地方,这是需要的地方,我将有一个JScrollPane已经在UI设置。我想调用这个方法返回这个JPanel,我想把它添加到滚动窗格中。
private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {
jScrollPane3.add(loadImages("C://users//images"));
jScrollPane3.revalidate();
jScrollPane3.repaint();
}
但是没有显示。是否因为布局未设置?
不jScrollPane3使用什么样的布局? –
我没有设置布局。所以我猜测默认的布局.. – Nemo