我在做一个非常简单的费用追踪器:
public class ExpenseTracker {
JFrame frame;
JPanel mainPanel;
JPanel inputPanel;
JPanel registerPanel;
DefaultTableModel tableModel;
JDatePicker datePicker;
JTextField nameTextField;
JTextField amountTextField;
SimpleDateFormat sdf;
Date date;
public static void main(String[] args) {
new ExpenseTracker().buildGUI();
}
public void buildGUI() {
mainPanel = new JPanel();
inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
JLabel nameLabel = new JLabel("Name: ");
nameLabel.setFont(new Font("Arial", Font.ITALIC, 25));
nameTextField = new JTextField();
nameTextField.setDocument(new JTextFieldLimit(10));
JLabel dateLabel = new JLabel("Date: ");
dateLabel.setFont(new Font("Arial", Font.ITALIC, 25));
datePicker = new JDatePicker();
JLabel amountLabel = new JLabel("Amount: ");
amountLabel.setFont(new Font("Arial", Font.ITALIC, 25));
amountTextField = new JTextField();
amountTextField.setDocument(new JTextFieldLimit(5));
JButton addExpense = new JButton("Add");
addExpense.addActionListener(new addExpenseListener());
inputPanel.add(nameLabel);
inputPanel.add(nameTextField);
inputPanel.add(dateLabel);
inputPanel.add(datePicker);
inputPanel.add(amountLabel);
inputPanel.add(amountTextField);
inputPanel.add(addExpense);
registerPanel = new JPanel();
tableModel = new DefaultTableModel();
JTable register = new JTable(tableModel);
tableModel.addColumn("Name");
tableModel.addColumn("Date");
tableModel.addColumn("Amount");
register.setBackground(Color.LIGHT_GRAY);
registerPanel.add(register);
mainPanel.add(BorderLayout.NORTH, inputPanel);
mainPanel.add(BorderLayout.CENTER, registerPanel);
frame.add(mainPanel);
frame.setVisible(true);
}
public void addToRegister() {
String name = nameTextField.getText();
sdf = new SimpleDateFormat();
Date dateToFormat = (Date) datePicker.getModel().getValue();
String date = sdf.format(dateToFormat);
String amount = amountTextField.getText();
tableModel.addRow(new Object[] {name, date, amount});
}
省略了一些代码。我得到了一个异常:
无法将类java.util.GregorianCalendar强制转换为类java.util.Date(java.util.GregorianCalendar和java.util.Date位于加载程序“引导”的模块java.base中)
我不知道如何改变它,我知道的是如何从DatePicker中获取日期,这是类冲突的地方,使用jdatepicker库。
1条答案
按热度按时间5t7ly7z51#
Java.时间
java.util
Date-Time API及其格式化APISimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到modern Date-Time API。首先,进行以下更改(检查
Calendar#getTime
以了解更多信息)然后切换到
java.time
API,如下所示:现在,您可以在组件中使用
formattedDateStr
。得到
ZonedDateTime
的另一种方法可以如Ole V. V.所建议的:从**Trail: Date Time**了解有关现代日期-时间API的更多信息。