我正在制作一个小程序,它从sqlite数据库中检索数据并填充JTable。用户还可以通过适当的表单填充数据库。问题是,如何更新JTable以显示用户添加的内容?目前,它仅在重新运行整个应用程序后显示它。
这是表格的代码:
package kpkw;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import static javax.swing.WindowConstants.EXIT_ON_CLOSE;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
public class MainTable {
//protected List<List<Object>> allMembers = new ArrayList<>();
//protected List<Object> member = new ArrayList<>();
protected MainTable(){
}
private void PassFromDBtoTable(List<List<Object>> allMembers){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
try {
c = DriverManager.getConnection("jdbc:sqlite:HistoriaPrzeplywow.s3db");
c.setAutoCommit(false);
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT * FROM HistoriaPrzeplywow;" );
while ( rs.next() ) {
List<Object> member = new ArrayList();
int idSQL = rs.getInt("ID");
String id2SQL = rs.getString("ID2");
int id3SQL = rs.getInt("ID3");
String typSQL = rs.getString("Typ");
String imieSQL = rs.getString("Imie");
String nazwiskoSQL = rs.getString("Nazwisko");
int naleznoscSQL = rs.getInt("Naleznosc");
String tytulemSQL = rs.getString("Tytulem");
String dataSQL = rs.getString("Data");
member.add(idSQL);
member.add(id2SQL);
member.add(id3SQL);
member.add(typSQL);
member.add(imieSQL);
member.add(nazwiskoSQL);
member.add(ManageCurrency(naleznoscSQL));
member.add(tytulemSQL);
member.add(dataSQL);
allMembers.add(member);
}
}
catch ( SQLException e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
finally{
if(rs!=null&& stmt!=null && c!=null){
try{
rs.close();
stmt.close();
c.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
}
private String ManageCurrency(int naleznoscSQL){
String currency = Integer.toString(naleznoscSQL);
currency = new StringBuilder(currency).insert(currency.length()-2, ".").toString();
return currency;
}
private void ResizeColumnWidth(JTable table){
final TableColumnModel columnModel = table.getColumnModel();
for(int col = 0; col < table.getColumnCount(); col++){
int width = 70;
for(int row = 0; row < table.getRowCount(); row++){
TableCellRenderer renderer = table.getCellRenderer(row, col);
Component component = table.prepareRenderer(renderer, row, col);
int componentSize = component.getPreferredSize().width;
width = Math.max(componentSize ,width);
}
columnModel.getColumn(col).setPreferredWidth(width);
}
} // method doesn't work so far
private void initUI(){
JFrame mainFrame = new JFrame();
JPanel mainPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu plikMenu = new JMenu("Plik");
List<List<Object>> allMembers = new ArrayList<>();
List<Object> member = new ArrayList<>();
PassFromDBtoTable(allMembers);
for(int i = 0; i< member.size(); i++){
System.out.println(member.get(i));
}
MyTableModel mtb = new MyTableModel(allMembers);
JTable rekordy = new JTable(mtb);
JScrollPane scrollPane = new JScrollPane(rekordy);
ResizeColumnWidth(rekordy);
rekordy.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
rekordy.setAutoCreateRowSorter(true);
JMenuItem noweKPMenuItem = new JMenuItem("Nowe KP...");
JMenuItem noweKWMenuItem = new JMenuItem("Nowe KW...");
JMenuItem zakonczMenuItem = new JMenuItem("Zakończ");
mainFrame.setLayout(new BorderLayout());
mainFrame.setTitle("Historia Przepływów");
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.setSize(660, 200);
mainFrame.setJMenuBar(menuBar);
//JButton test = new JButton("test");
//mainFrame.add(mainPanel);
mainPanel.setLayout(new BorderLayout());
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
mainPanel.add(scrollPane, BorderLayout.CENTER);
//mainPanel.add(test);
menuBar.add(plikMenu);
plikMenu.add(noweKPMenuItem);
plikMenu.add(noweKWMenuItem);
plikMenu.add(zakonczMenuItem);
mainFrame.add(scrollPane, BorderLayout.CENTER);
mainFrame.setVisible(true);
noweKPMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
//KP run = new KP();
KP.run();
}
});
}
public class MyTableModel extends AbstractTableModel{
protected List<List<Object>> allMembers = new ArrayList<>();
public MyTableModel (List<List<Object>> allMembers) {
this.allMembers = allMembers;
}
protected MyTableModel(){
}
String[] columnNames = {"ID", "ID2", "ID3", "Typ", "Imię", "Nazwisko","Należność", "Tytułem", "Data"};
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public int getRowCount() {
return allMembers.size();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
//List<Object> row = allMembers.get(rowIndex);
return allMembers.get(rowIndex).get(columnIndex);
}
@Override
public boolean isCellEditable(int row, int column)
{
return false;
}
protected void addRecord(int ID, String ID2, int ID3, String typ, String imie, String nazwisko, int naleznosc, String tytulem, String data){
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:HistoriaPrzeplywow.s3db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
//pstmt = c.createStatement();
String sqlCommand = ("INSERT INTO HistoriaPrzeplywow (ID,ID2,ID3,Typ,Imie,Nazwisko,Naleznosc,Tytulem,Data) VALUES (?,?,?,?,?,?,?,?,?);");
pstmt = c.prepareStatement(sqlCommand);
pstmt.setInt(1, ID);
pstmt.setString(2, ID2);
pstmt.setInt(3, ID3);
pstmt.setString(4, typ);
pstmt.setString(5, imie);
pstmt.setString(6, nazwisko);
pstmt.setInt(7, naleznosc);
pstmt.setString(8, tytulem);
pstmt.setString(9, data);
pstmt.executeUpdate();
c.commit();
List<Object> rowData = new ArrayList<>();
rowData.add(ID);
rowData.add(ID2);
rowData.add(ID3);
rowData.add(typ);
rowData.add(imie);
rowData.add(nazwisko);
rowData.add(tytulem);
rowData.add(data);
allMembers.add(rowData);
fireTableDataChanged();
}
catch(SQLException| ClassNotFoundException e){
e.printStackTrace();
}
finally{
if(c!=null){
try{
c.close();
// pstmt.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
/*MainTable(){
initUI();
}*/
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//System.out.println(new File(".").getAbsoluteFile());
MainTable guiMainTable = new MainTable();
guiMainTable.initUI();
}
});
}
}
这是表格的代码:
package kpkw;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class KP extends JFrame {
private ArrayList<JPanel> naleznosciArrayList = new ArrayList<>();
private ArrayList<JTextField> zaCoArrayList = new ArrayList<>();
private ArrayList<JTextField> zloteArrayList = new ArrayList<>();
private ArrayList<JTextField> grArrayList = new ArrayList<>();
private static int liczbaWierszy = -1;
public KP() {
initUI();
}
private void usunPole(JPanel nal){
nal.remove(naleznosciArrayList.get(liczbaWierszy));
naleznosciArrayList.remove(liczbaWierszy);
liczbaWierszy--;
}
private void initUI(){
setTitle("KP");
setSize(500, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
this.setJMenuBar(menubar);
JMenu plik = new JMenu("Plik");
menubar.add(plik);
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
this.add(container);
JPanel title = new JPanel();
JLabel kpTytul = new JLabel("Generator KP");
kpTytul.setFont(new Font("Serif",Font.BOLD, 14));
container.add(title);
title.add(kpTytul);
JPanel pola1 = new JPanel();
pola1.setLayout(new GridLayout(2,2));
container.add(pola1);
JLabel lData = new JLabel(" Data");
JTextField tData = new JTextField(1);
tData.setEditable(false);
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
tData.setText((dateFormat.format(date)));
JLabel lNumer = new JLabel(" KP");
JPanel numery = new JPanel();
numery.setLayout(new BoxLayout(numery, BoxLayout.X_AXIS));
JTextField tNumerRef = new JTextField(1);
tNumerRef.setEditable(false);
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
try {
c = DriverManager.getConnection("jdbc:sqlite:HistoriaPrzeplywow.s3db");
c.setAutoCommit(false);
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT Count(*) FROM HistoriaPrzeplywow;" );
rs.next();
int numberOfRows = rs.getInt(1)+1;
tNumerRef.setText(Integer.toString(numberOfRows));
}
catch(SQLException e){
e.printStackTrace();
}
finally{
if(c!=null&&rs!=null){
try{
c.close();
//stmt.close();
rs.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
JTextField tNumerReg = new JTextField(1);
JTextField tNumerRok = new JTextField(1);
DateFormat rokFormat = new SimpleDateFormat("yyyy");
Date dataRok = new Date();
tNumerRok.setText((rokFormat.format(dataRok)));
tNumerRok.setEditable(false);
numery.add(tNumerRef);
numery.add(tNumerReg);
numery.add(tNumerRok);
pola1.add(lData);
pola1.add(tData);
pola1.add(lNumer);
pola1.add(numery);
JPanel pola2 = new JPanel();
pola2.setLayout(new GridLayout(3,2));
container.add(pola2);
JLabel lImie = new JLabel(" Imię");
JTextField tImie = new JTextField(1);
JLabel lNazwisko = new JLabel(" Nazwisko");
JTextField tNazwisko = new JTextField(1);
//JLabel lZaCo = new JLabel("Za co");
//JTextField tZaCo = new JTextField(1);
pola2.add(lImie);
pola2.add(tImie);
pola2.add(lNazwisko);
pola2.add(tNazwisko);
JPanel naleznosci = new JPanel();
naleznosci.setLayout(new BoxLayout(naleznosci, BoxLayout.X_AXIS));
JLabel lZaCo = new JLabel("Tytułem:");
JTextField tZaCo = new JTextField(1);
zaCoArrayList.add(tZaCo);
JLabel gap = new JLabel(" ");
JLabel lKasa = new JLabel("Wartość:");
JTextField tZlote = new JTextField(1);
zloteArrayList.add(tZlote);
JLabel lZl = new JLabel("zł");
JTextField tGr = new JTextField(1);
grArrayList.add(tGr);
JLabel lGr = new JLabel("gr");
JLabel gap2 = new JLabel(" ");
JLabel gap3 = new JLabel(" ");
//JLabel lWinien = new JLabel("Winien");
//JTextField tWinien = new JTextField(1);
naleznosci.add(lZaCo);
naleznosci.add(tZaCo);
naleznosci.add(gap);
naleznosci.add(lKasa);
naleznosci.add(gap3);
naleznosci.add(tZlote);
naleznosci.add(lZl);
naleznosci.add(tGr);
naleznosci.add(lGr);
container.add(naleznosci);
JPanel separator = new JPanel();
container.add(separator);
separator.add(new JSeparator(SwingConstants.HORIZONTAL));
JButton generuj = new JButton("Generuj");
container.add(generuj);
generuj.setAlignmentX(Component.LEFT_ALIGNMENT);
generuj.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if(tImie.getText().equals("") || tNazwisko.getText().equals("") || tNumerReg.getText().equals("") || tZaCo.getText().equals("") || tZlote.getText().equals("") || tGr.getText().equals("")){
//System.out.println("Nie wypełniono wszystkich pól");
ErrorWindow.setMessage("<html><center>Nie wypełniono wszystkich pól</center></html>");
ErrorWindow.main();
}
else {
try{
int ID = Integer.parseInt(tNumerRef.getText());
int ID3 = Integer.parseInt(tNumerRok.getText());
String typ = "KP";
String naleznosc = tZlote.getText() + tGr.getText();
int naleznoscInt = Integer.parseInt(naleznosc);
MainTable mt = new MainTable();
mt.new MyTableModel().addRecord(ID, tNumerReg.getText(), ID3, typ, tImie.getText(), tNazwisko.getText(), naleznoscInt, tZaCo.getText(), tData.getText());
}
catch(NumberFormatException e) {
e.printStackTrace();
}
}
}
});
}
public static void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
KP gui = new KP();
gui.setVisible(true);
}
});
}
}
任何帮助将不胜感激。
答案 0 :(得分:2)
MainTable mt = new MainTable();
mt.new MyTableModel().addRecord(...);
不要创建新的JTable。您需要访问框架中显示的JTable的现有TableModel。然后在该表模型上调用addRecord(...)方法。
同样在您使用的自定义TableModel中:
fireTableDataChanged();
这是错误的方法,因为您没有更改所有数据。你所做的就是添加一行数据,所以你应该使用:
fireTableRowsInserted(...);