滚动条未出现在 JList 上



我使用的是GridBagLayout,并且有一个自定义类的JListJList本身正如我所期望的那样显示,但滚动条没有出现。(我的数据大小也大于我的JList的大小。(我检查了许多相关链接,他们都提到了这两行,但这对我不起作用。

JScrollPane scrollPane = new JScrollPane(list); 
add(scrollPane);

完整代码:

import java.awt.Button;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Label;
import javax.swing.*;
public class UserPart extends JFrame {
Label messageL = new Label("Confirm an item for more options.");
Button confirmB = new Button("Confirm");
Button backB = new Button("Back");
DefaultListModel<User2> model;
public UserPart() {
JList<User2> list = new JList<User2>();
model = new DefaultListModel<User2>();
for (int i = 0; i < MainActivity2.arr.size(); i++) {
User2 u = new User2();
u.setForShow(i);
model.addElement(u);
}
// SETTING THE APPEARANCE OF THE JLIST
list.setModel(model);
list.setCellRenderer(new MyListCellRenderer());
list.setLayoutOrientation(JList.VERTICAL);
list.setPreferredSize(new Dimension(500, 750));
//////////////////////////////////////////////    
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("List of users");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.gridx = 0;
gbc.gridy = 0;
this.add(messageL, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
this.add(list, gbc); //ADDED JLIST TO LAYOUT HERE
JScrollPane scrollPane = new JScrollPane(list); // DEFINED SCROLL BAR HERE
add(scrollPane); // ADDED SCROLL BAR TO LAYOUT HERE
setSize(1000, 1500);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

将约束权重(weightxweighty(设置为大于零的值-使用所有布局-还将fill设置为BOTH。不要将列表直接添加到框架中,只需添加滚动窗格,并如上所述设置约束。不要将AWT组件(Label(与Swing组件混合使用,而是使用JLabel。总结如下:

JLabel label = new JLabel("Confirm an item for more options.");
JScrollPane scroll = new JScrollPane(list);
GridBagConstraints gbc = new GridBagConstraints();
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
frame.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
frame.add(scroll, gbc);

相关内容

  • 没有找到相关文章

最新更新