如何将对象中的数据插入到Eclipse生成的JTable中? (请不要数据库)

时间:2017-04-27 20:07:05

标签: java eclipse swing user-interface jtable

这是我在Stack Overflow上的第一篇文章,所以如果我错误地使用这个列表,请原谅我。我还在学习这个系统。 :P

我有一个问题,如何能够从另一个类创建一个对象,并使用该数据将其存储在BankAppGUI主类中找到的JTable中(更多信息见下文)

Class AddAccountMenu():

package A09Project;

import javax.swing.JDialog;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.awt.event.ActionEvent;

@SuppressWarnings("unused")

public class AddAccountMenu extends JDialog {

    private static final long serialVersionUID = -2200080161616216223L;
    private JTextField initDepositField;
    private JTextField ssnField;
    private JTextField lastNField;
    private JTextField firstNField;
    private JComboBox<String> typeField;

    private String lastName;
    private String firstName;
    private String ssn;
    private double amount;
    private Bank bank;
    private Customer cust;
    private Account account;

    private void cancelButtonActionPerformed(ActionEvent arg0) {
        this.dispose();
    }

下面是一个代码块,分配给下面包含的BankAppGUI.java上的JButton“Add Account ...”。 这有许多检查和平衡,以确保用户输入有效。 我的主要问题是,在此之下,我希望能够从Customer类(我可以根据需要提供)中创建一个对象,并将该数据分配给BankAppGUI.java上的JTable。有解决方案吗让我知道我可能缺少什么。

    private void finishButtonAddAccActionPerformed(ActionEvent arg0) {
        StringBuilder warnings = new StringBuilder();
        String firstName = "", lastName = "", ssn = "", depositString = "";
        double amount = 0;
        //Verify first name field
        if (firstNField.getText().isEmpty()) {
            warnings.append("First name must not be empty.\n");
        } else {
            firstName = firstNField.getText();
        }
        //Verify last name field
        if (lastNField.getText().isEmpty()) {
            warnings.append("Last name must not be empty.\n");
        } else {
            lastName = lastNField.getText();
        }
        if (!ssnField.getText().matches("\\d{3}-?\\d{2}-?\\d{4}")) {
            warnings.append("SSN must be 9 digits, dashes are acceptable.\n");
        } else {
            ssn = ssnField.getText().replace("-", "");
        }
        //Verify initial deposit
        if (initDepositField.getText().isEmpty()) {
            warnings.append("Initial deposit must be entered.");
        } else {
            try {
                amount = Bank.round(Double.parseDouble(initDepositField.getText()), 2);
            } catch (NumberFormatException ex) {
                warnings.append("Initial deposit must be a number.");
            }
        }
        if (warnings.length() > 0) {
            JOptionPane.showMessageDialog(this, warnings.toString(), "Input Warnings", JOptionPane.WARNING_MESSAGE);
        } else {
            AccountType accountType = AccountType.UNDEFINED;
            if (typeField.getSelectedItem().toString() == "Checkings") {
                if (amount >= 50) {
                    accountType = AccountType.CHECKINGS;
                } else {
                    warnings.append("Checkings accounts require at least a $50 initial deposit.");
                }
            } else if (typeField.getSelectedItem().toString() == "Savings") {
                if (amount >= 25) {
                    accountType = AccountType.SAVINGS;
                } else {
                    warnings.append("Savings accounts require at least a $25 initial deposit.");
                }
            }
            if (accountType != AccountType.UNDEFINED) {
                Customer cust = new Customer(firstName, lastName, ssn, account);


                this.dispose();

            } else {
                JOptionPane.showMessageDialog(this, warnings.toString(), "Input Warnings", JOptionPane.WARNING_MESSAGE);
            }

        }
    }
    public void fillWithAccount(int firstName, int lastName, int ssn, int amount) {
        //this is the method that I am trying to create to initialize 
    }
    public AddAccountMenu(final javax.swing.JFrame parent, boolean modal, Bank bank) {
        super(parent, modal);
        setResizable(false);
        setTitle("Add account...");
        setBounds(100, 100, 391, 260);
        setLocationRelativeTo(parent);
        this.bank = bank;
        cust = null;
        getContentPane().setLayout(new GridLayout(6, 2, 5, 5));

        JLabel fNameAddAccLabel = new JLabel("First name: ");
        getContentPane().add(fNameAddAccLabel);

        firstNField = new JTextField();
        firstNField.setToolTipText("");
        getContentPane().add(firstNField);
        firstNField.setColumns(10);

        JLabel lNameAddAccLabel = new JLabel("Last name:");
        getContentPane().add(lNameAddAccLabel);

        lastNField = new JTextField();
        getContentPane().add(lastNField);
        lastNField.setColumns(10);

        JLabel ssnAddAccLabel = new JLabel("Social Security #:");
        getContentPane().add(ssnAddAccLabel);

        ssnField = new JTextField();
        getContentPane().add(ssnField);
        ssnField.setColumns(10);

        JLabel initDepositAddAccLabel = new JLabel("Initial deposit:");
        getContentPane().add(initDepositAddAccLabel);

        initDepositField = new JTextField();
        getContentPane().add(initDepositField);
        initDepositField.setColumns(10);

        JLabel acctTypeAddAccLabel = new JLabel("Account type:");
        getContentPane().add(acctTypeAddAccLabel);

        typeField = new JComboBox<String>();
        typeField.setModel(new DefaultComboBoxModel<String>(new String[] {"Checkings", "Savings"}));
        getContentPane().add(typeField);

        JButton cancelBtnAddAcc = new JButton("Cancel");
        cancelBtnAddAcc.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                cancelButtonActionPerformed(arg0);
            }
        });
        getContentPane().add(cancelBtnAddAcc);

        JButton finBtnAddAcc = new JButton("Finish");
        finBtnAddAcc.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                finishButtonAddAccActionPerformed(arg0);
            }
        });
        getContentPane().add(finBtnAddAcc);
    }


}

