BorderLayout
在填充单元格的内部创建面板是一种简单的方法吗?
这是一个简单的示例,我希望灰色面板 ( pnlTitle
) 与包含单元格 (100 像素) 一样宽,但我不想这样做pnlTitle.setPreferredSize(new Dimension(100, 20));
这是代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestCode2_InsideColumn {
public static void main(String[] args) {
JFrame window = new JFrame("Test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 200);
window.setMinimumSize(new Dimension(350, 150));
JPanel panelMain = new JPanel(new BorderLayout());
window.add(panelMain);
JLabel labelN = new JLabel("North");
panelMain.add(labelN, BorderLayout.NORTH);
JLabel labelS = new JLabel("South");
panelMain.add(labelS, BorderLayout.SOUTH);
GridBagLayout innerLayout = new GridBagLayout();
GridBagConstraints innerConstraints = new GridBagConstraints();
//Second (and last) column won't have fixed size, so last number is useless
innerLayout.columnWidths = new int[] {100, 100};
JPanel innerPanel = new JPanel(innerLayout);
innerPanel.setBackground(new Color(0, 220, 250));
panelMain.add(innerPanel, BorderLayout.CENTER);
innerConstraints.anchor = GridBagConstraints.NORTHWEST;
innerConstraints.weightx = 0.0;
innerConstraints.weighty = 0.0;
innerConstraints.gridx = 0;
innerConstraints.gridy = 0;
JLabel lblTitle = new JLabel("Title");
JPanel pnlTitle = new JPanel(new BorderLayout());
pnlTitle.add(lblTitle);
innerLayout.setConstraints(pnlTitle, innerConstraints);
innerPanel.add(pnlTitle);
innerConstraints.gridx = 1;
innerConstraints.weightx = 1.0;
innerConstraints.fill = GridBagConstraints.HORIZONTAL;
JLabel lblDescription = new JLabel("Label");
innerLayout.setConstraints(lblDescription, innerConstraints);
innerPanel.add(lblDescription);
window.setVisible(true);
}
}