[英]How to get data from JFrame 1 to another JFrame?
在阅读了很多人发布和回答的问题后,我仍然不知道如何在Java中传递数据。 我这里有一个简单的代码,要求用户输入他们的年龄,身高,体重和一个打开第二帧的按钮。
第一帧
public Collectdata()
{
JPanel text = new JPanel();
text.add(jage);
text.add(age);
text.add(jheight);
text.add(height);
text.add(jweight);
text.add(weight);
text.setLayout(new GridLayout(3,2));
JPanel jbutt = new JPanel();
jbutt.add(next);
setLayout(new BorderLayout());
add(text,BorderLayout.CENTER);
add(jbutt,BorderLayout.SOUTH);
next.addActionListener(this);
}
public static void main(String[] args)
{
Collectdata GUI = new Collectdata();
GUI.setTitle("DataCollection"); //Set title
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close program
GUI.setSize(250,150);
GUI.setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
if(a.getSource() == next)
{
Calculate secondwind = new Calculate(this);
secondwind.setTitle("Calculate"); //Set title
secondwind.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close program
secondwind.setSize(350,150);
secondwind.setVisible(true);
this.setVisible(false);
}
}
}
这是单击按钮后将显示的第二帧。
第二帧
public Calculate(Collectdata collectdata)
{
this.collectdata = collectdata;
JPanel text = new JPanel();
text.add(jage);
text.add(age);
text.add(jheight);
text.add(height);
text.add(jweight);
text.add(weight);
text.setLayout(new GridLayout(3,2));
age.setEditable(false);
height.setEditable(false);
weight.setEditable(false);
setLayout(new BorderLayout());
add(text,BorderLayout.CENTER);
}
我希望能够从JFrame获取键控的数据,以便能够传递到第二个JFrame并使用该数据进行一些计算。
我怎么做?
谢谢。
通常,当向用户请求/提示信息时,您将使用某种对话框,这是一个短暂的单一目的窗口,其作用应该是从用户那里收集少量信息,提出问题。或提供某种信息通知。
您需要保持职责隔离,并尝试尽可能多地分离代码,例如,您的Calculate
类不关心信息的生成方式,而集合类不关心您将要做什么与信息。
为此,从创建一个自定义类开始,从JPanel
扩展,该类包含从用户收集数据所需的所有字段...
public class UserInfoEditorPane extends JPanel {
private JSpinner jage;
private JSpinner jheight;
private JSpinner jweight;
public UserInfoEditorPane() {
// Set the UI as you want...
}
public Collectdata getUserInfo() {
// Create a new instance of Collectdata
// and populate it with the values from
// the fields...
Collectdata data = ...;
//...
return data;
}
}
(nb我将Collectdata
用作POJO,而不是UI类)
现在,使用JOptionPane
类的东西,向用户显示面板...
UserInfoEditorPane userInfoPane = new UserInfoEditorPane();
switch (JOptionPane.showMessageDialog(null, userInfoPane, "User Info", JOptionPane.PLAIN_MESSAGE)) {
case JOptionPane.OK_OPTION:
Calculate secondwind = new Calculate(userInfoPane.getUserInfo());
secondwind.setTitle("Calculate"); //Set title
secondwind.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close program
secondwind.pack();
secondwind.setLocationRelativeTo(null);
secondwind.setVisible(true);
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.