如何显示JList的水平和垂直滚动条?

时间:2015-10-17 12:36:21

标签: java swing jlist scrollpane

今天我和JList一起玩,然后我发现了一个问题。 我知道我的田地没有好名字,但正如我所说,我只是在玩耍。

我想为我的JList创建一个水平和垂直的JScrollPane。实际上,它有效,但仍然存在问题。

我总是要向右滚动才能看到垂直滚动窗格: my ScrollPanes my ScrollPanes

我的代码:

   final JList list = new JList(GUI.strings.toArray());

   JScrollPane scrollPane = new JScrollPane(list);
   JScrollPane scrollPanex = new JScrollPane(scrollPane);

   scrollPanex.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
   scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

   getContentPane().add(scrollPanex, BorderLayout.CENTER);

有没有办法解决这个问题,所以我总能看到两个滚动条?

1 个答案:

答案 0 :(得分:3)

只需使用一个JScrollPane,然后设置单个JScrollPane的两个滚动条策略。

final JList list = new JList(GUI.strings.toArray());
JScrollPane scrollPane = new JScrollPane(list);

scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

getContentPane().add(scrollPane, BorderLayout.CENTER);

如,

import java.awt.Dimension;
import java.util.Random;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;

public class ScrollPaneFun {
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            Random rand = new Random();
            DefaultListModel<String> lModel = new DefaultListModel<>();
            JList<String> myList = new JList<>(lModel);
            myList.setVisibleRowCount(20);

            for (int i = 0; i < 50; i++) {
               StringBuilder sb = new StringBuilder();
               sb.append(String.valueOf(i) + ": ");
               for (int j = 0; j < 50; j++) {
                  for (int k = 0; k < 3; k++) {
                     char c = (char) ('a' + rand.nextInt('z' - 'a' + 1));
                     sb.append(c);
                  }
                  sb.append(' ');
               }
               lModel.addElement(sb.toString());
            }

            JScrollPane scrollPane = new JScrollPane(myList);
            scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            JViewport viewport = scrollPane.getViewport();
            int w = 400;
            int h = viewport.getPreferredSize().height;
            Dimension preferredSize = new Dimension(w, h);
            viewport.setPreferredSize(preferredSize);
            JOptionPane.showMessageDialog(null, scrollPane);
         }
      });
   }
}