gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:19:00 26 4
gpt4 key购买 nike

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

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

类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();
}

下面是分配给 JButton“添加帐户...”的代码块,可在下面的 BankAppGUI.java 中找到。这有很多检查和平衡,以确保用户输入有效。我的主要问题是,在此之下,我希望能够从 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当您第一次运行程序时,此类包含主应用程序,有四个 JButton 可供选择: 添加帐户(它导致 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);
}

}

最佳答案

I want to be able to create an object out of the Customer class (which I can provide if needed) and assign that data onto the JTable

那么您应该首先创建一个CustomTableModel。这是一个包含 Customer 对象的 TableModel。查看Row Table Model了解创建自定义模型的分步方法。

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

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

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

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

您现在可以定义您的表,如下所示:

private CustomTableModel customTableModel = new CustomTableModel();
private JTable accountable = new JTable( customTableModel );
//private JTable accountTable;

最后一个问题。类中的所有代码都引用“帐户”,但您将业务对象称为“客户”。我认为你应该保持一致,并将一切称为“帐户”。

关于java - 如何将对象中的数据插入到 Eclipse 生成的 JTable 中? (请不要数据库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43667043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com