简体   繁体   中英

How do I use JList inside of JPanel So I can set the bounds of the list?

I am having trouble using JLists in Java. I have watched video tutorials on how to use them, but they all use them with some sort of layout. I would like to have it so the "setPreferedLayout" is null, and I can use the setBounds method to decide where my lists and buttons go on the window. When I do that, and I do somthing like frame.add(list) or panel.(list) to add it to my panel, it doesn't show up on the window, but my button does.

I have something like this:

    //DECLARATION
    JFrame f = new JFrame("main Window");
    JPanel p = new JPanel();

    int WIDTH = 800;
    int HEIGHT = 650;

    public static JList mainList;
    String[] mainArray = {"one","two","three"};

    //INIT
    public mainClass() {
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(p);
        f.setVisible(true);
        p.setLayout(null);
        p.setPreferredSize( new Dimension(WIDTH,HEIGHT) );
        f.pack();
        p.setVisible(true);

        p.setFocusable(true);

        System.setProperty("sun.java2d.opengl","true");
        Thread thr1 = new Thread (r1);
        thr1.start();

        mainList = new JList(mainArray);
        mainList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        mainList.setSelectedIndex(0);
        mainList.setVisibleRowCount(3);
        JScrollPane listScrollPane = new JScrollPane(mainList);
    }

again, i'm trying to create a JList that I can have in whatever position I would like. thats basically what i'm trying to get. Whenever I try to di it the way it works will Jbuttons (setting its bounds and adding it to the panel) It doesn't show up when I runt he program...

public mainClass() {
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        mainList = new JList(mainArray);
        mainList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        mainList.setSelectedIndex(0);
        mainList.setVisibleRowCount(3);
        JScrollPane listScrollPane = new JScrollPane(mainList);
        p.add(listScrollPane);
        f.add(p);
        p.setPreferredSize( new Dimension(WIDTH,HEIGHT) );        
        f.pack();        
        f.setVisible(true);
        p.setFocusable(true);

        System.setProperty("sun.java2d.opengl","true");
        Thread thr1 = new Thread (r1);
        thr1.start();


    }

this should work you never added your list to panel, also you set visible than pack() thats not gonna work. The last thing you should do is set Visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM