2

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

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

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

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

2 回答 2

4

看起来像一个严重的嵌套丢失案例:-)

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

  • 具有不同管理器的深层容器
  • 只有一个孩子的容器

在您的情况下,除了顶级边框布局之外的所有内容都有一个“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)

遇到的问题:

  • 文本区域是单行的,没有换行
  • 文本区域居中

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

  • 经理不应该的部分是 textArea 默认情况下不换行,您必须明确配置它才能这样做。由于管理器(== FlowLayout)的部分原因是它总是根据他们的 prefSize 布置它的孩子,没有别的。这归结为有一个固定的孩子大小,无论有多少空间可供父母使用。因此,即使 textArea 被配置为换行,它也会保持初始大小,无论其父级可以得到多宽。
  • 内部 FlowLayout 对齐其子级...居中。因此,您在 BoxLayout 级别上设置的任何对齐方式都没有任何效果。胶水不是这样:只有当其他孩子/人在该维度上具有最大尺寸时,它才会占用所有多余的空间(带有 FlowLayout 的面板没有,仅仅是因为简单的 LayoutManager 没有最大,只有 LayoutManager2 类型的管理器有)

是时候退后一步并查看初始要求了:

垂直列出的多个文本区域,其宽度不超过 JScrollPane 的宽度,以及所需的高度

零阶解是

  • 根据需要配置 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 特征的方法。

于 2012-09-18T09:28:24.863 回答
3

首先,我不认为Box应该与其他任何东西一起使用BoxLayout(我可能是错的,但这就是我的阅读方式)

就个人而言,我会使用其中一个GridBagLayoutVerticalLayout来自 SwingLabs。

为了方便横向限制,你还会想看看Scrollable界面,特别是getScrollableTracksViewportWidth

于 2012-09-17T19:56:41.023 回答