Java,添加JScrollPane以列出JPanel

时间:2015-10-19 07:44:01

标签: java swing jpanel jscrollpane

我想知道是否有办法将JScrollPane添加到JList,其中该列表位于JPanel上。我到处寻找这方面的例子,但我找不到任何例子。滚动没有出现。

这是我的代码:

import java.awt.Dimension;
import javax.swing.*;
import javax.swing.ListSelectionModel;

public class MyClass{
public static void main(String args[]){

    //Declaring JFrame, JPanel, JList, JScrollPane objects
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JList list; 
    JScrollPane scroll; 
    String[] numberTest = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};

    //JFrame, frame
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setVisible(true);

    //JPanel, panel
    panel.setLayout(null);
    frame.add(panel);

    //JList, list
    list = new JList(numberTest);

    //list properties
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setLayoutOrientation(JList.VERTICAL);
    list.setVisibleRowCount(3);

    //Add JScrollPane to list   [What I need help with, its not working]
    JScrollPane listScroller = new JScrollPane(list);
    listScroller.setPreferredSize(new Dimension(250, 80));

    //Setbounds, add list and repaint frame
    list.setBounds(25, 25, 100, 100);
    panel.add(list);
    frame.repaint();

}
}

1 个答案:

答案 0 :(得分:0)

将JScrollPane添加到JPanel。

public class MyClass{
public static void main(String args[]){

//Declaring JFrame, JPanel, JList, JScrollPane objects
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JList list; 
JScrollPane scroll; 
String[] numberTest = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};

//JFrame, frame
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);

//JPanel, panel
panel.setLayout(null);
frame.add(panel);

//JList, list
list = new JList(numberTest);

//list properties
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisibleRowCount(3);

//Add JScrollPane to list   [What I need help with, its not working]
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(250, 80));

//Setbounds, add list and repaint frame
listScroller.setBounds(25, 25, 100, 100);
panel.add(listScroller);
frame.repaint();
}
}