下面的代码将我的问题重现为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的解决方案的解决方案:
添加以下代码,在末尾创建一个'filling'不可见组件:
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);
一种选择可能是在panel
的末尾添加填充符JPanel
,并具有以下约束:
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weighty = 1.0;
panel.add(new JPanel(), gridBagConstraints);