java - 将 JScrollPane 的组件向左对齐?

标签 java swing layout alignment jscrollpane

目前,我有一个 JScrollPane 嵌套在具有 BorderLayout 的面板中。更重要的是,在 JScrollPane 中,我打算垂直列出多个文本区域,其宽度不超过 JScrollPane 的宽度,以及它们需要的高度(滚动 Pane 只有一个垂直滚动条)。

我的问题是,相对于最大的文本区域,文本区域似乎在 JScrollPane 中居中,并且它们都是一行。

谁能告诉我,看看我的代码,如何让文本区域在滚动 Pane 的右侧之前换行,以及如何将它们左对齐?

private JPanel generateStateView(State state) {
        //Create a new panel, and the info label.
        JPanel container = new JPanel(new BorderLayout());
        JLabel infoLabel = new JLabel("The state of " + state.getName() + 
                ", with " + state.getElectoralVotes() + " Electoral Votes.");
        container.add(infoLabel, BorderLayout.NORTH); //Put the label on top.
        //Will scroll through polls.
        JScrollPane pollViewer = new JScrollPane();
        //This will be the scroll pane's "viewport".
        JViewport pollViewport = new JViewport();
        //And finally, this will actually hold the individual polls.
        JPanel pollPanel = new JPanel(new GridLayout(
                state.getPolls().size(), 1));
        pollPanel.setAlignmentX(LEFT_ALIGNMENT);
        //Iteratively add the polls to the container
        for (Poll poll : state.getPolls()) {
            //Holds individual polls
            Box pollBox = Box.createHorizontalBox();
            //Create the poll's panel and add it to the poll container.
            pollBox.add(generatePollPanel(poll));
            pollBox.add(Box.createHorizontalGlue()); //Fill to the right
            pollBox.setAlignmentX(LEFT_ALIGNMENT);
            pollPanel.add(pollBox); //Put the box into the pollPanel.
        }
        //Put the panel into the viewport.
        pollViewport.add(pollPanel);
        //Put the viewport "into" the scroll pane
        pollViewer.setViewport(pollViewport);
        //Put the pane into the state view.
        container.add(pollViewer, BorderLayout.CENTER);
        return container; //And give back the container.
    }

    /**
     * Method: generatePollPanel
     * Purpose: Generates a panel containing information on a particular poll.
     * @param poll The poll to have information generated from.
     * @return The JPanel.
     */
    private JPanel generatePollPanel(Poll poll) {
        //Create a new panel, then a text area to fill with the info.
        JPanel pollPanel = new JPanel();
        JTextArea pollInfo = new JTextArea("Conducted by " + poll.getAgency() + 
                " on day " + poll.getDate() + " for " + poll.getNumDays() + 
                " days, " + poll.getPercentVoteDem() +
                "% voted Democrat, and " + poll.getPercentVoteRep() +
                "% voted Republican.");
        pollInfo.setEditable(false); //We don't want the user editing this.
        pollPanel.add(pollInfo); //Throw the area in, and return the panel.
        pollPanel.setAlignmentX(LEFT_ALIGNMENT);
        return pollPanel;
    }

    /**
     * Method: valueChanged
     * Purpose: Handle the event of a different list item being selected.
     * @param event The object containing information about this event.
     */
    public void valueChanged(ListSelectionEvent event) {
        //Instantiating JList with a type of ? seems to solve the issue of
        //eclipse complaining about an unchecked cast (originally to
        //JList<String>, so I should be able to cast child values directly
        //to string later on anyways.
        JList<?> stateList = (JList<?>) event.getSource();
        //Account for keyboard and mouse actions
        if (!event.getValueIsAdjusting()) {
            State chosenState; //Keep track of the picked state.
            try {
                //Try to get the currently selected state
                chosenState = db.findState((String) stateList.getSelectedValue());
            }
            catch (NoSuchElementException exception) {
                //Somehow the picked state was not found, notify the user.
                reportError("The selected state is not available.");
                return;
            }
            //Find the container for the gui window.
            Container container = getContentPane();
            //Remove the empty state view container by generating a new one.
            container.remove(currentStateView);
            //Generate the state view and add that to the container.
            currentStateView = generateStateView(chosenState);
            container.add(currentStateView, BorderLayout.CENTER);
            //Redraw everything.
            revalidate();
        }
    }

