鉴于我的要求:
- JPanel 的单个垂直列。
- 设置 JPanel 的垂直位置*,而不使用同级面板的属性。
- 调整框架大小时,组件位置和大小是固定的。
- 尽可能保持其他布局方面的自动化(例如首选尺寸计算)
(*) 位置: 我的意思是 Component.setLocation(x, y) 中的位置.
是否有一个显而易见的解决方案,如果这是 GridBagLayout,该怎么做?
详细信息:
我想通过仅指定组件的垂直位置将组件垂直放置在列容器(如垂直框)中。在不失去 BoxLayout 等布局的其他优点的情况下,最好的方法是什么?
在垂直框中,必须使用 filler 设置组件的垂直位置。 ,或者通过调整上面组件的大小,就不存在这样的可能性:
panel.setLocation(getLocation().x, y)
另一方面,使用无布局容器让我负责任务管理:
- 组件的初始大小
- 容器大小调整事件。
这里是null layout的解决方案推荐,这里这是一个custom一,这是 GridBagLaout 。另外,MIGLayout 似乎是通用的(但我不希望在我的项目中添加另一个库)。
最佳答案
我为也正在寻找相同要求的人编写了以下程序。
注意:确保将第一个元素添加到 0 位置,因为不会有更多组件,并且除了 0 之外没有其他位置可用,第二个元素添加到 0 或 1,第三个元素添加到 0 或 1 或 2 等等上
public class VerticalList extends JFrame {
JPanel pnl = null;
TextField tf = new TextField(10);
Box center = Box.createVerticalBox();
JScrollPane jsp = new JScrollPane(center);
JPanel ctrl = new JPanel(new FlowLayout());
JButton send = new JButton("Send");
public VerticalList() {
jsp.setAutoscrolls(true);
ctrl.add(send);
ctrl.add(new JLabel("Position:"));
ctrl.add(tf);
Container cnt = getContentPane();
cnt.add(jsp, BorderLayout.CENTER);
cnt.add(ctrl, BorderLayout.SOUTH);
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pnl = new JPanel(new FlowLayout());
pnl.setBorder(BorderFactory.createLineBorder(Color.red));
pnl.add(new JLabel("Added to Position: "+tf.getText()));
pnl.setMaximumSize(new Dimension(Integer.MAX_VALUE, (int)pnl.getPreferredSize().getHeight()));
try{
int index = Integer.parseInt(tf.getText());
center.add(pnl, index);
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Please Provide a Valid position", "Position Error", JOptionPane.ERROR_MESSAGE);
}
validate();
}
});
setPreferredSize(new Dimension(300, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
pack();
}
public static void main(String[] args) {
new VerticalList();
}
}
关于java - 垂直JPanel手动定位: which layout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26083606/