包 tabPane 一共2个类,
Connect用来创建数据库连接,tabpane为主类。
package tabPane;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Connect {
//public static final String url = "jdbc:mysql://127.0.0.1/";
//public static final String name = "com.mysql.jdbc.Driver";
public static final String user = "root";
public static final String password = "ll";
public Connection conn = null;
public PreparedStatement pst = null;
String con_resu;
public Connection getConnection(String dbname,String Id,String Key) {
try {
Class.forName("com.mysql.jdbc.Driver");//指定连接类型
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/"+dbname, user, password);//获取连接
con_resu="连接成功";
} catch (Exception e) {
con_resu="连接失败";
e.printStackTrace();
}
return conn; // 返回Connection对象
}
public PreparedStatement statement(String sql) throws SQLException{
pst= conn.prepareStatement(sql);
return pst;
}
public void close() {
try {
this.conn.close();
this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
以下为 tabpane 类
package tabPane;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
//import tabPane.Renderertable.RowRenderer;
public class tabpane extends JFrame {
private static final long serialVersionUID = 1L;
//成员变量都面临没法及时清零的问题,没法重复使用
Vector<String>tb_name=new Vector<>(); //表名矢量,构建表的下拉列表
Vector<String>columnname; //列头数组,由于表的列头是局部变量,所以需另存
static Connection con ;
static PreparedStatement psql;
static int tb_num; //数据库内的表的个数
int column_num=0; //列数,在读取表时候赋值
String tselecteditem = null; //table
String dselecteditem = null;//db
String cselecteditem = null;//column
JTextField F_column=new JTextField(10);
JTextField fdb_name=new JTextField(10); //新加的数据库输入框
JTextField fdb_id=new JTextField(10);
JTextField fdb_key=new JTextField(10);
JTextField F_result=new JTextField(40); //
JTextField f_con=new JTextField(8); //
JTextField f_deleid=new JTextField(8); //
JTextField f_deleresu=new JTextField(10); //
//JComboBox<String>databox = new JComboBox<>(new dataComboBox()); //数据库名,选择表
JComboBox<String>listbox = new JComboBox<>(new MyComboBox()); //表名,选择表
JComboBox<String>columnbox = new JComboBox<>(new ColumnBox()); //表名,选择表
public DefaultTableModel tableModel; //显示表面板中,存查询结果
public DefaultTableModel in_tableModel;//修改面板中,创建输入框
public JTable table = new JTable();//JTable 的数据内容是 DefaultTableModel
public JTable in_table = new JTable();
JScrollPane spane = new JScrollPane(); // 创建JScrollPane面板对象
//窗口
JDesktopPane desktopPane = null;// 定义一个桌面面板对象
InternalFrame loginFrame = null;// 登录内部窗体对象
InternalFrame searchFrame = null;// 查询内部窗体对象
InternalFrame insertFrame = null;// 插入内部窗体对象
InternalFrame deleFrame = null;// 插入内部窗体对象
//主方法
public static void main(String args[]) throws IOException {
tabpane frame = new tabpane();
frame.setVisible(true);
}
public tabpane() throws IOException { //构造方法
//设置frame
super();
setTitle("数据库管理系统");
setBounds(100, 100, 570, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置外部pane
desktopPane = new JDesktopPane();// 创建桌面面板对象
desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
getContentPane().add(desktopPane, BorderLayout.CENTER);
final JLabel backLabel = new JLabel(); // 创建一个标签组件对象
//URL resource = this.getClass().getResource("back.jpg"); // 获得背景图片的路径
//InputStream in = this.getClass().getResourceAsStream("back.jpg");
URL url = this.getClass().getResource("back");
ImageIcon icon = new ImageIcon(url); // 创建背景图片对象
backLabel.setIcon(icon); // 令标签组件显示背景图片
backLabel.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight());// 设置组件的显示位置及大小
desktopPane.add(backLabel, new Integer(Integer.MIN_VALUE));// 将标签组件添加到指定索引位置
//登录面板的内容###############
JLabel Ldb_name=new JLabel("数据库名:");
JLabel Ldb_id=new JLabel("账号:");
JLabel Ldb_key=new JLabel("密码:");
JLabel Ldb_resu=new JLabel("连接结果:");
fdb_name.setText("mydb");//在构造方法中给文本框变量赋值
fdb_id.setText("root");
fdb_key.setText("ll");
JPanel pd1=new JPanel();
pd1.setLayout(null);
Ldb_name.setBounds(15, 15, 90,25);
Ldb_id.setBounds(125,15, 70,25);
Ldb_key.setBounds(235, 15, 105,25);
pd1.add(Ldb_name);
pd1.add(Ldb_id);
pd1.add(Ldb_key);
JPanel pd2=new JPanel();
pd2.setLayout(null);
fdb_name.setBounds(10, 0, 100,25);
fdb_id.setBounds(120,0, 100,25);
fdb_key.setBounds(230, 0, 100,25);
pd2.add(fdb_name);
pd2.add(fdb_id);
pd2.add(fdb_key);
JButton fdb_ok =new JButton("创建连接");
fdb_ok.addActionListener( new Db_con());
JPanel pd3=new JPanel();
pd3.setLayout(null);
fdb_ok.setBounds(10, 0, 90,25);
Ldb_resu.setBounds(125,0, 60,25);
f_con.setBounds(230, 0, 100,25);
pd3.add(fdb_ok);
pd3.add(Ldb_resu);
pd3.add(f_con);
JButton b_list =new JButton("获取表");
b_list.addActionListener(new Readtable());
JLabel Ltable = new JLabel("请选择表:");
JPanel pd4=new JPanel();
pd4.setLayout(null);
b_list.setBounds(10, 0, 90,25);
Ltable.setBounds(125,0, 70,25);
listbox.setBounds(225, 0, 105,25);
pd4.add(b_list);
pd4.add(Ltable);
pd4.add(listbox);
JPanel pd_login=new JPanel(new GridLayout(4, 1,10,10));
pd_login.add(pd1);
pd_login.add(pd2);
pd_login.add(pd3);
pd_login.add(pd4);
//查询面板内容#################
tableModel = new DefaultTableModel();
table=new JTable(tableModel);
spane.getViewport().add(table);
JButton b_read =new JButton("显示表内容");
b_read.addActionListener(new Act_r_table_content());
JPanel pd_search=new JPanel(new BorderLayout(0,0));
pd_search.add( spane,BorderLayout.CENTER);
JPanel Jp1=new JPanel();
Jp1.add(b_read);
pd_search.add( BorderLayout.NORTH,Jp1);
//插入与修改面板内容#################
in_tableModel = new DefaultTableModel();
in_table=new JTable(in_tableModel);
in_table.setRowHeight(25); //设置高度
JScrollPane jscrollpane=new JScrollPane();
jscrollpane.getViewport().add(in_table);
JLabel L_column=new JLabel("选择列:");
JLabel L_state=new JLabel("Result:");
L_state.setFont(new Font("标楷体", Font.BOLD, 16));
JButton but =new JButton("插入数据");
but.addActionListener(new Act_insert()); //按钮注册监听器
JButton butt =new JButton("清除插入");
butt.addActionListener(new Act_clear());
but.setBounds(90,0,80,32);
butt.setBounds(210,0,80,32);
JButton b_fix=new JButton("修改数据");
b_fix.addActionListener(new Act_motify());
JPanel jp_insert = new JPanel(new GridLayout(4, 0,0, 15));
JPanel p22 = new JPanel();
p22.setLayout(null);
L_column.setBounds(50, 0, 90,25);
columnbox.setBounds(110,0, 90,25);
F_column.setBounds(210, 0, 90,25);
L_column.setFont(new Font("标楷体", Font.BOLD, 13));
p22.add(L_column );
p22.add(columnbox );
p22.add(F_column);
JPanel p23 = new JPanel();
p23.add(but );
p23.add(b_fix);
p23.add(butt);
JPanel p24 = new JPanel(new BorderLayout());
p24.add(BorderLayout.WEST,L_state);
p24.add(BorderLayout.CENTER,F_result);
jp_insert.add(jscrollpane);
jp_insert.add(p22);
jp_insert.add(p23);
jp_insert.add(p24);
//dele面板
JButton b_dele=new JButton("删除");
b_dele.addActionListener(new Act_dele());
JLabel L_deleid=new JLabel("输入要删除的行号:");
JLabel L_deleresu=new JLabel("删除结果:");
JPanel jp_dele= new JPanel();
jp_dele.add(L_deleid);
jp_dele.add(f_deleid);
jp_dele.add(b_dele);
jp_dele.add(L_deleresu);
jp_dele.add(f_deleresu);
//主框架
JPanel pde3=new JPanel(); // 添加面板
JButton jb_insert=new JButton("插入");
pde3.add(jb_insert);
final JPanel panel = new JPanel();
final FlowLayout flowLayout = new FlowLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
panel.setLayout(flowLayout);
getContentPane().add(panel, BorderLayout.NORTH);
final JButton personnelButton = new JButton();
personnelButton.setText("登录窗口");
personnelButton .addActionListener(new BAListener(pd_login,loginFrame, "登录窗口"));
panel.add(personnelButton);
final JButton reckoningButton = new JButton();
reckoningButton.setText("查询窗口");
reckoningButton .addActionListener(new BAListener(pd_search,searchFrame, "查询窗口"));
panel.add(reckoningButton);
final JButton treatmentButton = new JButton("插入与修改");
treatmentButton .addActionListener(new BAListener(jp_insert,insertFrame, "插入与修改"));
panel.add(treatmentButton);
final JButton deleButton = new JButton("删除数据");
deleButton .addActionListener(new BAListener(jp_dele,deleFrame, "删除数据"));
panel.add(deleButton);
}//构造方法结尾
//JComboBox下拉列表的内容封装在ComboBoxModel
class MyComboBox extends AbstractListModel<String> implements ComboBoxModel<String> {
private static final long serialVersionUID = 1L;
public String getElementAt(int index) {
return tb_name.get(index);
}
public int getSize() {
return tb_num;
}
public void setSelectedItem(Object items) {
tselecteditem = (String) items;
}
public Object getSelectedItem() {
return tselecteditem;
}
}
class ColumnBox extends AbstractListModel<String> implements ComboBoxModel<String> {
private static final long serialVersionUID = 1L;
public String getElementAt(int index) {
return columnname.get(index);
}
public int getSize() {
return column_num;
}
public void setSelectedItem(Object items) {
cselecteditem = (String) items;
}
public Object getSelectedItem() {
return cselecteditem;
}
}
class dataComboBox extends AbstractListModel<String> implements ComboBoxModel<String> {
/**
*
*/
private static final long serialVersionUID = 1L;
String[] list ={"mydb","db_database28","test","CTXSYS"}; //通过Readtable找到表数组
public String getElementAt(int index) {
return list[index];
}
public int getSize() {
return list.length;
}
public void setSelectedItem(Object items) {
dselecteditem = (String) items;
}
public Object getSelectedItem() {
return dselecteditem;
}
}
//连接数据库动作类
public class Db_con implements ActionListener{
public void actionPerformed(ActionEvent e1) {
String db_name=fdb_name.getText();
String db_id=fdb_id.getText();
String db_key=fdb_key.getText();
Connect conn=new Connect();
con = conn.getConnection(db_name, db_id, db_key);
System.out.println(conn.con_resu);
String s_con =conn.con_resu;
f_con.setText(s_con);
}
}
//读取表名,用于构建下拉列表
public class Readtable implements ActionListener{ //读取
public void actionPerformed(ActionEvent e2) {
Vector<String>temptbname=new Vector<>();
ResultSet rs = null;
DatabaseMetaData meta = null;
try {
meta = con.getMetaData();
rs = meta.getTables(null, null, null, new String[] { "TABLE" });
int i=0;
while (rs.next()) {
// ss_tables[i]=rs.getString(3); // 读取的表名存到成员本地数组
temptbname.add(rs.getString(3));
i++;
}
tb_num=i;
for(int k=0; k<tb_num;k++){
// System.out.println( tb_name.get(k));
}
tb_name=temptbname;
Iterator<String>it=tb_name.iterator();
while(it.hasNext()){
System.out.println(dselecteditem+":tb_name="+(String)it.next());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//读取表内容########################################
class Act_r_table_content implements ActionListener{
public void actionPerformed(ActionEvent aa) {
try {
//表
Vector<String>columnName=new Vector<>(); //列头矢量,只能作为局部变量,否则会累加,显示多余
Vector<String>tempcolumn=new Vector<>(); //临时列不存行号
Statement sql = con.createStatement(); //Statement对象用于执行简单不带参数的SQL 语句
ResultSet res = sql.executeQuery("select * from "+tselecteditem+"");//不加条件时候读取所有行。
ResultSetMetaData data=res.getMetaData();
columnName.add("行号"); //第一列手动加行号
column_num=data.getColumnCount(); //列数
for(int i = 1 ; i<= column_num ; i++){
columnName.add(data.getColumnName(i)); //读取列名
tempcolumn.add(data.getColumnName(i));
}
columnname=tempcolumn;
int k=1;
Vector<Vector<String>>tablevalues=new Vector<>();//二维向量,存表内容
while (res.next()) { // 如果当前语句不是最后一条则进入循环
Vector<String>rowV=new Vector<>();
int j=1;
rowV.add(Integer.toString(k++)); //每行先添加列号
for(int i = 1 ; i<= data.getColumnCount() ; i++){
rowV.add(res.getString(data.getColumnName(j++)));
}
tablevalues.add(rowV);
}
tableModel.setDataVector(tablevalues,columnName); //表头加二维矢量组成表
fitTableColumns(table); //调整格子宽度
//DefaultTableCellRenderer backGroundColor = new DefaultTableCellRenderer();
//backGroundColor.setBackground(Color.red); //绘制部门列的背景为黄色
paintRow( table);
//方法setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer)
//table.setDefaultRenderer( Object.class, new classcellRenderer()); //set color
//插入表格
Vector<Vector<String>>in_tablevalues=new Vector<>(); //插入面板中得输入用的二维表格
Vector<String>inrowV=new Vector<>();
for(int i = 1 ; i<= column_num; i++){
inrowV.add("");
}
in_tablevalues.add(inrowV);
in_tableModel.setDataVector(in_tablevalues,tempcolumn); //加载数据
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
//逐行渲染,可以设置被点击行颜色,逐格渲染不行
public void paintRow(JTable table) //成员方法
{
//table.setSelectionForeground(Color.RED);
table.setSelectionBackground(Color.yellow);
TableColumnModel tcm = table.getColumnModel();
for (int i = 0, n = tcm.getColumnCount(); i < n; i++)
{
TableColumn tc = tcm.getColumn(i); //以列为单位渲染的
tc.setCellRenderer(new RowRenderer());
}
}
private class RowRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent(JTable t, Object value,boolean isSelected, boolean hasFocus, int row, int column)
{
//设置奇偶行的背景色,可在此根据需要进行修改
if (column==0) { // 为序号列加上颜色
setBackground(Color.decode("#EBEBEB"));
}
else
setBackground(Color.decode("#E0FFFF"));
return super.getTableCellRendererComponent(t, value, isSelected, hasFocus, row, column);
}
}
//单元格渲染类
class classcellRenderer implements TableCellRenderer {
//DefaultTableCellRenderer类可以绘制单元格的背景、字体颜色等功能
DefaultTableCellRenderer DEFAULT_RENDERER =new DefaultTableCellRenderer();
// 定义组件方法,获取表格渲染组件
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component componentrenderer =DEFAULT_RENDERER.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
//估计遍历所有格
Color foreground, background; //定义颜色变量
if (column==0) { // 为序号列加上颜色
foreground = Color.black;
background = Color.decode("#EBEBEB"); //背景暗灰色
}
else if(column==1&&(row%2==0)){
foreground = Color.black;
background = Color.orange; //背景暗灰色
}
else {
foreground = Color.BLACK;
background = Color.WHITE;
}
componentrenderer.setForeground(foreground);
componentrenderer.setBackground(background);
return componentrenderer;
}
}
//自动调整表格宽度
public void fitTableColumns(JTable myTable)
{
myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
myTable.setRowHeight(30); //设置格高度
JTableHeader header = myTable.getTableHeader(); //得到表头
int rowCount = myTable.getRowCount(); //得到行数
//获取列数据getColumns() Returns an Enumeration of all the columnName in the model.
//Enumeration=javax.swing.table.TableColumn@1099f62
Enumeration columnName = myTable.getColumnModel().getColumns(); //个数为列的个数
while(columnName.hasMoreElements())
{
//A TableColumn represents all the attributes of a column in a JTable
TableColumn column = (TableColumn)columnName.nextElement(); //列头名,构建表列
// column.getIdentifier() 是列名, TableColumn column是列的编号
String str=(String)column.getIdentifier();
int indexofcolumn = header.getColumnModel().getColumnIndex(str);//根据列名得到列的序号
// col= 0,1'''''''''''
//获取表头宽度
int width = (int)header.getDefaultRenderer().getTableCellRendererComponent(myTable, column.getIdentifier(),
false, false, -1, indexofcolumn).getPreferredSize().getWidth();
//获取列的宽度,取最大值
for(int row = 0; row < rowCount; row++)
{
int columnWidth = (int)myTable.getCellRenderer(row, indexofcolumn).getTableCellRendererComponent (myTable, myTable.getValueAt(row, indexofcolumn),
false, false, row, indexofcolumn).getPreferredSize().getWidth();
width = Math.max(width, columnWidth);
}
header.setResizingColumn(column); // 表头的宽度设为与列相同
column.setWidth(20+width+myTable.getIntercellSpacing().width); //列宽
}
}
//插入数据
class Act_insert implements ActionListener{
public void actionPerformed(ActionEvent e)
{
String newsql = "insert into "+tselecteditem+" values(";
int k=0;
for(k=0;k<column_num;k++){
if(k==column_num-1){
newsql=newsql+"'"+in_table.getValueAt(0, k)+"'"+")";
break;
}
newsql=newsql+"'"+in_table.getValueAt(0, k)+"'"+",";
}
try {
psql = con.prepareStatement(newsql);
psql.executeUpdate(); // 执行sql语句
F_result.setText("成功输入数据");
} catch (SQLException e1) {
F_result.setText("插入失败,sql="+newsql);
e1.printStackTrace();
}
}
}
//清除插入
class Act_clear implements ActionListener{
public void actionPerformed(ActionEvent e) {
F_result.setText("");
}
}
//修改动作
class Act_motify implements ActionListener{
public void actionPerformed(ActionEvent e) {
String newsql="update "+tselecteditem+" set ";
int k=0;
for(k=0;k<column_num;k++){
String str=(String)in_table.getValueAt(0, k);
if(!str.equals(""))
newsql=newsql+columnname.get(k)+"="+"'"+str+"'"+",";
System.out.println("Vn="+columnname.get(k) );
}
int length=newsql.length();
String substr=newsql.substring(0,length-1); //除去","
substr=substr+" where "+cselecteditem+"="+"'"+F_column.getText()+"'";
System.out.println(substr);
try {
psql = con.prepareStatement(substr);
psql.executeUpdate(); //执行语句
F_result.setText("修改成功");
} catch (SQLException e1) {
F_result.setText("修改失败sql="+substr);
e1.printStackTrace();
}
}
}
//删除动作类
class Act_dele implements ActionListener{
public void actionPerformed(ActionEvent e ) {
String dele_tableid=f_deleid.getText();
PreparedStatement ps=null;
String sql ="delete from "+tselecteditem+" where id ="+"'"+dele_tableid+"'";
int xx=0;
try{
ps=con.prepareStatement(sql);
xx=ps.executeUpdate();
if(xx==1){
f_deleresu.setText("删除成功");
}
else{
f_deleresu.setText("删除失败"+sql);
}
}catch(SQLException e1){
e1.printStackTrace();
}
}
}
//创建内部窗口动作nb类
private class BAListener implements ActionListener {
InternalFrame inFrame;
String title;
JPanel inpd;
public BAListener(JPanel pd,InternalFrame inFrame, String title) {
this.inFrame = inFrame;
this.title = title;
this.inpd=pd;
}
public void actionPerformed(ActionEvent e) {
if (inFrame == null || inFrame.isClosed()) {// 获得桌面面板中的所有内部窗体
JInternalFrame[] tableFrames = desktopPane.getAllFrames(); // 获得桌面面板中拥有内部窗体的数量
int titleBarHight = 30 * tableFrames.length;
int x = 10 + titleBarHight, y = x; // 设置窗体的显示位置
inFrame = new InternalFrame(title); // 创建指定标题的内部窗体
if(title.equals("登录窗口")){
inFrame.setBounds(x, y, 360, 200);
}
else if(title.equals("查询窗口")){
inFrame.setBounds(x, y, 450, 370);
}
else if(title.equals("插入与修改")){
inFrame.setBounds(x, y, 400,250);
}
else if(title.equals("删除数据")){
inFrame.setBounds(x, y, 330,160);
}
else{
inFrame.setBounds(x, y, 420,250);
}
inFrame.setVisible(true); // 设置窗体可见
inFrame.add(inpd);
desktopPane.add(inFrame); // 将窗体添加到桌面面板中
}
try {
inFrame.setSelected(true);// 选中窗体
} catch (PropertyVetoException propertyVetoE) {
propertyVetoE.printStackTrace();
}
}
}
private class InternalFrame extends JInternalFrame {
/**
* 内部窗口,一个名称参数title
*/
private static final long serialVersionUID = 1L;
public InternalFrame(String title) {
super();
setTitle(title);// 设置内部窗体的标题
setResizable(true);// 设置允许自由调整口大小
setClosable(true);// 设置提供关闭按钮
setIconifiable(true);// 设置提供图标化按钮
setMaximizable(true);// 设置提供最大化按钮
ImageIcon icon = new ImageIcon(this.getClass().getResource("ico")); // 创建图片对象
setFrameIcon(icon); // 设置窗体图标
}
}
}