我在正确使用挥杆布局时遇到了麻烦。
我正在尝试实现类似screenshot1的东西,但是我得到了类似screenshot2的东西。
请在下面查看我的源代码。
我哪里错了?我怎样才能实现我想要的(如截图1)。
注意:当我多次运行代码时,有时我会得到正确的表和树之间的对齐。看起来像这里的比赛条件。
截图1
截图2
源代码:
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.util.Date;
public class SwingLayoutTest {
private static final int screenWidth;
private static final int screenHeight;
static {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenWidth = screenSize.width;
screenHeight = screenSize.height;
}
public static void main(String[] args) throws Exception {
JFrame mainWindow = new JFrame();
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setSize(800, 600);
mainWindow.setExtendedState(JFrame.MAXIMIZED_BOTH);
Container contentPane = mainWindow.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS));
JTree tree = createTree();
tree.setPreferredSize(new Dimension(screenWidth/2, screenHeight));
JScrollPane scrollTree = new JScrollPane(tree);
JTable table = createTable();
table.setPreferredSize(new Dimension(screenWidth/2, screenHeight));
table.getColumnModel().getColumn(1).setWidth(100);
table.getColumnModel().getColumn(2).setWidth(100);
JScrollPane scrollTable = new JScrollPane(table);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollTree, scrollTable);
contentPane.add(splitPane);
mainWindow.setVisible(true);
}
private static JTree createTree(){
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("This is root Node");
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
rootNode.add(child1);
child1.add(new DefaultMutableTreeNode("Child 1 1"));
child1.add(new DefaultMutableTreeNode("Child 1 2"));
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");
rootNode.add(child2);
child2.add(new DefaultMutableTreeNode("Child 2 1"));
child2.add(new DefaultMutableTreeNode("Child 2 2"));
return new JTree(rootNode);
}
private static JTable createTable(){
String[] columnNames = {"Name", "Size", "Modified Time"};
Object[][] data = {{"This is row 1","1000", new Date()},
{"This is row 2", "5455", new Date()}};
return new JTable(data, columnNames);
}
}