主要课程:BankAppGUI Screenshot 这个类包含了第一次运行程序时的主应用程序,有四个JButtons可供选择:添加帐户(通向JDialog [AddAccountMenu.java]我试图将对象数据从这里添加到我的JTable中主类(不使用mySQL或任何其他数据库),删除帐户,存款和提款。

package A09Project;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.JMenuItem;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class GUIBankApp extends JFrame {

    private static final long serialVersionUID = 1100618131811836737L;
    private Bank bank;
    private JPanel contentPane;
    private JTable accountTable;
    private List list = new List();

    private void addAccountButtonActionPerformed(ActionEvent arg0) {
        AddAccountMenu menu = new AddAccountMenu(this, true, bank);
        menu.setVisible(true);
        System.out.println();
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUIBankApp frame = new GUIBankApp();
                    frame.setVisible(true);
                    frame.setTitle("Coffee Bank Unlimited™");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @SuppressWarnings("serial")
    public GUIBankApp() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 565, 415);
        setLocationRelativeTo(null);
        bank = new Bank();
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        JMenu fileMenu = new JMenu("File");
        menuBar.add(fileMenu);

        JMenuItem exitItem = new JMenuItem("Exit");
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        exitItem.setSelectedIcon(new ImageIcon(GUIBankApp.class.getResource("/A09Project/exitIcon.png")));
        exitItem.setIcon(new ImageIcon(GUIBankApp.class.getResource("/A09Project/exitIcon.png")));
        fileMenu.add(exitItem);

        JMenu editMenu = new JMenu("Edit");
        menuBar.add(editMenu);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JPanel panel = new JPanel();

        JPanel panel_1 = new JPanel();
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.TRAILING)
                .addComponent(panel, GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
                .addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE))
        );
        panel_1.setLayout(new BorderLayout(0, 0));

        JScrollPane scrollPane = new JScrollPane();
        panel_1.add(scrollPane, BorderLayout.CENTER);

        accountTable = new JTable();
        accountTable.setModel(new DefaultTableModel(
            new Object[][] {
                {"Haden", "Butikofer", new Integer(8734297), null},
            },
            new String[] {
                "First Name", "Last Name", "Acct. #", "Balance"
            }
        ) {
            Class[] columnTypes = new Class[] {
                String.class, String.class, Integer.class, Double.class
            };
            public Class getColumnClass(int columnIndex) {
                return columnTypes[columnIndex];
            }
        });
        accountTable.getColumnModel().getColumn(0).setResizable(false);
        accountTable.getColumnModel().getColumn(1).setResizable(false);
        accountTable.getColumnModel().getColumn(2).setResizable(false);
        accountTable.getColumnModel().getColumn(3).setResizable(false);
        scrollPane.setViewportView(accountTable);

        JButton btnAddAcc = new JButton("Add account...");
        btnAddAcc.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                addAccountButtonActionPerformed(arg0);
            }
        });
        panel.add(btnAddAcc);

        JButton btnDelAcc = new JButton("Remove account...");
        panel.add(btnDelAcc);

        JButton btnDeposit = new JButton("Deposit funds...");
        panel.add(btnDeposit);

        JButton btnWithdraw = new JButton("Withdraw funds...");
        panel.add(btnWithdraw);
        contentPane.setLayout(gl_contentPane);
    }

}

1 个答案:

答案 0 :(得分:1)

  

我希望能够在Customer类中创建一个对象(如果需要,我可以提供)并将该数据分配到JTable

那么你应该首先创建一个Prelude Control.Lens> iover (itraversed . traversed) (,) [[1,2],[3]] [[(0,1),(1,2)],[(0,3)]] 。这是CustomTableModel,其中包含TableModel个对象。查看Row Table Model了解创建自定义模型的分步方法。

然后在您创建Custom对象的对话框中,您可以传入对TableModel的引用,以便您可以更新TableModel。

Customer

然后,当您显示对话框时,需要将TableModel添加为参数:

Customer cust = new Customer(firstName, lastName, ssn, account);
customTableModel.addCustomer( cust );
this.dispose();

您现在可以为表定义如下内容:

//AddAccountMenu menu = new AddAccountMenu(this, true, bank);
AddAccountMenu menu = new AddAccountMenu(this, true, bank, customTableModel);

最后一个问题。您班级中的所有代码都引用了&#34;帐户&#34;,但您将业务对象称为&#34;客户&#34;。我认为你应该保持一致,并将所有内容称为&#34;帐户&#34;。