以下代码将我的问题重现为SSCCE
. 我想JPanels
在JScrollPane
. 我的实际代码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();