最佳答案

看起来像是一个严重的嵌套迷路:-)

虽然嵌套可以是实现布局要求的一种方法,但如果它没有给出预期的输出,则很难找出到底出了什么问题。此外,还有一般警告信号表明嵌套基本上有问题

  • 深层次的容器,管理人员千差万别
  • 只有一个子容器的容器

在您的情况下,除了顶级 borderlayout 之外的所有布局都有一个“netto”(即,不是为了解决布局问题)子级,其级别为:

BorderLayout (the state view)
   GridLayout (the panel that's the scrollPane's view)
      BoxLayout (the panel that contains a single pollBox)
         FlowLayout (the panel that contains the textArea)

遇到的问题:

  • 文本区域是单行且不换行
  • 文本区域居中

都是由于 LayoutManager 的特性造成的,部分(第一)或完全(第二):

  • 不属于管理器的部分是 textArea 默认情况下不会换行,您必须显式配置它才能这样做。归因于管理器(== FlowLayout)的部分是它总是根据其子级的 prefSize 对其进行布局,仅此而已。归根结底,无论父级有多少可用空间,子级的大小都是固定的。因此,即使将 textArea 配置为换行,它也会坚持初始大小,无论其父级可以达到多宽。
  • 内部 FlowLayout 将其子项...居中对齐。因此,您在 BoxLayout 级别上设置的任何对齐方式都不会产生任何效果。胶水则不然:如果其他子级在该维度上具有最大尺寸(带有 FlowLayout 的面板没有,仅仅因为它是简单的 LayoutManager,那么它只占用所有 多余的空间)没有 max 的概念,只有 LayoutManager2 类型的管理器有)

是时候退后一步并审查最初的要求了:

multiple text areas listed vertically, with a width that does not exceed the JScrollPane's, and as much height as they need

零阶解是

  • 根据需要配置textArea
  • 扔掉所有布局嵌套(在scrollPane内)

在代码中:

JComponent overview = new JPanel(new BorderLayout());
overview.add(new JLabel("All polls for state XY"), BorderLayout.NORTH);

JComponent pollPanel = new JPanel(); 
pollPanel.setLayout(new BoxLayout(pollPanel, BoxLayout.PAGE_AXIS));
for (int i = 0; i < 10; i++) {
    pollPanel.add(generatePollTextArea(i)); //Put the box into the pollPanel.
}
pollPanel.add(Box.createVerticalGlue());
JScrollPane pollViewer = new JScrollPane(pollPanel);
overview.add(pollViewer);
showInFrame(overview, "layout text only");

protected JComponent generatePollTextArea(int i) {
    String agency = "agency ";
    // simulates different size text
    for (int j = 0; j < i; j++) {
        agency += i;
    }
    String text = "Conducted by " + agency + 
            " on day " + "today" + " for " + 20 + 
            " days, " + 99 +
            "% voted Democrat, and " + 0.2 +
            "% voted Republican.";
    JTextArea pollInfo = new JTextArea(text); 
    // give it some reasonable initial width
    // in terms of content
    pollInfo.setColumns(20);
    pollInfo.setLineWrap(true);
    pollInfo.setWrapStyleWord(true);
    pollInfo.setEditable(false); //We don't want the user editing this.
    return pollInfo;
}

“Das Wort zum Dienstag”:嵌套布局并不是避免学习嵌套布局各个级别上使用的 LayoutManager 特征的方法。

关于java - 将 JScrollPane 的组件向左对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12465600/

相关文章:

java - 在没有字段绑定(bind)的情况下使用表单错误?

java - JComboBox 未出现在窗口中

java - 从 JDK 中删除了 Swing?

java - 将行动态添加到单独文件中的表布局

java - 如何生成不重复的随机布局

java - 线程 "main"java.lang.NoClassDefFoundError : org/apache/commons/codec/DecoderException 中的异常

java - 有没有支持esmtp管道的java api?

java - 相当于 Scala dropWhile

java - 窗口关闭和 JFrame 的单个实例

Java Swing 元素大小和定位问题