Reputation: 95
I have 5 labels in grid layout frame. I would like to change gridlayout to border layout with using names of location from an array (e.g. String gborders[] = { "North", "Center", "South", "East", "West" }; ) and enumerate label location. Is it possible?
That is what I have:
package w1;
import java.awt.*;
import javax.swing.border.*;
import javax.swing.*;
public class LayShow {
private static JLabel lLabel;
public static void main(String[] args) {
int t = 15;
String lmNames[] = {"Label 1", "Label 2",
"Label 3", "Label 4", "Label 5"};
String gborders[] = { "North", "Center", "South", "East", "West" };
Color colors[] = { new Color(11, 125, 155), new Color(155, 55, 200),
new Color(201, 245, 145), new Color(255, 255, 140),
new Color(161, 224, 224), new Color(11, 125, 155) };
Font fonts[] = {new Font("SansSerif", Font.BOLD, t),
new Font("Arial", Font.BOLD, t+1),
new Font("SansSerif", Font.PLAIN, t+2),
new Font("SansSerif", Font.ITALIC, t+3),
new Font("SansSerif", Font.ITALIC, t+4)};
JFrame frame = new JFrame("Frame");
frame.setLayout(new GridLayout(0, 2));
for (int i = 0; i < lmNames.length; i++) {
final Border
borderColor = BorderFactory.createLineBorder(colors[i+1]);
JPanel p = new JPanel();
p.setBackground(colors[i]);
p.setBorder(BorderFactory.createTitledBorder(borderColor , lmNames[i]));
lLabel = new JLabel("label number: " + (i+1));
p.add(lLabel);
lLabel.setFont(fonts[i]);
lLabel.setForeground(colors[i+1]);
lLabel.setToolTipText("ToolTip for label number: " + (i+1));
frame.add(p);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Upvotes: 0
Views: 330
Reputation: 11298
You can do the following
String[] gborders = { BorderLayout.NORTH,BorderLayout.CENTER,
BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.EAST };
Add all inner panels in a single panel
JFrame frame = new JFrame("Frame");
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
at the end of for loop
for (int i = 0; i < lmNames.length; i++) {
....
lLabel.setToolTipText("ToolTip for label number: " + (i+1));
panel1.add(p,gborders[i]);
}
frame.add(panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
Done.
Upvotes: 2