我想知道使用mig布局实现相对常规布局的“最佳”方式。 我有大型组件(比如说,在这种情况下是JLists),以及两个大组件之间的按钮。所以我想要一个垂直的按钮堆栈,底部有一个空隙。我已经做了几次,但是
所以,我想用miglayout实现这个演示:
+---------------+ +----+ +----------------------+
| list 1 | | bt1| | list2 |
| | +----+ | |
| | +----+ | |
| | | bt2| | |
| | +----+ | |
| | +----+ | |
| | | bt3| | |
| | +----+ | |
| | | |
| | | |
+---------------+ +----------------------+
目前,我这样做:
add(new JScrollPane(jlist1),"grow, pushy");
add(button1,"flowy, aligny top, split 3");
add(button2, "");
add(button3, "");
add(new JScrollPane(jlist2), "grow, pushy");
有没有更好的方法呢?是否值得避免创建一个用于放置按钮的面板?
答案 0 :(得分:4)
我只是把按钮放在自己的面板上。这简化了布局,类似的组件往往会被一起修改,因此最好将它们放在单独的函数或类中。
我尽可能尝试使用容器的树状结构,而不是包含所有组件的复杂布局。当一切都依赖于其他一切的布局时,它会使阅读和重新排列更难。
答案 1 :(得分:0)
对于仍在为这种布局而苦苦挣扎的人:您可以使用MigLayout
来完成此操作,而无需额外的JPanel
作为按钮容器:
/**
* Simple assign panel layout.
*/
public class AssignView extends JPanel {
private JScrollPane scrollPane;
private JScrollPane scrollPane_1;
private JList<Object> list;
private JList<Object> list_1;
private JButton btnNewButton;
private JButton btnNewButton_1;
private JButton btnNewButton_2;
private JButton btnNewButton_3;
/**
* Create the panel.
*/
public AssignView() {
initialize();
}
private void initialize() {
setLayout(new MigLayout("", "[grow][][grow]", "[grow,top]"));
add(getScrollPane(), "cell 0 0,grow");
add(getBtnNewButton(), "flowy,cell 1 0");
add(getScrollPane_1(), "cell 2 0,grow");
add(getBtnNewButton_2(), "cell 1 0");
add(getBtnNewButton_1(), "cell 1 0");
add(getBtnNewButton_3(), "cell 1 0");
}
private JScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new JScrollPane();
scrollPane.setViewportView(getList());
}
return scrollPane;
}
private JButton getBtnNewButton() {
if (btnNewButton == null) {
btnNewButton = new JButton("New button");
}
return btnNewButton;
}
private JScrollPane getScrollPane_1() {
if (scrollPane_1 == null) {
scrollPane_1 = new JScrollPane();
scrollPane_1.setViewportView(getList_1());
}
return scrollPane_1;
}
private JButton getBtnNewButton_1() {
if (btnNewButton_1 == null) {
btnNewButton_1 = new JButton("New button");
}
return btnNewButton_1;
}
private JButton getBtnNewButton_2() {
if (btnNewButton_2 == null) {
btnNewButton_2 = new JButton("New button");
}
return btnNewButton_2;
}
private JList<Object> getList() {
if (list == null) {
list = new JList<>();
}
return list;
}
private JList<Object> getList_1() {
if (list_1 == null) {
list_1 = new JList<>();
}
return list_1;
}
private JButton getBtnNewButton_3() {
if (btnNewButton_3 == null) {
btnNewButton_3 = new JButton("New button");
}
return btnNewButton_3;
}
}