【问题标题】:JScrollPanes, JTextAreas, and maximum sizesJScrollPanes、JTextAreas 和最大尺寸
【发布时间】:2012-06-29 05:43:24
【问题描述】:

上下文:在抽认卡应用程序中,我有一个CardData(表示抽认卡一侧的数据结构)的视图。它的最基本形式是String text。视图(称为CardDataView)由textJScrollPane 内的不可编辑JTextArea 组成。

有一次,我需要(垂直)排列一堆这些CardDataViews,所以我把它们放在垂直的Box

问题是:当我从“首选”大小(由pack 确定)扩展窗口然后将其缩小时,JScrollPane 添加了一个水平滚动条并允许我在文本字段中水平滚动.本质上,它会在不应该的时候调整文本区域的大小。

这是我的代码(精简和简化):

public class DebugTest {

    public static void main(String[] args) {
        CardDataView cdv = new CardDataView(new CardData(
                "Lorem ipsum dolor sit amet filler filler filler"));
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(cdv), BorderLayout.CENTER);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

}

class CardData {
    private String text; // text on the card

    /*
     * NOTE: This class has been simplified for SSCCE purposes. It's not really
     * just a String field in production; rather, it has an image and other
     * properties.
     */

    public CardData(String text) {
        super();
        this.text = text;
    }

    public String getText() {
        return text;
    }

}

class CardDataView extends Box {
    private JTextArea txtrText; // the text area for the text

    /*
     * NOTE: As with CardData, this class has been simplified. It's not just a
     * JTextArea; it's also an ImageView (custom class; works fine), among other
     * things.
     */

    public CardDataView(CardData data) {
        super(BoxLayout.Y_AXIS);
        txtrText = new JTextArea();
        txtrText.setLineWrap(true);
        txtrText.setRows(3);
        txtrText.setEditable(false);
        txtrText.setWrapStyleWord(true);
        final JScrollPane scrollPane = new JScrollPane(txtrText);
        add(scrollPane);
        txtrText.setText(data.getText());
    }
}

现在,真正让我感到困惑的事情(除非我做错了)是,如果我基本上内联数据和视图类,只需创建一个带有文本和滚动的文本区域窗格(即使设置相同的行数、相同的换行设置等),它的行为也符合预期。会发生什么?

关注点: - 所有进口都井然有序。 - 如果您想知道为什么CardLayoutViewBox:在生产中,它不仅仅是一个文本框。当它是JPanel 而我是setLayout 而不是super 时,也会发生同样的错误。 - 如果我根本不使用CardData 类(并手动设置文本区域的文本),也会发生同样的故障。

有什么想法吗?

【问题讨论】:

  • “内联数据和视图类”是什么意思
  • 您是否尝试过使用GridBagLayoutGridBagConstraints.VERTICAL/NONE 作为gridBagLayoutObject.fill 值,而不是在CardDataView 类中选择BoxLayout?由于您将此类添加到JFrameCENTER 和此处BorderLayout 不尊重CENTER 组件恕我直言的preferredSize()。而是尝试将此添加到JPanel,然后将此JPanel 放在JFrameCENTER
  • 删除根滚动窗格,您的示例运行良好。现在我会按照 nIcEcOw 的建议使用 GridBagLayout 而不是 BoxLayout。

标签: java swing jscrollpane gridbaglayout sizing


【解决方案1】:

回答我的评论:

使用GridBagLayoutGridBagConstraints.VERTICAL/NONE 作为gridBagLayoutObject.fill 值,而不是BoxLayout。因为在向JFrameCENTER 添加组件时,BorderLayout 永远不会尊重preferredSize()CENTER 组件。因此尝试将你的东西添加到JPanel,然后将这个JPanel 放在JFrameCENTER 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多