【问题标题】:Programatically Create and Select Values From Components - Swing以编程方式从组件中创建和选择值 - Swing
【发布时间】:2014-06-23 04:06:44
【问题描述】:

我有这个方法,它在点击时向 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
        }
    }
}

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

【问题讨论】:

  • 为什么不用变量呢? JLabel label = ...; add(label); label.setBorder(...);

标签: java swing


【解决方案1】:

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

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

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

【讨论】:

  • 我也有一个类似的方法,为用户输入添加指令+文本框,假设我给所有文本框一个变量名,就像你的例子一样 - 我如何从每个文本框中提取数据一? - 例如,如果屏幕上有 10 个文本框?
  • 您可以将这些标签和文本框存储在一个数组中。要提取数据,您只需要遍历数组即可。
  • 哦,你让我想到了......也许有一个哈希表,关键可能是名称和数据的组件......嗯,在我勾选它之前的最后一件事 - 无论如何以编程方式将组件的名称设置为变量?
  • 可以举个例子吗?我不太明白这个问题。
  • 喜欢 Jlabel --myvariable-- = new JLabel();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 2012-02-05
相关资源
最近更新 更多