В коде JTable извлекает все данные из базы данных с одной таблицей и двумя столбцами.
Программа является лишь минимальным примером.База данных (Javadb) "SOMETABLE", таблица "TESTTABLE", первый столбец "DATA1" (char), второй столбец "DATA2" (char).
Программа получает и показывает входные данные и записи от и докомандная строка.Остальное делается на Гуй.Сначала получите входные данные для DATA1 и DATA2, затем нажмите «Сохранить», затем покажите записи, нажав «Загрузить».
И затем нажмите «Del», чтобы отобразить записи в JTable.Просто переключение между GUI и CLI.
Но когда я запускаю программу, JTable показывает все данные только в одном столбце, а не в двух столбцах?
Извините за недопонимание.
public class DBtest {
JFrame f;
JPanel p1;
JPanel p2;
JPanel p3;
JButton b1;
JButton b2;
JButton b3;
JMenuItem delete;
JPopupMenu pm;
JTable t;
String[] c = {
"DATA1",
"DATA2"
};
Object[][] obj = null;
Object o1;
Object o2;
int n;
Scanner sc;
String s1;
String s2;
Object row2Delete;
Connection con;
PreparedStatement ps;
Connection con1;
PreparedStatement ps1;
Connection con2;
PreparedStatement ps2;
Connection con3;
PreparedStatement ps3;
ResultSet rs;
ResultSet rs2;
public static void main(String[] args) {
new DBtest().startApp();
}
public void startApp() {
p1 = new JPanel();
p2 = new JPanel();
p3 = new JPanel();
b1 = new JButton("Save");
b1.addActionListener(new SaveListener());
b2 = new JButton("Load");
b2.addActionListener(new LoadListener());
b3 = new JButton("Del");
b3.addActionListener(new DelListener());
t = new JTable(obj, c);
pm = new JPopupMenu();
delete = new JMenuItem("Delete ?");
delete.addActionListener(new DeleteListener());
pm.add(delete);
p1.setLayout(new BorderLayout());
p1.add(p2, BorderLayout.NORTH);
p2.setLayout(new FlowLayout());
p2.add(b1);
p2.add(b2);
p2.add(b3);
f = new JFrame();
f.getContentPane().add(p1);
f.setTitle("Database");
f.setSize(450, 550);
f.setResizable(false);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sc = new Scanner(System.in);
System.out.println("Type something");
s1 = sc.nextLine();
System.out.println("Type again");
s2 = sc.nextLine();
sc.close();
}
public class DelListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
try {
tableView(); //filling the table
boolean DEBUG = false;
boolean ALLOW_COLUMN_SELECTION = false;
boolean ALLOW_ROW_SELECTION = true;
t.setPreferredScrollableViewportSize(new Dimension(500, 70));
t.setFillsViewportHeight(true);
t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (ALLOW_ROW_SELECTION) {
ListSelectionModel rowSM = t.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) return;
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
if (lsm.isSelectionEmpty()) {
System.out.println("No rows are selected");
} else {
int selectedRow = lsm.getMinSelectionIndex();
pm.show(t, 50, 50);
System.out.println("Row " + selectedRow + " is now selected");
}
}
});
}
JScrollPane scrollPane = new JScrollPane(t);
p1.add(scrollPane, BorderLayout.CENTER);
f.validate();
} catch (SQLException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void tableView() throws SQLException, ClassNotFoundException {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con1 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con1.commit();
String sql = "SELECT DATA1 FROM ME.SOMETABLE";
ps1 = con1.prepareStatement(sql);
rs = ps1.executeQuery();
con2 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con2.commit();
String sql2 = "SELECT DATA2 FROM ME.SOMETABLE";
ps2 = con2.prepareStatement(sql2);
rs2 = ps2.executeQuery();
//Create new table model
DefaultTableModel tableModel = new DefaultTableModel();
//Retrieve meta data from ResultSet
ResultSetMetaData metaData = rs.getMetaData();
ResultSetMetaData metaData2 = rs2.getMetaData();
//Get number of columns from meta data
int columnCount = metaData.getColumnCount();
int columnCount2 = metaData2.getColumnCount();
//Get all column names from meta data and add columns to table model
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
tableModel.addColumn(metaData.getColumnLabel(columnIndex));
}
for (int columnIndex = 1; columnIndex <= columnCount2; columnIndex++) {
tableModel.addColumn(metaData2.getColumnLabel(columnIndex));
}
//Create array of Objects with size of column count from meta data
Object[] row = new Object[columnCount];
Object[] row2 = new Object[columnCount2];
//Scroll through result set
while (rs.next() && rs2.next()) {
//Get object from column with specific index of result set to array of objects
for (int i = 0; i < columnCount; i++) {
row[i] = rs.getObject(i + 1);
for (int h = 0; h < columnCount2; h++) {
row2[h] = rs2.getObject(h + 1);
}
}
//Add row to table model with that array of objects as an argument
tableModel.addRow(row);
tableModel.addRow(row2);
}
//Now add that table model to your table
t.setModel(tableModel);
t.setAutoCreateRowSorter(true);
}
public class DeleteListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con3 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con3.commit();
String sql = "DELETE FROM ME.SOMETABLE WHERE DATA1=?";
int row = t.getSelectedRow();
int column = t.getColumnCount();
for (int i = 0; i < column; i++) {
row2Delete = t.getValueAt(row, i);
}
ps3 = con3.prepareStatement(sql);
ps3.setString(1, "+row2Delete+");
int rowsDeleted = ps3.executeUpdate();
System.out.println("Row deleted: " + " " + rowsDeleted);
if (rowsDeleted > 0) {
System.out.println(" delete successfully!");
}
ps3.clearParameters();
} catch (SQLException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (ps3 != null) con3.close();
if (con3 != null) con3.close();
} catch (SQLException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class SaveListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con.commit();
//System.out.println(textAreaText() + "\n");
String sql = "INSERT INTO SOMETABLE (DATA1, DATA2)" + "VALUES (?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, s1);
ps.setString(2, s2);
ps.executeUpdate();
ps.clearParameters();
} catch (SQLException es) {
es.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps != null) con.close();
if (con != null) con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
public class LoadListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con1 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con1.commit();
String sql = "SELECT DATA1 FROM ME.SOMETABLE";
ps1 = con1.prepareStatement(sql);
rs = ps1.executeQuery();
con2 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con2.commit();
String sql2 = "SELECT DATA2 FROM ME.SOMETABLE";
ps2 = con2.prepareStatement(sql2);
rs2 = ps2.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next() && rs2.next()) {
for (int z = 0; z < rsmd.getColumnCount(); z++) {
n = z + 1;
o1 = rs.getObject(z + 1);
o2 = rs2.getObject(z + 1);
System.out.println(rs.getObject(z + 1) + "\n");
System.out.println(rs2.getObject(z + 1) + "\n");
}
}
ps1.clearParameters();
ps2.clearParameters();
} catch (SQLException es) {
es.printStackTrace();
} catch (Exception ex) {} finally {
try {
if (ps2 != null) con2.close();
if (con2 != null) con2.close();
if (ps1 != null) con1.close();
if (con1 != null) con1.close();
} catch (SQLException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}