使用textfield键入预设值,然后打印出该值

时间:2016-11-01 08:21:03

标签: java

我做了class a

class a
int account
string first name
string last name
int balance

然后我在textfield中创建class b

class b
textField_4 = new JTextField();
    textField_4.setBounds(210, 123, 150, 30);
    getContentPane().add(textField_4);
    textField_4.setColumns(10);

    JButton btnNewButton = new JButton("Enter");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
                PrintStream diskWriter = new PrintStream("");
                diskWriter.print("Account: ");
                diskWriter.println(account);

如何将class a account中的值写入class b textfield

2 个答案:

答案 0 :(得分:0)

所以你的"帐户"变量是在一个不同的类中,你想把它放在你的文本域?

您可以将自己的帐户变量声明为public int account;,并且为了调用它,您必须使用class_b variable = new class_b();,并将其放在文本字段中,您将使用{{1 }}

希望我帮忙!

答案 1 :(得分:0)

尝试这样的方法从textField获取文本并将其打印到文本文件:

更新: 第一类:

public class ClassB {

int account = 3000;
String firstname = "Coder";
String lastname = "ACJHP";
int balance = 300;

public String getDatas() {
    return new String(account + firstname + lastname + balance);
  }
}

这是另一类:

textField = new JTextField();
    ClassB classB = new ClassB(); //INITIALIZING FIRST CLASS
    textField.setText(classB.getDatas());//THERE GETTING THE TEXT AND ADDING TO TEXTFIELD
    textField.setBounds(97, 28, 151, 42);
    contentPane.add(textField);
    textField.setColumns(10);

    JButton btnPrintIt = new JButton("Print it!");
    btnPrintIt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = textField.getText();
            if(!text.equals(null) || text.length() > 0){


                File file = new File("text.txt");                   
                PrintStream printStream;
                try {
                    printStream = new PrintStream(file);
                    printStream.println(text);

                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }   

            }
        }
    });