I'm designing a GUI with 20 or so components: 10 labels, 4 text fields, 4 buttons, and 2 text areas. Using GridBagLayout seemed a great idea. But with all the instance variables required to do it by the book for each component (i.e., not reuse), a general method for adding components seemed a must. I really thought this could work:
(Note: HORIZ is abbreviation for GridBagConstraints.HORIZONTAL; CENTER is abbreviation for GridBagConstraints.CENTER.)
public static void addComponent(Container f, Component c,
int x, int y,
int w, int h,
int ipadx, int ipady,
float wtx, float wty,
int fill, int anchor, Insets insets){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = w; gbc.gridheight = h;
gbc.fill = fill;
gbc.ipadx = ipadx; gbc.ipady = ipady;
gbc.insets = insets; gbc.anchor = anchor;
gbc.weightx = wtx; gbc.weighty = wty;
f.add(c,gbc);
}
I called it like so:
Insets insets = new Insets(0,0,0,0);
JFrame frame = new JFrame();
label = new JLabel("Blablablah");
addComponent(frame, label, 0,0, 1,1, 0,0, 0.5f,0, HORIZ, CENTER, insets);
But I got message "cannot add to layout: constraint must be a string (or null)" at f.add(c.gbc)
.
I think I understand the error: frame
doesn't have GridBagConstraints
prior to the call to addComponent
and gbc
in the first line of the method doesn't belong to parameter f
(or anything else?).
So I modified the method signature slightly, omitting Container
:
public static void addComponent( Component c,
int x, int y,
... (rest unchanged)
And I modified the problem line like so:
frame.add(c, gbc);
So I'm using a global variable, frame
, when I'd rather pass it as an argument.
Two questions:
(1) Is there a way to minimally modify my code to enable passing frame
to addComponent
?
(2) Is there any reason to want to do so? I guess this amounts to asking, what would YOU do?
P.S. Here's calls to the modified addComponent
, hastily thrown together to get some semblance of the first few lines of what I want. The spacing reeks at the moment--I need to monkey with insets, ipads, fills--but it's actually usable. (New name for frame
is GUI
.)
private static void createAndShowGUI() {
GUI = new JFrame();
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gbl = new GridBagLayout();
GUI.setLayout(gbl);
addComponent(lblRootNode, 0,0, 1,1, 0,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));
addComponent(txtRootNode, 1,0, 5,1, 60,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));
addComponent(btnBrowse, 6,0, 1,1, 0,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));
addComponent(lblFilenamePat, 0,1, 2,1, 0,0, 0.5f,0, HORIZONTAL, EAST, new Insets(0,0,0,0));
addComponent(txtFilenamePat, 2,1, 4,1, 0,0, 0.5f,0, HORIZONTAL, LINE_END, new Insets(0,0,0,0));
addComponent(lblDates, 0,2, 2,1, 0,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));
addComponent(lblSizes, 2,2, 2,1, 0,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));
...