我在网格布局框架中有5个标签。我想使用数组中的位置名称将gridlayout更改为边框布局(例如String gborders [] = {“North”,“Center”,“South”,“East”,“West”};)和枚举标签地点。有可能吗?
这就是我所拥有的:
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);
}
}
答案 0 :(得分:2)
您可以执行以下操作
String[] gborders = { BorderLayout.NORTH,BorderLayout.CENTER,
BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.EAST };
在单个面板中添加所有内部面板
JFrame frame = new JFrame("Frame");
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
在for循环结束时
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);
完成。