[英]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.