首页 > 解决方案 > 由于 BoxLayout 中的滚动窗格,JComponent 部分隐藏

问题描述

我想为我的用户添加在表单上添加评论的可能性。为了显示它们,我在一个简单的 JScrollPane 中创建了 JPanel。我将此 JPanel 的布局设置为,BoxLayout因为我希望将它们全部添加到一列中,这似乎是调用BoxLayout.Y_AXIS构造函数的最简单方法。我也尝试过GridLayoutGridBagLayout但这不是我想要的。

我的问题是,当 JPanel 具有 BoxLayout 布局时,它的宽度自动与其容器相同,但我的容器是 JScrollPane 并且插入符号隐藏了我的评论的右侧!

一张图片胜过千言万语。

您可以在左下角看到 JTextField 和一个 JButton,这是 click 事件的代码:

private void btnAjoutCommentaireActionPerformed(java.awt.event.ActionEvent evt) {       
    //I take the text from the JTextField and format it to html                                      
    String formattedComment = "<html><br><div style='width:280px;'>" + 
            txtArCommentaire.getText().replaceAll("\n", "<br>") + 
            "</div><br></html>";

    JLabel label = new JLabel(formattedComment);
    //I add a blue border
    label.setBorder(new TitledBorder(new EtchedBorder(Color.lightGray, Color.blue), ConfigUser.getCu().toString()));
    //this below doesn't work
    label.setSize(280, 200);

    //I tried adding a JPanel in between but it didn't really worked out
    //JPanel panel = new JPanel();
    //panel.setLayout(new GridLayout(1, 1));
    //panel.setSize(297, 200);
    //panel.add(label);

    ///pnlCommentaire is the JPanel inside the JScrollPane

    pnlCommentaire.setLayout(new BoxLayout(pnlCommentaire, BoxLayout.Y_AXIS));

    pnlCommentaire.add(label);

    pnlCommentaire.revalidate();
    pnlCommentaire.repaint();
}

如您所见,我尝试使用 htmlstyle='width:280px'和使用 JLabel 来调整大小,label.setSize(280, 200);但它们都不起作用。

您对我如何调整此 Jlabel 的大小有任何想法吗?

编辑 :

我添加了一个margin-right属性,div这样我至少可以完全看到 JLabel 中的文本,但右边框仍然隐藏。

 String formattedComment = "<html><br><div style='width:280px;margin-right:50px;'>" + 
            txtArCommentaire.getText().replaceAll("\n", "<br>") + 
            "</div><br></html>";

标签: javaswinglayout-managerboxlayout

解决方案


推荐阅读