gpt4 book ai didi

java - 将 JPanel 排列在 ScrollPane 顶部,而不是居中

转载 作者:太空宇宙 更新时间:2023-11-04 14:40:02 24 4
gpt4 key购买 nike

以下代码将我的问题重现为 SSCCE。我想在 JScrollPane 内创建一个垂直可滚动的 JPanels 列表。我的实际代码将 JPanels 居中对齐,但它应该在顶部对齐。我该怎么做,非常感谢任何帮助。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class TestingWindow {

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setBounds(100, 100, 150, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

JPanel panel = new JPanel();
GridBagLayout gbl_panel = new GridBagLayout();
panel.setLayout(gbl_panel);
scrollPane.setViewportView(panel);

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.NORTH;
gbc.weightx = 1;

gbc.fill = GridBagConstraints.HORIZONTAL;

JPanel panelToAdd = new JPanel();
JLabel label = new JLabel("Test 1");
panelToAdd.setBackground(Color.blue);
panelToAdd.add(label);
panelToAdd.setAlignmentY(Component.TOP_ALIGNMENT);
panel.add(panelToAdd, gbc, -1);
panel.revalidate();

JPanel panelToAdd2 = new JPanel();
JLabel label2 = new JLabel("Test 2");
panelToAdd2.setBackground(Color.green);
panelToAdd2.add(label2);
panel.add(panelToAdd2, gbc, -1);
panel.revalidate();

JPanel panelToAdd3 = new JPanel();
JLabel label3 = new JLabel("Test 3");
panelToAdd3.setBackground(Color.yellow);
panelToAdd3.add(label3);
panel.add(panelToAdd3, gbc, -1);
panel.revalidate();
frame.setVisible(true);
}
});
}

}

基于@MadProgrammer解决方案的解决方案:

添加以下代码以在末尾创建“填充”不可见组件:

    GridBagConstraints gbc_finish = new GridBagConstraints();
gbc_finish.gridwidth = GridBagConstraints.REMAINDER;
gbc_finish.anchor = GridBagConstraints.NORTH;
gbc_finish.weighty = 1;
JPanel panelToAdd4 = new JPanel();
panelToAdd4.setOpaque(false);
panel.add(panelToAdd4, gbc_finish, -1);
panel.revalidate();

最佳答案

您是否尝试过将它们放置在边框布局的北部面板中?

frame.getContentPane().add(scrollPane, BorderLayout.NORTH);

关于java - 将 JPanel 排列在 ScrollPane 顶部,而不是居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25057740/

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