简体   繁体   中英

Java swing - Items in scrollable GridLayout not visible

I am trying to create a simple Swing UI that shows a list of text areas, all beneath one another. I want to have a scrollbar that allows me to scroll vertically through the list.

However, I cant seem to make the entries in the grid visible and stay that way.

It seems like the entries appear for a fraction of a second and then disappear again. I can't make sense of it at all.

Here's my code:

public class MyWindow extends JFrame {
JPanel stretchPanel;
JScrollPane scrollpane;
JPanel centrePanel;
JScrollBar scrollbar;

public MyWindow(String title) {
    super(title);
    BorderLayout layout = new BorderLayout();
    setLayout(layout);

    stretchPanel = new JPanel();
    scrollpane = new JScrollPane();
    stretchPanel.setLayout(new FlowLayout());
    centrePanel = new JPanel();
    centrePanel.setLayout(new GridLayout(0, 1));
    scrollbar = new JScrollBar(JScrollBar.VERTICAL);
    scrollpane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scrollpane.setVerticalScrollBar(scrollbar);

    scrollpane.setViewportView(stretchPanel);
    stretchPanel.add(centrePanel);
    scrollpane.add(stretchPanel);
    add(scrollpane, BorderLayout.CENTER);
    fillGrid();
    setVisible(true);
}

public void fillGrid() {
    centrePanel.removeAll();
    for (int i = 0; i < 20; i++) {
        TextField entry = new TextField("Hello");
        centrePanel.add(entry);
    }
    scrollpane.setPreferredSize(new Dimension(800, 700));
    pack();
}

public static void main(String[] args) {
    new MyWindow("d");
}

}

Any help is greatly appreciated!

You're adding your JPanel to the JScrollPane, something you should never do. You need to set the view port view with your JPanel so that it is added to the JScrollPane's viewport, as the JScrollPane tutorial and API explain. So not

scrollpane.add(stretchPanel);

but rather

scrollpane.setViewportView(stretchPanel);

Other issues:

  • Why create your own JScrollBar and not use the default one provided by JScrollPane?
  • Since you're displaying a grid of JTextFields, perhaps you should instead be creating and displaying a JTable.

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