JFrame中的滚动窗格未显示

时间:2019-03-15 10:12:12

标签: java swing jframe jscrollpane

我尝试将滚动条放在框架上,但是它不起作用,我看不到滚动条。

这是我的代码:

Popup noticePopup = new Popup("Notice", 1500, 900);
JPanel noticePanel = new JPanel();
noticePanel.setPreferredSize(new Dimension(1500,1000));
List<List> ListNote = controller.Medicament.consultationNotice(medocSelectStr);
String noticeThis =null;
for(int n=0;n<ListNote.size();n++) {
    noticeThis = (String) ListNote.get(n).get(1);
}
JTextArea noticeArea = new JTextArea(noticeThis);
noticePopup.add(noticePanel);
noticePanel.add(noticeArea);
JScrollPane jScrollPane = new JScrollPane( noticePanel);
// only a configuration to the jScrollPane...
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

// Then, add the jScrollPane to your frame
noticePopup.getContentPane().add(jScrollPane);

JScrollPane scroll=new JScrollPane(noticePanel,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
noticePopup.getContentPane().add(scroll);

2 个答案:

答案 0 :(得分:1)

您要创建两个具有相同内容的滚动窗格:

//you may add extra selector like this

<div class="selector-1"></div>
<div class="selector-1 selector-2"></div>

和:

 JScrollPane jScrollPane = new JScrollPane( noticePanel);

并且您要将它们都添加到弹出窗口中,并且还将通知面板添加到弹出窗口中,因此需要删除很多代码

JScrollPane scroll=new JScrollPane(noticePanel,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

答案 1 :(得分:1)

我看到许多潜在的问题:

Popup noticePopup = new Popup("Notice", 1500, 900);
JPanel noticePanel = new JPanel();
noticePanel.setPreferredSize(new Dimension(1500,1000));

不要尝试手动编码框架或面板的尺寸:

  1. 您不知道人们将使用哪种分辨率
  2. 您提供的数字没有意义。面板的宽度不能与框架相同,因为框架带有边框。高度不能相差100,因为面板将被扩展以填充可用空间。

如果您希望框架填满屏幕,则只需使用:

noticePopup.setExtendedState(JFrame.MAXIMIZED_BOTH);

您期望以下代码做什么:

for (int n=0; n < ListNote.size(); n++) 
{
    noticeThis = (String) ListNote.get(n).get(1);
}

如果列表中有多个项目,则只需将“ noticeThis”变量中的文本替换为列表中的最后一项。

相反,您应该将文本追加到文本区域:

JTextArea noticeArea = new JTextArea(5, 20);

for (int n = 0; n < ListNote.size(); n++) 
{
    if (n > 0 ) noticeArea.append("\n");

    noticeArea.append( (String)ListNote.get(n).get(1) );
}

为什么有一个“ noticePanel”:

noticePanel.add(noticeArea);
JScrollPane scroll=new JScrollPane(noticePanel, ...);
noticePopup.getContentPane().add(scroll);

默认情况下,JPanel使用FlowLayout,它将遵循添加到其中的任何组件的首选大小。我不知道文本区域的首选大小是多少,但是只有当组件的首选大小大于滚动窗格的大小时,滚动条才会出现。

只需将文本区域直接添加到滚动窗格,滚动条将根据需要显示:

JScrollPane scroll=new JScrollPane(noticeArea, ...);
noticePopup.add(scroll);

请注意,自JDK1.4起,您无需使用getContentPane()