将两个面板彼此相邻对齐

时间:2014-04-05 18:00:26

标签: java swing alignment jpanel layout-manager

我目前正在尝试创建一个脚本编辑器。但是行号JPanel未在JTextArea旁边顶部对齐。 lineNumber JPanel显示在JTextArea右侧的中心。

看起来像这样:

enter image description here

这是实例化这两个组件的类:

private ScriptEditor() {

    ((FlowLayout) this.getLayout()).setVgap(0);
    ((FlowLayout) this.getLayout()).setHgap(0);

    //This is the lineNumber JPanel which has no LayoutManager set.
    lineNumPanel = new LineNumberPanel();

    //I tried setAlignmentY but it did not work
    lineNumPanel.setAlignmentY(TOP_ALIGNMENT);

    //The text area.
    scriptArea = new JTextArea(22,15);
    scriptArea.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
    scriptArea.setMargin(new Insets(3, 10, 3, 10));


    //This JPanel contains the two components: lineNumber JPanel and the JTextArea
    JPanel temp = new JPanel();
    temp.add(lineNumPanel);
    temp.add(scriptArea);

    //Set the scrollPane
    JScrollPane scrollPane = new JScrollPane(temp);
    scrollPane.setPreferredSize(new Dimension(width, height));

    //Add the scrollPane to this JPanel.
    add(scrollPane);
}

1 个答案:

答案 0 :(得分:1)

JPanel temp = new JPanel();

默认情况下,JPanel使用FlowLayout。 FlowLayout垂直居中添加到面板的组件。如果您不喜欢这种行为,请尝试使用不同的布局管理器,例如水平BoxLayout,这样您就可以根据垂直对齐的组件对齐顶部/中心/底部的组件。

但是,使用JPanel并不是最好的方法。相反,您应该将行号组件添加到滚动窗格的row header。有关此方法的示例,请参阅Text Component Line Number