当前位置: 首页 > 知识库问答 >
问题:

将JScrollPane的组件向左对齐?

慕容雅珺
2023-03-14

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

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

共有1个答案

杨良才
2023-03-14

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

虽然it嵌套是实现布局需求的一种手段,但如果它不能提供预期的输出,就很难找出到底哪里出了问题。此外,还有一般的警告信号,表明嵌套基本上出了问题

  • 具有不同管理器的容器的深层
  • 只有一个子容器
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)
    null
    null

是时候后退一步,回顾一下婚姻要求了:

垂直列出的多个文本区域,宽度不超过JScrollPane的宽度,高度随需要而定

零阶解是

    null
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;
}
 类似资料:
  • 问题内容: 我需要在JScrollPane中内容的 左侧 放置一个滚动条。是否可以在没有单独的JScrollBar组件的情况下完成?也许只是通过设置一些对齐方式? 问题答案: 通过反复试验,我发现 像魅力一样运作。

  • 问题内容: 我正在开发我的第一个Swing应用程序,并且遇到了有关对话框窗口的布局问题,该对话框窗口是我为用户创建的,以便在某些字段中输入值。由于显示的字段数根据用户的选择而有所不同,因此我在对话框中使用了JScrollPane,将其视口设置为要添加字段组件的面板。 对于要显示的每个字段,我创建并添加三个组件: “字段名称”标签 字段组件(通常是JTextField,但也可以是JComboBox或

  • 问题内容: 我有可变长度的刻度标签,我想将它们向左对齐(即,较短的标签和y轴之间有一个空格)。有什么合理的方法可以做到这一点吗?使用水平对齐方式“向左”会将其向左对齐,但是它们都从轴开始,因此最终在绘图内。因此,另一个问题可能是- 我可以更改其起点吗? 演示代码: 问题答案: 您只需要添加一个。查看matplotlib刻度相对于轴的位置 (文件) 确定垫子应该是什么:

  • 问题内容: 我正在尝试向JTable中的特定列添加滚动功能。我已经实现了一个自定义的TableCellRenderer组件,并且可以看到表中的滚动窗格很好,但是我无法滚动它。我也尝试实现TableCellEditor,但没有任何运气。 有谁知道如何使包含scrollPane的单元格可滚动? 问题答案: 使用TableCellRenderer不可能添加任何滚动行为,因为它不接收任何事件,仅绘制组件。

  • 我试图将一个JLabel和一个JScrollPane(包含一个JTextArea)对齐到一个JPanel的左边。当我把JTextArea直接放在面板中时,对齐是正确的。只有当JTextArea在滚动窗格中时,对齐方式才不正确。 下面的第一个图像带有滚动窗格,第二个图像没有滚动窗格。如何正确对齐滚动窗格?

  • 问题内容: 我希望整个块都以其父对象为中心,但是我希望块的内容保持对齐。 例子最有用 在本页面 : http://yaml-online- parser.appspot.com/?yaml=%23+ASCII+Art%0d%0a—+%7c%0d%0a %5c%2f%2f%7c%7c%5c% 2f%7c%7c%0d%0a %2f%2f +%7c%7c ++%7c%7c __%0d%0a&type =