使用另一个 class 格式化 JTextfields

formatting JTextfields using another class

这是 Gui 设计的代码 class 下面是为程序提供功能的 Class。我试图从文本字段中获取用户输入,这样我就可以使用 clearAll 方法删除文本,还可以使用 saveit method.I 尝试使用 nameEntry.setText(""); 保存用户输入;在 clearAll 方法中,但它不起作用,请有人帮助我!

//Import Statements
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.*;


//Class Name
public class Customer extends JFrame {
    Function fun = new Function();

    public static void main(String[]args){
        Customer.setLookAndFeel();
        Customer cust = new Customer();
    }


    public Customer(){
        super("Resident Details");
        setSize(500,500);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        FlowLayout two = new FlowLayout(FlowLayout.LEFT);
        setLayout(two);


        JPanel row1 = new JPanel();
        JLabel name = new JLabel("First Name",JLabel.LEFT);
        JTextField nameEntry = new JTextField("",20);
        row1.add(name);
        row1.add(nameEntry);
        add(row1);

        JPanel row2 = new JPanel();
        JLabel surname = new JLabel("Surname    ",JLabel.LEFT);
        JTextField surnameEntry = new JTextField("",20);
        row2.add(surname);
        row2.add(surnameEntry);
        add(row2);

        JPanel row3 = new JPanel();
        JLabel contact1 = new JLabel("Contact Details : Email                 ",JLabel.LEFT);
        JTextField contact1Entry = new JTextField("",10);
        FlowLayout newflow = new FlowLayout(FlowLayout.LEFT,10,30);
        setLayout(newflow);
        row3.add(contact1);
        row3.add(contact1Entry);
        add(row3);

        JPanel row4 = new JPanel();
        JLabel contact2 = new JLabel("Contact Details : Phone Number",JLabel.LEFT);
        JTextField contact2Entry = new JTextField("",10);
        row4.add(contact2);
        row4.add(contact2Entry);
        add(row4);

        JPanel row5 = new JPanel();
        JLabel time = new JLabel("Duration Of Stay                             ",JLabel.LEFT);
        JTextField timeEntry = new JTextField("",10);
        row5.add(time);
        row5.add(timeEntry);
        add(row5);


        JPanel row6 = new JPanel();
        JComboBox<String> type = new JComboBox<String>();
        type.addItem("Type Of Room");
        type.addItem("Single Room");
        type.addItem("Double Room");
        type.addItem("VIP Room");
        row6.add(type);
        add(row6);

        JPanel row7 = new JPanel();
        FlowLayout amt = new FlowLayout(FlowLayout.LEFT,100,10);
        setLayout(amt);
        JLabel amount = new JLabel("Amount Per Day                               ");
        JTextField AmountField = new JTextField("\u20ac ",10);
        row7.add(amount);
        row7.add(AmountField);
        add(row7);

        JPanel row8 = new JPanel();
        FlowLayout prc = new FlowLayout(FlowLayout.LEFT,100,10);
        setLayout(prc);
        JLabel price = new JLabel("Total Price                                         ");
        JTextField priceField = new JTextField("\u20ac ",10);
        row8.add(price);
        row8.add(priceField);
        add(row8);

        JPanel row9 = new JPanel();
        JButton clear = new JButton("Clear");
        row9.add(clear);
        add(row9);

        JPanel row10 = new JPanel();
        JButton save = new JButton("Save");
        save.addActionListener(fun);
        row10.add(save);
        add(row10);

        //Adding ActionListners
        nameEntry.addActionListener(fun);
        clear.addActionListener(fun);
        save.addActionListener(fun);

        setVisible(true);
    }

    private static void setLookAndFeel() {
            try {
                UIManager.setLookAndFeel(
                    "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
                );
            } catch (Exception exc) {
            // ignore error
                }
    }

}

//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.awt.event.*;


//Class Name
public class Function implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if(command.equals("Add Customer")) {
            Login();
        }
        else if(command.equals("Register")){
            Registration();
        }
        else if(command.equals("Exit")){
            System.exit(0);
        }       
        else if(command.equals("Clear")){
            ClearAllFields();
        }
        else if(command.equals("Save")){
            SaveIt();
        }
    }

    public static void Login(){
        Customer cust = new Customer();
    }

    public static void Registration(){
        //Do Nothing

    }
    //This clears all the text from the JTextFields
    public static void ClearAllFields(){

    }

    //This will save Info on to another Class
    public static void SaveIt(){


    }


}

再次根据评论,解决此问题的一种简单方法是提供控制器(侦听器)可以调用的 gui public 方法,然后将当前显示的 GUI 实例传递给侦听器,允许它调用 GUI 可能具有的任何 public 方法。下面的代码比你的简单,只有一个 JTextField,但它可以说明这一点:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class GUI extends JPanel {
    private JTextField textField = new JTextField(10);
    private JButton clearButton = new JButton("Clear");

    public GUI() {
        // pass **this** into the listener class
        MyListener myListener = new MyListener(this);
        clearButton.addActionListener(myListener);
        clearButton.setMnemonic(KeyEvent.VK_C);

        add(textField);
        add(clearButton);
    }

    // public method in GUI that will do the dirty work
    public void clearAll() {
        textField.setText("");
    }

    // other public methods here to get text from the JTextFields
    // to set text, and do whatever else needs to be done

    private static void createAndShowGui() {
        GUI mainPanel = new GUI();

        JFrame frame = new JFrame("GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class MyListener implements ActionListener {
    private GUI gui;

    // use constructor parameter to set a field
    public MyListener(GUI gui) {
        this.gui = gui;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        gui.clearAll();  // call public method in field
    }
}

一个更好更稳健的解决方案是以模型-视图-控制器的方式构建您的程序(查看这个),但是对于您正在做的这个简单的学术练习来说,这可能有点过头了。

或者,您可以在调用 Function 的构造函数之前定义它,然后将其传递给构造函数,从而使 Function class 知道 nameEntry,例如:

JTextField nameEntry = new JTextField("",20);

Function fun = new Function(nameEntry);

然后,在Function中,将nameEntry添加为Function的成员变量,并为Function构造一个接受nameEntry的构造函数,(在"public class Function..."行之后),如:

JTextField nameEntry;

public Function(JTextField nameEntry) {
    this.nameEntry = nameEntry;
}

现在,将编译以下内容:

public void ClearAllFields(){
    nameEntry.setText("");
}

并且,清除按钮将清除名称字段。