gpt4 book ai didi

java - 是否可能 - 来自数组值的边框布局位置?

转载 作者:行者123 更新时间:2023-12-02 07:26:18 24 4
gpt4 key购买 nike

我在网格布局框架中有 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);
}
}

最佳答案

您可以执行以下操作

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);

完成。

关于java - 是否可能 - 来自数组值的边框布局位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13551678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com