我創建了一個貨幣兌換計算器從互聯網上導入它的日期,將它存儲在一個.dat文件中,並將其所有數據顯示在JTable中。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
方法始終會從數據庫中獲取數據。如果從菜單中單擊更新,則從現在開始更新的所有內容對於表格都是徒勞的,但「計算器」仍將使用數據庫中的更新值。
''我不相信剩下的代碼是需要的,但如果它確實讓我知道......「 - 請看[mcve]和[SSCCE](http:// sscce .org)鏈接來查看*確切的*需要什麼代碼。這不是代碼的其餘部分,而是更多的代碼,足以讓我們編譯,運行代碼不變(無數據庫允許),並遇到問題,但足夠小以便在代碼格式的文本中發佈在您的問題中。 –
@HovercraftFullOfEels,我已經添加了更多的代碼部分,如果他需要整個代碼,請告訴我,所以它會更容易編譯 – Voxito
請閱讀或重新閱讀我上面發佈的鏈接。他們會解釋(以及我已經說過的)爲什麼我們絕對不想看到整個程序,以及爲什麼你發佈的代碼段不如我們試圖讓你發佈的內容有幫助。請在回覆前閱讀鏈接*。 –