【问题标题】:Align two panels next to eachother将两个面板彼此相邻对齐
【发布时间】:2014-05-18 01:20:31
【问题描述】:

我目前正在尝试创建一个脚本编辑器。但是 lineNumber JPanelJTextArea 旁边不是顶部对齐的。 lineNumber JPanel 出现在JTextArea 右侧的中心。

看起来像这样:

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

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);
}

【问题讨论】:

  • 为什么不使用一些已经制作好的代码编辑器文本区域,比如 RSyntaxTextArea?它很容易使用,而且比你用这种方式做的任何事情都要好。

标签: java swing alignment jpanel layout-manager


【解决方案1】:
JPanel temp = new JPanel();

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

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

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    相关资源
    最近更新 更多