Reputation: 1009
I've got this method which adds some instructions, a button and JLabel to a JPanel on click but I need some way of selecting these three elements so I can style them, I'm using a solution of iterating through all components and finding the ones I want to style but It won't let me set the border of the JPanels, it's not an option when you view available methods. Is there anyway to set the border of the JLabel in the loop at the bottom? OR a way to individually select each element.
When the user clicks a button on a different JPanel the GenerateImageArea method runs.
public void GenerateImageArea(int id)
{
areaHeight += 200; // Extends JPanel
i++;
gbc.gridx = 0;
gbc.gridy = i;
gbc.gridwidth = 4;
gbc.anchor = GridBagConstraints.LINE_START;
// Add the instructions JLabel
add(new JLabel("["+ (id+5) + "]: Select an image of maximum dimensions 720 * 350 pixels."), gbc);
i++;
gbc.gridx = 0;
gbc.gridy = i;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.LINE_START;
// Add a button to load an image
add(new JButton("Load Image"));
gbc.gridx = 1;
gbc.gridwidth = 3;
// Add the JLabel which acts as a space to display the image
add(new JLabel(""));
// Set colour + font of the instructions JLabel
for (int i = 0; i < this.getComponentCount(); i++) {
Component comp = this.getComponent(i);
if (comp.toString().contains("]:")) {
comp.setForeground(Settings.SITE_GREEN);
comp.setFont(Settings.SUBTITLEFONT);
}
else if (comp.toString().contains("")) {
// I need to change the border of the second JLabel
}
}
}
Similar to this I need to programatically add JTextAreas then style and retrieve the data from them after the user clicks submit. How can i programatically add components but be able to extract the input afterwards?
Upvotes: 0
Views: 36
Reputation: 1563
Instead of finding the elements that you want to style, you can style them directly. For example, instead of doing this:
add(new JLabel("["+ (id+5) + "]: Select an image of maximum dimensions 720 * 350 pixels."), gbc);
you can do:
// Create instruction label
JLabel instruction = new JLabel("["+ (id+5) + "]: Select an image of maximum dimensions 720 * 350 pixels.");
// Style it
instruction.setForeground(Settings.SITE_GREEN);
instruction.setFont(Settings.SUBTITLEFONT);
// Add it.
add(instruction, gbc);
I believe this approach is easier, and less error prone.
Upvotes: 1