Shivam Paw
Shivam Paw

Reputation: 203

Making JPanel dynamically fit into JDialog

I have a JPanel that is returned from a class and then a button is added to the bottom of it in a new panel.

The code is this:

String csv = csvName.getText();
String csvN = (String)ss.getSelectedItem()+csv+".csv";
JPanel f = T1Data.program(csvN);

JDialog desktopFrame = new JDialog();
desktopFrame.add(f);
desktopFrame.setModal(true);
desktopFrame.setSize(900, 500);
desktopFrame.setVisible(true);

And this is the T1Data.program class.

public static JPanel program(String csvName) {

    JPanel f = new JPanel(new BorderLayout());

    try {

        String path = System.getProperty("user.dir");

        String datafile = path+csvName;
        FileReader fin = new FileReader(datafile);
        DefaultTableModel m = createTableModel(fin, null);
        JTable table = new JTable(m);
        JScrollPane stable = new JScrollPane (table);
        stable.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        stable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        f.add(stable,BorderLayout.NORTH);
        JButton btn = new JButton("Save Edits");
        f.add(btn,BorderLayout.SOUTH);

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                toExcel(m, new File(path+csvName));
                JOptionPane.showMessageDialog(f, "Saved CSV File!");
            }
        });


    } catch (Exception e) {
        e.printStackTrace();
    }

    return f;

}

When I run it, it will show normally and all fit. I've posted a link to it in the comments because I can't post 3 links in a post for now.

If I make it smaller this happens: http://i.gyazo.com/0d7792cc11eaaba66c6743f5cb5addd7.png the horizontal bar and the save button disappeared.

If I make it bigger this happens: http://gyazo.com/b4820450324d308ea4b4710af8acc6a7.png there is a big gap under the JTable.

How can I fix this so that the JTable dynamically resizes to fit the JDialog?

Upvotes: 0

Views: 224

Answers (1)

VGR
VGR

Reputation: 44308

You probably want to change this:

f.add(stable,BorderLayout.NORTH);

to this:

f.add(stable, BorderLayout.CENTER);

A JScrollPane should be placed in the center of a BorderLayout, since the center component will stretch both horizontally and vertically when the parent is resized. The edge components stretch in one dimension only, which is not usually the intent of a JScrollPane.

Upvotes: 1

Related Questions