javaswingjpaneljscrollpane

Dialog empty with JScrollPane und JPanel


I am trying to add the content to the mainPanel and mainpanel to the mainScrollPane. However, an empty dialog is displayed.

IMPORTANT: it must be implemented with JPanel and JScrollPane...

   `setModal(true);
    setTitle("Edit item");
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    JPanel mainPanel = new JPanel();
    mainPanel.setPreferredSize(new Dimension(400, 700));

    JScrollPane mainScrollPane = new JScrollPane();
    mainScrollPane.add(mainPanel);
    setLayout(new BorderLayout());
    add(mainScrollPane);

    mainPanel.add(new JLabel("ID: "));
    mainPanel.add(txtID = new JTextField(item.getID()));
    mainPanel.add(new JLabel("Description: "));
    mainPanel.add(txtDescription = new JTextField(item.getDescription()));


    pack();
    setVisible(true);`

Solution

  • Please provide a minimal reproducible example. It could look like what follows:

    MyFrame.java

    import javax.swing.*;
    import java.awt.*;
    
    class Item { 
        String id; 
        String description; 
        Item(String id, String description) {this.id = id;this.description = description;}
        String getId() {return id;}
        String getDescription() {return description;}
    }
    
    public class MyFrame extends JFrame {
        Item item = new Item("007", "Special watch");
        public MyFrame() {
            // setModal(true);
            setTitle("Edit item");
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    
            JPanel mainPanel = new JPanel();
            mainPanel.setPreferredSize(new Dimension(400, 700));
    
            mainPanel.add(new JLabel("ID: "));
            mainPanel.add(new JTextField(item.getId()));
            mainPanel.add(new JLabel("Description: "));
            mainPanel.add(new JTextField(item.getDescription()));
    
            /* From Oracle's documentation, see link below: 
               Creates a JScrollPane that displays the contents of the
               specified component, where both horizontal and vertical
               scrollbars appear whenever the component's contents are
               larger than the view.
            */
            JScrollPane mainScrollPane = new JScrollPane(mainPanel);
    
            // Just to show the bars
            mainScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
            mainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);  
    
            getContentPane().add(mainScrollPane); // <- This makes it shine!
    
            pack();
            setVisible(true);
        }
    
        public static void main(String[] args) {
            new MyFrame();
        }
    }
    
    $ javac MyFrame.java
    $ java MyFrame   
    

    Et voilà:

    Screenshot

    https://docs.oracle.com/javase/8/docs/api/javax/swing/JScrollPane.html