简体   繁体   中英

JList of TextFields and JScrollPane doesn't show / Java Swing

I am trying to create a window that shows a dynamic list of textFields and if the number of textfields is large then I want to add a scroller. I am using GridLayout. The problem is that the panel I added the Jlist and scroller doesn't show anything, neither the list nor the scroller. Below you will find a part of my code.

                   //Label 
                JLabel numberOfTxt = new JLabel("Please enter the number in every TextField");
                int n = 11; //A random number of TextFields
                firstPanel.add(numberOfTxt, BorderLayout.NORTH); //Add label to panel

                JList textFieldList = new JList(); //Create a list of TextFields
                for (int i = 0; i < n; i++) {
                    //Add TextFields to list
                    JTextField textField = new JTextField();
                    textField.setBounds(0, 0, 6, 0);

                    textFieldList.add(textField);
                    System.out.println("textFieldList" + textFieldList);
                }


                textFieldList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                textFieldList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
                textFieldList.setVisibleRowCount(8);

                //Create scroller
                JScrollPane listScroller = new JScrollPane(textFieldList);
                listScroller.setBounds(0, 20, 600, 600);

                //Create layout for panel where the textfields will be added
                if (n % 2 != 0) {
                    n = n + 1;
                }
                thirdPanel.setLayout(new GridLayout(n / 2, 2, 10, 6));
                thirdPanel.add(textFieldList);
                thirdPanel.setVisible(true);

                //ContentPane has BoxLayout
                contentPane.add(firstPanel);
                contentPane.add(thirdPanel);

                contentPane.repaint();
                window.pack();
            }
            window.revalidate();
        }
    });
  1. JList does not works this way. If you really need a JList of TextFields you should use ListCellRenderer (probably you don't, see p.3).

  2. You adding textFieldList both to listScroller and thirdPanel . Probably, you should replace thirdPanel.add(textFieldList); by thirdPanel.add(listScroller); .

  3. thirdPanel uses GridLayout , but only one control is ever added to it. You should either add TextField directly to thirdPanel (easier way), or let the JList manage them.

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