Программирование на Java часть 2
.pdfv.add(rs.getString(i));
}
model.addRow(v);
}
setModel(model); setAutoResizeMode(AUTO_RESIZE_ALL_COLUMNS);
} catch (SQLException ex) { Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Создадим класс TablePanel в котором будет создаваться таблица и кнопки для редактирования таблицы.
Листинг 4.11
package by.belhard.user_interface.tables_panel;
import by.belhard.dao.DaoGoods; import by.belhard.dao.DaoOrders; import by.belhard.dao.DaoUsers; import by.belhard.entity.Goods; import by.belhard.entity.Orders; import by.belhard.entity.Users; import by.belhard.mysql.DB;
import by.belhard.user_interface.MyTable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter;
import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.sql.ResultSet;
import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public abstract class TablePanel extends JPanel {
protected DB db;
protected JScrollPane scroll; protected MyTable table;
protected JButton delete, add, change;
151
public TablePanel(DB db) { this.db = db; setSize(500, 500); setLayout(null);
}
public void initComponents() { createTable();
scroll = new JScrollPane(table); scroll.setBounds(20, 20, 680, 300); delete = new JButton("Delete"); add = new JButton("Add"); change = new JButton("Change"); add.setBounds(20, 350, 200, 20);
change.setBounds(260, 350, 200, 20); delete.setBounds(495, 350, 200, 20); add(scroll);
add(add);
add(delete);
add(change);
}
public abstract void action();
public abstract void createTable();
public void updateTable() { remove(scroll); createTable();
scroll = new JScrollPane(table); scroll.setBounds(20, 20, 680, 300); add(scroll);
updateUI();
}
}
Создадим потомки класса TablePanel для каждой таблицы. TableUsersPanel позволяет добавить нового пользователя(все логины
должны быть уникальны), отредактировать все данные, кроме users_id, т.к. это первичный ключ и удалить пользователя.
152
Листинг 4.12
package by.belhard.user_interface.tables_panel;
import by.belhard.dao.DaoUsers; import by.belhard.entity.Users; import by.belhard.mysql.DB;
import by.belhard.user_interface.MyTable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.sql.ResultSet;
import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.JPanel;
public class TableUsersPanel extends TablePanel {
private JPanel panel = this;
public TableUsersPanel(DB db) { super(db); super.initComponents(); action();
}
@Override
public void action() { delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { try {
if (table.getSelectedRow() == -1) { JOptionPane.showMessageDialog(panel,
"Select the line you want to remove"); } else {
db.update("update users set delete_status =1 "
+"where users_id ="
+table.getValueAt(table.getSelectedRow(), 0)); updateTable();
}
153
} catch (SQLException ex) { JOptionPane.showMessageDialog(panel, "error in delete " + ex);
}
}
});
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { try {
int maxId = 0;
ResultSet rs = db.query("select max(users_id) from users"); if (rs.next()) {
maxId = rs.getInt(1);
}
DaoUsers daoUsers = new DaoUsers(db); daoUsers.insert(new Users(maxId)); updateTable();
} catch (SQLException ex) { JOptionPane.showMessageDialog(panel, "error in add " + ex);
}
}
});
change.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { if (table.getSelectedRow() != -1) {
try {
int role = 0;
if (table.getValueAt(table.getSelectedRow(), 4). toString().equalsIgnoreCase("user")) {
role = 1; } else {
if (table.getValueAt(table.getSelectedRow(), 4).toString(). equalsIgnoreCase("admin")) {
role = 0; } else {
throw new SQLException("error role");
}
}
int block_status = 0;
154
if (table.getValueAt( table.getSelectedRow(), 5).toString(). equalsIgnoreCase("active")) {
block_status = 0; } else {
if (table.getValueAt( table.getSelectedRow(), 5).toString(). equalsIgnoreCase("Blocked")) {
block_status = 1; } else {
throw new SQLException("" + "error block_status");
}
}
DaoUsers du = new DaoUsers(db);
du.update(new Users(Integer.valueOf( table.getValueAt(table.getSelectedRow(), 0).toString()), table.getValueAt(table.getSelectedRow(), 1).toString(), table.getValueAt(table.getSelectedRow(), 2).toString(), role,
block_status, Integer.valueOf(table.getValueAt(table.getSelectedRow(),
3).toString())
));
updateTable();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(TablePanel.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) {
Logger.getLogger(TablePanel.class.getName()).log(Level.SEVERE, null, ex);
}catch (NumberFormatException ex) { JOptionPane.showMessageDialog(panel, "Incorrect data " +
ex);
updateTable();
}catch (SQLException ex) { JOptionPane.showMessageDialog(panel, "Incorrect data " +
ex);
updateTable();
}
} else {
JOptionPane.showMessageDialog(panel, "Select the line you want to change");
}
155
}
});
}
@Override
public void createTable() { try {
table = new MyTable(db.query("select users_id,login,pass,balance, case role when 1 then 'user' when 0 then 'admin' end as role,IF(block_status=1,'Blocked','Active')as blocked_status from users where delete_status=0")) {
@Override
public boolean isCellEditable(int row, int column) { if (column == 0) {
return false;
}else { return true;
}
}
};
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Error creating table\n" + ex, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
TableGoodsPanel позволяет редактировать информацию о товаре. При добавлении нового товара необходимо выбрать изображение(все изображения должны лежать в папке images на том же уровне, что и jar - файл).
Листинг 4.13
package by.belhard.user_interface.tables_panel;
import by.belhard.dao.DaoGoods; import by.belhard.entity.Goods; import by.belhard.mysql.DB;
import by.belhard.user_interface.MyTable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.ResultSet;
import java.sql.SQLException;
156
import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
public class TableGoodsPanel extends TablePanel {
private JPanel panel = this; private JFileChooser chooser;
public TableGoodsPanel(DB db) { super(db);
initComponents();
action();
}
@Override
public void initComponents() { super.initComponents(); chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter( "Images", "jpg", "png", "jpeg");
chooser.setFileFilter(filter);
}
@Override
public void action() { delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { try {
if (table.getSelectedRow() == -1) { JOptionPane.showMessageDialog(panel,
"Select the line you want to remove"); } else {
db.update("update goods set delete_status =1 "
+"where goods_id ="
+table.getValueAt(table.getSelectedRow(), 0)); updateTable();
}
}catch (SQLException ex) { JOptionPane.showMessageDialog(panel, "error in delete " + ex);
}
}
157
});
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { try {
int maxId = 0;
ResultSet rs = db.query("select max(goods_id) from goods"); if (rs.next()) {
maxId = rs.getInt(1);
}
DaoGoods daoGoods = new DaoGoods(db); daoGoods.insert(new Goods(maxId)); updateTable();
} catch (SQLException ex) { JOptionPane.showMessageDialog(panel, "error in add " + ex);
}
}
});
change.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { if (table.getSelectedRow() != -1) {
try {
DaoGoods dg = new DaoGoods(db); dg.update(new
Goods(Integer.valueOf(table.getValueAt(table.getSelectedRow(), 0).toString()), table.getValueAt(table.getSelectedRow(), 1).toString(), Integer.valueOf(table.getValueAt(table.getSelectedRow(),
3).toString()),
table.getValueAt(table.getSelectedRow(), 2).toString())); chooser.showOpenDialog(panel);
if (chooser.getSelectedFile() != null) { dg.setImagePath(new
Goods(Integer.valueOf(table.getValueAt(table.getSelectedRow(), 0).toString()), chooser.getSelectedFile().getName()));
}
updateTable();
}catch (NumberFormatException ex) { JOptionPane.showMessageDialog(panel, "Incorrect data " +
ex);
updateTable();
158
}catch (SQLException ex) { JOptionPane.showMessageDialog(panel, "Incorrect data " +
ex);
updateTable();
}
} else {
JOptionPane.showMessageDialog(panel, "Select the line you want to change");
}
}
});
}
@Override
public void createTable() { try {
table = new MyTable(db.query("select goods_id,name, description, price from goods where delete_status=0")) {
@Override
public boolean isCellEditable(int row, int column) { if (column == 0) {
return false;
}else { return true;
}
}
};
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Error creating table\n" + ex, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
TableOrdersPanel выводит информацию о заказах. Можно посмотреть детализацию любого заказа в TableGoodsInOrdersPanel.
Листинг 4.14
package by.belhard.user_interface.tables_panel; import by.belhard.dao.DaoOrders;
import by.belhard.dao.DaoUsers; import by.belhard.entity.Orders; import by.belhard.entity.Users;
159
import by.belhard.mysql.DB;
import by.belhard.user_interface.MyTable;
import by.belhard.user_interface.tables_panel.TablePanel; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.sql.SQLException; import javax.swing.JButton;
import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel;
public class TableOrdersPanel extends TablePanel {
private JButton detailed;
private JPanel panel = this;
public TableOrdersPanel(DB db) { super(db);
initComponents();
action();
}
@Override
public void initComponents() { super.initComponents();
detailed = new JButton("Detailed"); change.setText("Change status"); detailed.setBounds(20, 350, 200, 20); remove(add);
remove(delete);
add(detailed);
updateUI();
}
@Override
public void action() { detailed.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFrame goodsInOrdersFrame = new JFrame("Goods in orders"); goodsInOrdersFrame.setSize(300, 280); goodsInOrdersFrame.setLocationRelativeTo(null);
160