向JList添加滚动条,将JList添加到JPanel

时间:2012-04-07 07:21:11

标签: java swing jpanel jscrollpane

我有一个我想动态填充的列表,因此需要滚动条。我添加了一个滚动条列表。问题是当我尝试将列表添加到面板时。滚动条在列表中变得可见,但即使列表元素的大小变大,它们也不起作用。

JPanel p4=new JPanel();
Container c=getContentPane();
myList=new JList(model);
myList.setVisibleRowCount(5);
myList.setFixedCellWidth(200);

p4.add(new JScrollPane(myList,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
     ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS));
c.add(p4);

2 个答案:

答案 0 :(得分:2)

在这里工作得很好。我为SplitPaneDemo.java使用了SSCCE文件,并删除了所有不必要的内容

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import java.awt.BorderLayout;

public class SplitPaneDemo extends JPanel {
  private JList<String> list;
  private String[] imageNames = { "Bird", "Cat", "Dog", "Rabbit", "Pig", "dukeWaveRed",
      "kathyCosmo", "lainesTongue", "left", "middle", "right", "stickerface"};
  public SplitPaneDemo() {
    setLayout( new BorderLayout(  ) );

    list = new JList<>(imageNames);
    list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
    list.setSelectedIndex( 0 );

    add( new JScrollPane(list) );
  }

  /**
   * Create the GUI and show it.  For thread safety,
   * this method should be invoked from the
   * event-dispatching thread.
   */
  private static void createAndShowGUI() {

    //Create and set up the window.
    JFrame frame = new JFrame("SplitPaneDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
    frame.getContentPane().add(splitPaneDemo);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        createAndShowGUI();
      }
    });
  }
}

答案 1 :(得分:0)

类似的问题:here

我不认为答案在你的情况下是一样的。当您向列表中添加内容时,可能会出现问题;你可以试试:

myList.revalidate();

改变之后。