简体   繁体   中英

Why does setPreferredSize() sometimes take precedent over setMinimumSize()?

I had an error yesterday where I added a JTable and a JPanel (with a JButton in it) to a JScrollPane . The JButton was fixed to the bottom of the table, and it added a row to the JTable when clicked.

The problem was if the table ever got bigger than the JScrollPane , it would only allow you to scroll to the bottom of the JTable ; you couldn't get to the JButton anymore. Today, I made an MCVE to try and get help, but first I monkeyed with it a bit more and ended up fixing my problem, but in a way that left me with more questions than answers... Here's the MCVE I had prepared:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class MCVE extends JFrame{

    private JButton addRow;
    private MCVEModel tableModel;
    private JTable table;
    private JScrollPane pane;
    private JPanel scrollPanel, panel;

    public static void main (String[] args) {
        new MCVE();
    }

    public MCVE() {
        initialize();
    }

    public void initialize () {
        this.setTitle("Halp");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setBounds(50, 50, 500, 300);
        this.setResizable(false);

        JPanel mainPanel = new JPanel(new GridBagLayout());

        /** The JPanel everything is put into **/
        scrollPanel = new JPanel();
        scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.Y_AXIS));

        /** The JScrollPane we're using **/
        pane = new JScrollPane(scrollPanel);
        pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 
        pane.getVerticalScrollBar().setUnitIncrement(10);

        /** The button which keeps getting cut off.... **/
        addRow = new JButton("...");
        addRow.setBackground(Color.WHITE);
        addRow.setMnemonic('R');
        addRow.setFocusable(false);
        addRow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addNewRow();
            }
        });

        /** I wrap the button into this panel so I can affix it to the left **/
        panel = new JPanel();
        panel.setMinimumSize(new Dimension(0, 20));
        panel.setLayout(null);
        addRow.setBounds(0, 0, 35, 15);
        panel.add(addRow);

        /** Faking some data to get the table to populate **/
        ArrayList<List<String>> allData = new ArrayList<List<String>>();
        ArrayList<String> fakeData = new ArrayList<String>();
        fakeData.addAll(Arrays.asList(
                  new String[]{"this", "is", "just", "sample", "data"}));
        for(int i = 0; i < 5; i++)
            allData.add(fakeData);

        List<String> columnNames = Arrays.asList(new String[] {"", "", "", "", ""});
        tableModel = new MCVEModel(columnNames, allData);

        table = new JTable();
        table.setModel(tableModel);

        /** Adding it all together **/
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1;
        c.weighty = 1;
        scrollPanel.add(table);
        scrollPanel.add(panel);
        mainPanel.add(pane, c);
        this.add(mainPanel);

        this.setVisible(true);
    }

    public void addNewRow () {
        tableModel.addRow(tableModel.getRowCount(), 
                new String[]{"true", "", "", "false", "false"});
        tableModel.fireTableRowsInserted(
                tableModel.getRowCount(), tableModel.getRowCount());
    }
} 
/** 
 * Just here to keep things compilable. Seriously cut back for the MCVE, 
 * but still replicates the problem without any errors.
 * Nothing below here should be relevant to the issue. 
 */
class MCVEModel extends DefaultTableModel {

    private static final long serialVersionUID = -6598574844380686148L;
    private List<String> columnNames;
    private List<List<String>> values;

    public MCVEModel (List<String> columnNames, List<List<String>> strings) {
        this.columnNames = columnNames;
        this.values = strings;
    }

    public int getColumnCount() {
        return columnNames.size();
    }

    public int getRowCount() {
        return values == null || values.size() == 0 ? 0 : values.get(0).size();
    }

    public String getColumnName(int col) {
        return columnNames.get(col);
    }

    public Object getValueAt(int row, int col) {
        return values.get(col).get(row);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Class getColumnClass(int c) {
        return String.class;
    }

    public boolean isCellEditable(int row, int col) {
        return true;
    }

    public void setValueAt(Object value, int row, int col) {
        values.get(col).set(row, (String) value);
        fireTableCellUpdated(row, col);
    }

    public void removeRow(int row) {
        for(int i = 0; i < values.size(); i++)
            values.get(i).remove(row);
        this.fireTableRowsDeleted(row, row);
    }

    public void addRow(int row, String[] strings) {
        for(int i = 0; i < values.size(); i++)
            values.get(i).add(row, strings[i]);
        fireTableRowsInserted(row, row);
    }
}

The problem is with this line:

panel.setMinimumSize(new Dimension(0, 20));

More precisely, it's with the word "Minimum". By changing this to:

panel.setPreferredSize(new Dimension(0, 20));

I got exactly the functionality I needed. Now when the table gets too large for the JScrollPanel , we're still able to scroll down and see the JButton ; it's no longer cut off.

I'm assuming this means the JPanel 's parent didn't honor its minimum dimensions, but that it did honor its preferred dimensions. Why is this? I had thought setPreferredSize() , setMinimumSize() , and setMaximumSize() interacted like, "I'd prefer to be this big, but no matter what I can't be smaller than my minimum or larger than my maximum," but it seems this isn't the case. I know none of these methods should be used too frequently, but when should I use setMinimumSize() over setPreferredSize() or vice versa?

The magic is this line:

scrollPanel.add(panel);

So, scrollPanel will contain this panel. Then, JScrollPane honors the preferredSize -s. Which makes sense, since its purpose is, by using the scroll bars, to make enough room for the contained components. In other words, JScrollPane -s impementation ignores the minimumSize -s.

Update:

From an other angle, JScrollPane -s source code checks the preferredSize of its children, but not the minimumSize . There's no deep philosophy here, JScrollPane is implemented this way.

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