在我的问题中,我问了类似的问题。但在我之前的项目中,我使用了GUI构建器,所以现在我想在没有Builder的情况下动态地将JTextField
添加到Panel
。我不是为什么但由于某种原因我无法执行此代码:
public class Reference {
JFrame frame = new JFrame();
JPanel MainPanel = new JPanel();
MainPanel main = new MainPanel();
JPanel SubPanel = new JPanel();
JButton addButton = new JButton();
JButton saveButton = new JButton();
private List<JTextField> listTf = new ArrayList<JTextField>();
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Reference();
}
public Reference() {
frame.add(main);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(addButton, BorderLayout.EAST);
frame.add(saveButton, BorderLayout.WEST);
frame.pack();
frame.setSize(500, 300);
frame.setVisible(true);
main.setLayout(new BorderLayout());
main.setBackground(Color.green);
main.add(SubPanel);
SubPanel.setBackground(Color.yellow);
addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
main.add(new SubPanel());
main.revalidate();
}
});
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
for (int i = 0; i < main.getComponentCount();) {
SubPanel panel = (SubPanel)main.getComponent(i);
JTextField firstName = panel.getFirstName();
String text = firstName.getText();
System.out.println( text );
}}
});
}
private class SubPanel extends JPanel {
JTextField firstName = new JTextField(15);
public SubPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
this.add(firstName);
listTf.add(firstName);
}
public JTextField getFirstName()
{
return firstName;
}
}
public class MainPanel extends JPanel
{
List<SubPanel> subPanels = new ArrayList<SubPanel>();
public MainPanel()
{
}
public void addSubPanel()
{
SubPanel panel = new SubPanel();
add(panel);
subPanels.add(panel);
}
public SubPanel getSubPanel(int index)
{
return subPanels.get(index);
}
}
}
saveButton
试图获得JTextField
的价值,但没有成功。在输出中,我只能看到JFrame
有2 Buttons
,但ActionListener
addButton
和saveButton
无效。我无法理解哪里出错了。
非常感谢任何帮助。
答案 0 :(得分:3)
在Swing中,你做某些事情的顺序非常重要,例如......
frame.add(main);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(addButton, BorderLayout.EAST);
frame.add(saveButton, BorderLayout.WEST);
frame.pack();
frame.setSize(500, 300);
frame.setVisible(true);
main
添加到frame
这里的问题是第2步。相反,如果我们只删除第2步(第4步和第5步也不是很好),您会发现您的窗口现在包含main
...
frame.add(main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(addButton, BorderLayout.EAST);
frame.add(saveButton, BorderLayout.WEST);
frame.pack();
frame.setVisible(true);
此...
for (int i = 0; i < main.getComponentCount();) {
SubPanel panel = (SubPanel) main.getComponent(i);
一个坏主意有三个原因;
i
永远是0
)main
的内容而实际上并不知道它上面有什么MainPanel
已有List
个SubPanel
... 您需要确保通过SubPanel
方法添加addSubPanel
(这可能会返回SubPanel
的实例)并提供一种方法访问此List
,可能是通过某种getter
。虽然,我对他们的价值观(即文本字段文本)更感兴趣,而不是SubPanel
本身;)