Java EventHandler无法正常工作,为什么要创建新的Frame?

时间:2015-04-25 17:52:04

标签: java swing user-interface events handler

我正在尝试为uni项目创建一个地址簿,我试图让GUI能够将输入到表单的详细信息保存到文件中。每次我在GUI上单击“保存”时,它都会创建一个新的Frame,而不是执行我在Even Handler中放置的代码。我仍然是Java的新手,我只是看不出它有什么问题。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;


public class AddressBook {


static AddressBookGui addressBookGui = new AddressBookGui();

static int writeCount;

File detailsFile = new File("customerDetails.txt");


public static void saveDetails() throws IOException {

    String title = addressBookGui.txtTitle.getText();

    FileWriter fw = new FileWriter("customerDetails.txt");
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw);

    out.println(title);


    out.close();

    writeCount++;
    }

}

上面是Handler类,下面是GUI。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class AddressBookGui {

private JLabel lblTitle;
public JTextField txtTitle;
private JButton btnSaveDetails;
private JPanel panel;
private JFrame frame;

public static void main(String[] args) {
    new AddressBookGui();
}

public AddressBookGui() {

    createPanel();
    addLabels();
    addTextFields();
    addButtons();

    frame.add(panel);
    frame.setVisible(true);
}

public void createPanel() {

    frame = new JFrame();
    frame.setTitle("Address Book");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800,950);
    frame.setVisible(true);

    panel = new JPanel();
    panel.setLayout(null);
}

public void addLabels() {

    lblTitle = new JLabel("Title");
    lblTitle.setBounds(90,210,140,30);
    panel.add(lblTitle);

}

public void addTextFields() {

    txtTitle = new JTextField("");
    txtTitle.setBounds(190,210,150,30);
    panel.add(txtTitle);

}
public void addButtons() {

    btnSaveDetails = new JButton("Save");
    btnSaveDetails.setBounds(200,600,80,30);
    btnSaveDetails.addActionListener(new SaveDetailsButton());
    panel.add(btnSaveDetails);

}


public class SaveDetailsButton implements ActionListener {
    public void actionPerformed(ActionEvent event) {

        try {
            AddressBook.saveDetails();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "File did not write correctly.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

}

}

提前致谢。

0 个答案:

没有答案