gpt4 book ai didi

java - 最终使用滚动条的 JPanel 列表

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:21 25 4
gpt4 key购买 nike

我正在尝试为我的 Java 应用程序构建一个 GUI。我动态添加 JPanel,这是我 GUI 中的“行”。在面板列表下,有一个用于添加新面板的按钮。随着 List 的增长,它会到达父 Container 的末尾。然后我想使用滚动条,以便用户能够到达列表中的每个面板。

到目前为止,我尝试了 JScrollPanes 和 Layouts,但我不知道如何让它工作。

你能给我一些建议吗?

this.setLayout(new BorderLayout());
JPanel listContainer = new JPanel();
listContainer.setLayout(BoxLayout(listContainer, BoxLayout.Y_AXIS);

this.add(new JScrollPane(listContainer), BorderLayout.CENTER);
this.add(new JButton(), BorderLayout.PAGE_END);

//then i add panels to the listContainer. this wont work, when the space is complettly used there is no scrollbar.

最佳答案

很难从您的代码片段中准确断言您可能遇到问题的地方。

enter image description here

public class DynamicPanelList {

public static void main(String[] args) {
new DynamicPanelList();
}

public DynamicPanelList() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private JPanel mainList;

public TestPane() {
setLayout(new BorderLayout());

mainList = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
mainList.add(new JPanel(), gbc);

add(new JScrollPane(mainList));

JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
panel.add(new JLabel("Hello"));
panel.setBorder(new MatteBorder(0, 0, 1, 0, Color.GRAY));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
mainList.add(panel, gbc, 0);

validate();
repaint();
}
});

add(add, BorderLayout.SOUTH);

}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}

您确实需要提供一个 SSCCE这将使我们能够诊断您遇到的问题。

就个人而言,这取决于您的要求,更好的布局管理器可能是来自 SwingLabs SwingX 库的 VerticalLayout

关于java - 最终使用滚动条的 JPanel 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14615888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com