我有一个JPanel
,其中包含我的JFrame
内的下拉列表和文本字段。我的JFrame
中有一个按钮,当用户点击该按钮时,应用程序会添加具有相同组件的新JPanel
,即下拉列表和文本字段。因此,为此,我创建了一个函数,使用ActionListener
单击按钮时会调用该函数。
从GUI端一切正常但问题是当用户完成添加JPanel
并在这些下拉菜单和文本字段中输入值时,它将单击“提交”按钮。单击“提交”按钮后,我应该能够从所有下拉菜单和文本字段中获取值。这是一个挑战,因为我使用相同的函数来创建JPanel
,我无法调用它的名称来获取值,因为这将为我提供最后JPanel
个值。
有什么建议我应该怎么做?我添加了JFrame
的屏幕截图和创建JPanel
的功能。任何帮助表示赞赏。感谢。
public static void AddPanel(final Container pane) {
panel1 = new JPanel();
String text = "<html><b>Property" + nooftimes + " :</b></html>";
JLabel label = new JLabel(text);
label.setPreferredSize(new Dimension(80, 30));
panel1.add(label);
panel1.add(new JLabel("Please enter the property"));
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
model.addElement("value1");
model.addElement("value2");
model.addElement("value3");
model.addElement("value4");
model.addElement("value5");
final JComboBox<String> comboBox1 = new JComboBox<String>(model);
AutoCompleteDecorator.decorate(comboBox1);
comboBox1.setPreferredSize(new Dimension(120, 22));
panel1.add(comboBox1);
final JTextField txtfield1 = new JTextField(
"Please enter your value here");
txtfield1.setPreferredSize(new Dimension(200, 22));
panel1.add(txtfield1);
txtfield1.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
txtfield1.setText("");
}
public void focusLost(FocusEvent e) {
// nothing
}
});
container.add(panel1);
nooftimes++;
frame.revalidate();
frame.validate();
frame.repaint();
}
答案 0 :(得分:3)
您可以返回JPanel
并将其存储在List<JPanel>
中。当您点击提交按钮时,您可以遍历JPanel
及其Component
。
public class Application {
private static List<JPanel> panels = new ArrayList<>();
private static Container someContainer = new Container();
public static void main(String[] args) {
panels.add(addPanel(someContainer));
panels.add(addPanel(someContainer));
panels.add(addPanel(someContainer));
submit();
}
public static JPanel addPanel(final Container pane) {
JPanel panel1 = new JPanel();
// shortened code
final JComboBox<String> comboBox1 = new JComboBox<String>();
panel1.add(comboBox1);
final JTextField txtfield1 = new JTextField("Please enter your value here");
txtfield1.setText(String.valueOf(Math.random()));
panel1.add(txtfield1);
return panel1;
}
private static void submit() {
for (JPanel panel : panels) {
Component[] components = panel.getComponents();
for (Component comp : components) {
// Cast comp to JComboBox / JTextField to get the values
if (comp instanceof JTextField) {
JTextField textField = (JTextField) comp;
System.out.println(textField.getText());
}
}
}
}
}
答案 1 :(得分:2)
您可以简单地使用特定方法创建一个类(扩展JPanel)来添加组件,并从用户获取输入(即从文本字段中获取组合框选择的索引和文本)。 每次添加一个面板时,你都不会调用静态方法,但是你创建了这个类的实例,将引用保留在某处(例如将它添加到一个arraylist中)。
但你可以考虑一个不同的场景:我个人不喜欢添加组件&#34;飞行&#34;你可以有一个组件(例如另一个JComboBox),用户可以在其中选择号码他需要的价值观。 你决定一个默认值(例如4),所以在开始时你创建了4个类的面板,你可以使用一个包含它们的简单数组。 如果用户更改了面板数量,您可以处置框架并创建一个新框架。 当然,如果您想要插入输入,或者如果框架结构需要花费很多时间,那么这种解决方案并不适合。
Here我创建了一个gui的屏幕截图:用户可以选择部分数量,当选择更改时我只需重新创建下面的面板,其中包含文本字段(以二维数组存储) )。