编程地创建和选择值从组件- Swing



我已经有了这个方法,它添加了一些指令,一个按钮和JLabel到点击时的JPanel,但我需要一些方法来选择这三个元素,这样我就可以对它们进行样式化,我使用的解决方案是遍历所有组件并找到我想要样式化的组件,但它不会让我设置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
        }
    }
}
与此类似,我需要以编程方式添加JTextAreas然后样式,并在用户单击提交后从中检索数据。我如何以编程方式添加组件,但能够提取输入之后?

您可以直接为它们设置样式,而不是找到您想要设置样式的元素。例如,不这样做:

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

最新更新