[英]Sending Jframe Jtextfield to another class
我有一個有textfield
和button
的JFrame
。 它應該在程序開始時可見,當我點擊按鈕時,它應該變為不可見,並將textfield的文本發送到另一個類。 但它什么也沒發送,當我點擊按鈕時,IDE進入調試模式。
public class JframeFoo extends JFrame {
private String username = new String();
public JframeFoo() {
// --------------------------------------------------------------
// Making Frame for login
final JTextField usernameFiled = new JTextField();
this.add(usernameFiled);
JButton signinButton = new JButton();
// ------------------------------------------------------------
signinButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
username = usernameFiled.getText();
setVisible(false);
Main.mainpage.setVisible(true);
}
});
// --------------------------------------------------------------------------
}
public String getuserName() {
return this.username;
}
}
我的另一個類調用Jframe:
System.out.println(JframeFoo.getusername);
暫時忽略向用戶跳出多個JFrame並不是一個很好的用戶界面設計,對於一個對象與另一個對象進行通信,它必須具有對另一個對象的有效引用。 (抱歉被女兒打斷了)。
因此,對於一個JFrame類從另一個獲取信息,它必須具有對獲取文本的第一個對象的引用,並且我沒有看到您傳遞該引用,例如在構造函數或setter方法中。
因此,例如,如果Class1的對象具有Class2對象所需的信息,那么傳遞它的一種方法是為Class2提供對Class1的有效實例的引用,然后讓Class2從Class1實例獲取信息。 例如,
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ClassMain {
private static void createAndShowGui() {
ClassMain mainPanel = new ClassMain();
JFrame frame = new Class1();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Class1 extends JFrame {
private JTextField textfield = new JTextField(10);
public Class1() {
JPanel contentPane = (JPanel) getContentPane();
contentPane.setLayout(new FlowLayout());
add(textfield);
add(new JButton(new AbstractAction("Open Window") {
@Override
public void actionPerformed(ActionEvent arg0) {
Class2 class2 = new Class2(Class1.this);
Class1.this.setVisible(false);
class2.pack();
class2.setVisible(true);
class2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}));
}
public String getTextfieldText() {
return textfield.getText();
}
}
class Class2 extends JFrame {
private Class1 class1;
private JLabel label = new JLabel("");
public Class2(Class1 class1) {
this.class1 = class1;
label.setText(class1.getTextfieldText());
add(label);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.