我创建了一个货币兑换计算器,从互联网上输入日期,将其存储在.dat文件中,并在JTable中显示其所有数据。
它应该按照以下方式工作,如果你更新JTable,计算器使用的汇率,也将改变,它曾经工作得很好,直到我需要从数据库本身导入JTable的数据。 我还有一个方法可以手动更新数据库中的所有数据,这些数据可以作为堆栈使用,而表和计算器应该始终采用上次导入的货币汇率中的数据。
现在的问题是,当你第一次自己手动编辑表时,它可以很好地工作,但是如果我使用这种方法更新数据,它将按原样更新数据,并且计算器将使用更新的数据,但表格不再有效。意思是,在使用该方法后,它不再更新表格,手动编辑表格中的数据不会影响计算器使用的数据。
更新数据库时有没有办法更新整个表格? 现在它的工作方式如下: JTable构造函数接受数据库中的第一个元素,当我更新数据库时,我认为该表根本没有影响。
我已经创建了一个更简化的代码来显示问题:
package calc.test;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class main_calc {
private JFrame main_frame, table_frame;
private JMenuBar menuBar;
private JScrollPane scrollpane;
private JTable my_table;
private TableRowSorter<TableModel> rowSorter;
private String[] columns = { "Name", "Unit", "Currency", "Country", "Rate", "Change" };
private JMenuItem view_table, updates;
private JMenu File_;
private JButton Show_value;
private static JTextField result_field;
private JTextField jtFilter;
private static Database my_data;
private JPanel top_right_frame, bottom_left_frame, bottom_right_frame;
private JPanel table_panel;
private static JComboBox<String> from_ComBox;
private JLabel search_label;
final static private String[] Currencies = { "NIS", "USD", "GBP", "JPY", "EUR", "AUD", "CAD", "DKK", "NOK", "ZAR",
"SEK", "CHF", "JOD", "LBP", "EGP" };
private boolean was_created = false;
public main_calc() {
my_data = new Database();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
main_frame = new JFrame("My Currency Exchange Calcualtor");
menuBar = new JMenuBar();
File_ = new JMenu("File");
File_.setMnemonic(KeyEvent.VK_F);
updates = new JMenuItem("Update currrencies");
updates.setMnemonic(KeyEvent.VK_F);
updates.addActionListener((ActionEvent event) -> {
try {
Extraction_BOI(my_data);
} catch (Exception e) {
e.printStackTrace();
}
});
view_table = new JMenuItem("Table");
table_frame = new JFrame("Currencies' Table");
table_panel = new JPanel();
table_panel.setLayout(new BorderLayout());
table_frame.setLayout(new BorderLayout());
table_frame.setSize(540, 277);
table_frame.setResizable(false);
view_table.setMnemonic(KeyEvent.VK_F);
view_table.addActionListener((ActionEvent event) -> {
if (!(was_created)) {
try {
Table_Creation();
search_label = new JLabel();
search_label.setText("Search:");
table_panel.add(search_label, BorderLayout.WEST);
table_panel.add(jtFilter, BorderLayout.CENTER);
table_frame.add(scrollpane, BorderLayout.CENTER);
table_frame.add(table_panel, BorderLayout.SOUTH);
jtFilter.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
String text = jtFilter.getText();
if (text.trim().length() == 0) {
rowSorter.setRowFilter(null);
} else {
rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
}
}
@Override
public void removeUpdate(DocumentEvent e) {
String text = jtFilter.getText();
if (text.trim().length() == 0) {
rowSorter.setRowFilter(null);
} else {
rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
}
}
@Override
public void changedUpdate(DocumentEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
table_frame.setVisible(true);
was_created = true;
});
Show_value = new JButton("Show");
result_field = new JTextField(10);
top_right_frame = new JPanel();
bottom_right_frame = new JPanel();
bottom_left_frame = new JPanel();
from_ComBox = new JComboBox<>(Currencies);
try {
Extraction_BOI(my_data);
} catch (Exception e) {
e.printStackTrace();
}
main_frame.setLocation(dim.width / 2 - main_frame.getSize().width / 2,
dim.height / 2 - main_frame.getSize().height / 2);
table_frame.setLocation(dim.width / 2 - table_frame.getSize().width / 2,
dim.height / 2 - table_frame.getSize().height / 2);
}
public void start() {
main_frame.setLayout(new GridLayout(0, 2));
menuBar.add(File_);
File_.add(view_table);
File_.add(updates);
main_frame.setJMenuBar(menuBar);
main_frame.add(top_right_frame);
main_frame.setResizable(false);
main_frame.setSize(400, 200);
main_frame.setVisible(true);
top_right_frame.setLayout(new FlowLayout());
top_right_frame.add(from_ComBox);
main_frame.add(bottom_left_frame);
main_frame.add(bottom_right_frame);
bottom_left_frame.add(Show_value);
bottom_right_frame.add(result_field);
Show_value.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
main_calc.get_table_cell();
}
});
main_frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public String[][] Extraction_BOI(Database my_data) throws Exception {
URL url = new URL("http://www.boi.gov.il/currency.xml");
String[] str = { "NAME", "UNIT", "CURRENCYCODE", "COUNTRY", "RATE", "CHANGE", "LAST_UPDATE" };
String listOfAll[][] = new String[15][7];
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
InputStream in = con.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(in);
int i = 0, j = 1, k = 0;
listOfAll[0][0] = "Shekel";
listOfAll[0][1] = "1";
listOfAll[0][2] = "NIS";
listOfAll[0][3] = "ISR";
listOfAll[0][4] = "1";
listOfAll[0][5] = "0";
listOfAll[0][6] = "-";
// Copy XML Elements into NodeLists//
NodeList listName = doc.getElementsByTagName(str[0]);
NodeList listUnit = doc.getElementsByTagName(str[1]);
NodeList listCurrencyCode = doc.getElementsByTagName(str[2]);
NodeList listCountry = doc.getElementsByTagName(str[3]);
NodeList listRate = doc.getElementsByTagName(str[4]);
NodeList listChange = doc.getElementsByTagName(str[5]);
// Copy all the NodeLists into String array named listOfAll//
for (i = 0; i < listName.getLength(); i++, j++, k = 0) {
listOfAll[j][k] = listName.item(i).getTextContent();
k += 1;
listOfAll[j][k] = listUnit.item(i).getTextContent();
k += 1;
listOfAll[j][k] = listCurrencyCode.item(i).getTextContent();
k += 1;
listOfAll[j][k] = listCountry.item(i).getTextContent();
k += 1;
listOfAll[j][k] = listRate.item(i).getTextContent();
k += 1;
listOfAll[j][k] = listChange.item(i).getTextContent();
k += 1;
}
in.close();
con.disconnect();
try {
my_data.put(listOfAll);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
my_data.serialize();
return listOfAll;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main_calc gui = new main_calc();
gui.start();
}
});
}
public static void get_table_cell() {
String[][] datas;
datas = my_data.peek();
int from_Index = from_ComBox.getSelectedIndex();
String result = datas[from_Index][4];
result_field.setText(String.valueOf(result));
}
@SuppressWarnings("serial")
public void Table_Creation() throws Exception {
this.my_table = new JTable(my_data.peek(), columns) {
public boolean isCellEditable(int row, int column) {
if (my_table.getValueAt(row, 0) == "Shekel" || column != 4)
return false;
return true;
}
};
this.scrollpane = new JScrollPane(my_table);
my_table.setFillsViewportHeight(true);
TableColumn column = null;
for (int i = 0; i < 5; i++) {
column = my_table.getColumnModel().getColumn(i);
column.setPreferredWidth(30);
}
rowSorter = new TableRowSorter<>(my_table.getModel());
jtFilter = new JTextField();
my_table.setRowSorter(rowSorter);
}
}
数据库类:
package calc.test;
import java.util.Vector;
import java.io.*;
@SuppressWarnings("serial")
public class Database extends Vector<String[][]> {
Database() {
super();
}
void put(String[][] o) {
addElement(o);
}
String[][] peek() {
if (isEmpty()) return null;
return (String[][]) lastElement();
}
void serialize(){
try {
FileOutputStream fout = new FileOutputStream("mydata.dat");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(this);
oos.close();
}
catch (Exception e) { e.printStackTrace(); }
}
}
在我创建的代码中,我删除了接口并删除了大部分内容。
如果要手动更新表,并单击show,它将显示您输入的更新值,因此它会更新数据库,因为get_table_cell
方法始终从数据库中获取数据。如果您点击菜单中的更新,那么从现在开始更新的所有内容对于表格来说都是徒劳的,但是&#34;计算器&#34;仍将使用数据库中的更新值。
答案 0 :(得分:0)
最终我设法通过一些解决方法来解决这个问题。
我已经改变了JTable构造函数将接收tableModel,而不是String [] []和列,这样,每当我更新数据库时,我只是编辑tableModel。
对于计算器转换方法,在上面列为get_table_cell
的代码中,我已经从JTable获取数据,因为每次单击udpate按钮时我总是更新表,计算器将一直使用更新的数据,所以现在当我手动编辑表时,即使在第一次更新后,我仍然可以给计算器手动数据,而不仅仅是数据库。
我做到了这样的事情:
一些表创建方法:
public void tableCreation() throws Exception {
modelTable = new DefaultTableModel(myDatabase.peek(), columns);
BOI_Calculator.myTable = new JTable(modelTable);
计算器方法,从表中获取数据:
outcome = convertFromSum * ((Double.parseDouble((String) myTable.getValueAt(fromIndex, 4)))
/ (Double.parseDouble((String) myTable.getValueAt(toIndex, 4))));
outcome = Double.parseDouble(new DecimalFormat("##.####").format(outcome));
outputField.setText(String.valueOf(outcome));
这就是我每次点击更新按钮时更新数据库和表格的方式:
extractData(myDatabase);
String[][] temp = myDatabase.peek();
DefaultTableModel temp2 = new DefaultTableModel(temp, columns);
myTable.setModel(temp2);