Java 通过编程从组件-Swing创建和选择值

Java 通过编程从组件-Swing创建和选择值,java,swing,Java,Swing,我有一种方法,可以在点击时向JPanel添加一些指令、按钮和JLabel,但我需要某种方法来选择这三个元素,以便对它们进行样式化,我使用的解决方案是迭代所有组件并找到我想要样式化的组件,但它不允许我设置JPanel的边界,当您查看可用的方法时,这不是一个选项。是否仍要在底部的循环中设置JLabel的边界?或单独选择每个元素的方法 当用户单击不同JPanel上的按钮时,GenerateImageArea方法将运行 public void GenerateImageArea(int id) {

我有一种方法,可以在点击时向JPanel添加一些指令、按钮和JLabel,但我需要某种方法来选择这三个元素,以便对它们进行样式化,我使用的解决方案是迭代所有组件并找到我想要样式化的组件,但它不允许我设置JPanel的边界,当您查看可用的方法时,这不是一个选项。是否仍要在底部的循环中设置JLabel的边界?或单独选择每个元素的方法

当用户单击不同JPanel上的按钮时,GenerateImageArea方法将运行

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
        }
    }
}
public void GenerateImageArea(int-id)
{
areaHeight+=200;//扩展JPanel
i++;
gbc.gridx=0;
gbc.gridy=i;
gbc.gridwidth=4;
gbc.anchor=GridBagConstraints.LINE\u START;
//将说明添加到JLabel中
添加(新JLabel(“[”+(id+5)+”]:选择最大尺寸为720*350像素的图像),gbc);
i++;
gbc.gridx=0;
gbc.gridy=i;
gbc.gridwidth=1;
gbc.anchor=GridBagConstraints.LINE\u START;
//添加按钮以加载图像
添加(新JButton(“加载图像”));
gbc.gridx=1;
gbc.gridwidth=3;
//添加用作显示图像空间的JLabel
添加(新JLabel(“”);
//设置说明的颜色+字体JLabel
对于(int i=0;i

与此类似,我需要以编程方式添加JTextAreas,然后在用户单击submit之后设置样式并从中检索数据。如何以编程方式添加组件,但之后能够提取输入

可以直接设置样式,而不是查找要设置样式的图元。例如,不要这样做:

add(new JLabel("["+ (id+5) + "]: Select an image of maximum dimensions 720 * 350 pixels."), gbc);
你可以做:

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

我相信这种方法更简单,也不容易出错。

为什么不使用变量<代码>JLabel标签=。。。;添加(标签);标签.订单(…)我还有一个类似的方法,为用户输入添加指令+文本框,比如我给所有文本框一个变量名,如您的示例中所示-如何从每个文本框中提取数据例如,如果屏幕上有10个文本框,您可以将这些标签和文本框存储在一个数组中。要提取数据,你只需要在数组上迭代。哦,你让我想到。。。也许有一个哈希表,关键可能是名称和数据的组成部分。。。嗯,在我勾选它之前的最后一件事是——是否有任何方法可以通过编程将组件的名称设置为变量?您可以举个例子吗?我不太明白这个问题,比如Jlabel--myvariable--=newjlabel();