Using MigLayout, why is a JButton following a JTable unresponsive and how to fix this?
- by M. Joanis
Hi everyone,
I am having a mind-boggling problem regarding the use of a JButton following a JTable with MigLayout. It is totally unresponsive unless I push it far enough past the JTable (then it can behave correctly).
I have tried running the code with both the MigLayout JAR of the version we use for end user products and with the very most recent one; same result.
Here is a sample code reproducing the problem (Main.java):
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
@SuppressWarnings("serial")
public class Main extends JFrame {
private JPanel panel;
private JTextField textField;
private JButton chooseButton;
private JTable table;
private JButton reloadButton;
private final DefaultTableModel model = new DefaultTableModel() {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
public Main() {
panel = new JPanel(new MigLayout("debug", "[][grow][]"));
setContentPane(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
/*** First row ***/
// "File:"
panel.add(new JLabel("File:"));
// textField for filename
textField = new JTextField("No file selected yet!");
textField.setEditable(false);
panel.add(textField, "growx");
// "Choose..." button
chooseButton = new JButton("Choose...");
panel.add(chooseButton, "wrap, sg buttons");
/*** Second row ***/
panel.add(new JLabel());
table = new JTable(model);
model.setColumnIdentifiers(new String[] {"col title"});
JScrollPane scrollpane = new JScrollPane(table);
Dimension scrollpaneDimension = new Dimension(125, 110);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
table.setPreferredScrollableViewportSize(scrollpaneDimension);
table.setFillsViewportHeight(true);
panel.add(table.getTableHeader(), "grow");
panel.add(scrollpane, "grow");
reloadButton = new JButton("Reload");
panel.add(reloadButton, "top, wrap, sg buttons");
pack();
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
I suppose it has something to do with the table header and the table itself ending up in the same layout cell, but I'm really not sure of this.
As I said, if I push the button far enough past the JTable, it will work again. If I drop it on the next row, it doesn't work, I have to move it down one more row.
The only library you need in your workspace to run the code is MigLayout.
Thank you all for your help, much appreciated!
M. Joanis