simplebookmanager.java

来自「我的Java课程设计」· Java 代码 · 共 370 行

JAVA
370
字号
import javax.swing.*;     
import java.awt.*;
import java.awt.event.*;     
import javax.swing.table.*;
import java.sql.*;
import edu.njust.cs.*;
public class SimpleBookManager{
	public static void main(String []args){
		SetFont.setFont(new Font("楷体", 0, 12));
		Connection con=null;
		try{
			con=SqlUtil.acquireConnection("127.0.0.1",
							"1433","bookTest","admin","xyz");
		}catch(Exception e){
			System.out.println(e);
			System.exit(-1);
		}
		if(con!=null){
			JFrame f=new JFrame();		
			f.addWindowListener(new WindowAdapter(){
					public void windowClosing(WindowEvent e){
						System.exit(0);
					}
				});
			f.getContentPane().add(new BookManager(f,con));			
			f.setSize(600,400);
			f.show();
		}
	}
}
class BookManager extends JPanel implements ActionListener{
	private String [] columnNames={"图书编号","书名","定价","出版社"};
	private Class []dataType={String.class,String.class,Double.class,String.class};	
	private CustomTableModel model=null;
	private JTable table=null;	
	private Connection con=null;
	private JButton btnAdd=new TextAndPicButton("image/addrow20.gif"," 增  加 ");	
	private JButton btnSearch=new TextAndPicButton("image/search20.gif"," 查  询 ");	
	private JButton btnDelete=new TextAndPicButton("image/deleterow20.gif"," 删  除 ");	
	private JButton btnExit=new TextAndPicButton("image/exit20.gif"," 退  出 ");	
	private JFrame f=null;
	public BookManager(JFrame f,Connection con){
		this.f=f;
		this.con=con;
		//构建工具条
		JToolBar toolBar=new JToolBar();
		toolBar.add(btnAdd);
		toolBar.add(btnSearch);
		toolBar.add(btnDelete);
		toolBar.add(btnExit);		
		//注册事件侦听器
		btnAdd.addActionListener(this);
		btnSearch.addActionListener(this);
		btnDelete.addActionListener(this);
		btnExit.addActionListener(this);		
		//构建表格
		model=new CustomTableModel(0,columnNames.length,columnNames,dataType);                table = new JTable(model);   
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION );
		//设定表格每列的宽度
		setTableColumnWidth(0,100);
		setTableColumnWidth(1,200);
		setTableColumnWidth(2,100);
		setTableColumnWidth(3,250);				
		//布局工具条及表格
		this.setLayout(new BorderLayout());
		this.add(toolBar,BorderLayout.NORTH);
		this.add(new JScrollPane(table),BorderLayout.CENTER);				
	}
	//设置表格指定列的宽度
	public void setTableColumnWidth(int column,int width){		
		if(column<columnNames.length&&column>=0){
			TableColumn col=table.getColumn(columnNames[column]);
			col.setPreferredWidth(width);
		}
	}
	public void actionPerformed(ActionEvent e){
		Object s=e.getSource();
		if(s==this.btnAdd) add();
		else if(s==this.btnSearch)	search();
		else if(s==this.btnDelete) delete();
		else if(s==this.btnExit) System.exit(0);
	}
	//增加一条记录到数据库
	public void add(){
		BookEditor be=new BookEditor(f,"增加",true);
		be.show();
		 //只有点击了信息对话框中的确定按钮,才增加记录
		if(be.getActionCode()==be.OK){
			String insertSql="insert into bookInfo VALUES (?,?,?,?)";
			Object []lineForDBAdd={be.getID(),be.getBookName(),
								        be.getBookPrice(),be.getBookPress()};			
			if(SqlUtil.addRowToDB(con,insertSql,lineForDBAdd))
			{  //成功写入数据库的记录,追加到表格的末行显示
				Object []lineForTable=
						   SqlUtil.getLineForTableFromLineForDB(lineForDBAdd,dataType);
				model.insertRow(model.getRowCount(),lineForTable);
				//将表格的最后一行选中
				table.changeSelection(model.getRowCount()-1,0,false,false);		
			}
			else
				JOptionPane.showMessageDialog(this,"新增时出错!",
					"提示",JOptionPane.INFORMATION_MESSAGE);				
		}
	}
	//查询数据库
	public void search(){
		SearchDialog sd=new SearchDialog(f,"查询",true);
		sd.show();
		if(sd.getActionCode()==sd.OK){
			String readSql=sd.getSQL();
			SqlUtil.readDBToTable(con,readSql,model,dataType);
		}
	}
	//删除选定的记录
	public void delete(){
		int selected=table.getSelectedRow();
		if(selected>=0&&selected<model.getRowCount()){	
			int result=JOptionPane.showConfirmDialog (f,"您确定要删除该条图书信息吗?"
			  ,"确认",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
			if (result!=JOptionPane.YES_OPTION)	return ;
			String deleteSql="delete from bookInfo where bookID=?";
			Object []keys={model.getValueAt(selected,0).toString()};
			if(SqlUtil.deleteFromDB(con,deleteSql,keys))
				model.removeRow(selected);
		}
		else
			JOptionPane.showMessageDialog(f,"请选定要删除的一行!"
						,"提示",JOptionPane.INFORMATION_MESSAGE);	
	
	}			
	//内部类,用于显示/编辑图书信息的一个模式对话框
	class BookEditor extends JDialog implements ActionListener	{
		final  int OK=1;
	    final  int CANCEL=-1;
	    final  int CLOSE=0;			
		private int actionCode=CANCEL;		
		private JLabel labID=new JLabel("  图书编号  ");
		private JTextField txtID=new JTextField();		
		private JLabel labBookName=new JLabel("  图书名称  ");
		private JTextField txtBookName=new JTextField();		
		private JLabel labBookPrice=new JLabel("  单        价  ");
		private JTextField txtBookPrice=new JTextField();		
		private JLabel labBookPress=new JLabel("    出  版  社    ");
		private JTextField txtBookPress=new JTextField();		
		private JButton btnPre=new JButton("上一个");
		private JButton btnNext=new JButton("下一个");							  
		private JButton btnOk=new JButton("确定");
		private JButton btnCancel=new JButton("取消");
		private JFrame f=null;
		public BookEditor(JFrame f,String s,boolean b)	{
			super(f,s,b);
			this.f=f;
			//面板p中显示图书信息
			JPanel p=new JPanel();
			p.setLayout(new GridBagLayout());
			LayoutUtil.add(p,GridBagConstraints.NONE,
						   GridBagConstraints.CENTER,0,0,0,0,1,1,labID);
			LayoutUtil.add(p,GridBagConstraints.HORIZONTAL,
						   GridBagConstraints.CENTER,100,0,1,0,1,1,txtID);
			LayoutUtil.add(p,GridBagConstraints.NONE,
						   GridBagConstraints.CENTER,0,0,2,0,1,1,labBookName);
			LayoutUtil.add(p,GridBagConstraints.HORIZONTAL,
						   GridBagConstraints.CENTER,100,0,3,0,1,1,txtBookName);			
			LayoutUtil.add(p,GridBagConstraints.NONE,
						   GridBagConstraints.CENTER,0,0,0,1,1,1,labBookPrice);
			LayoutUtil.add(p,GridBagConstraints.HORIZONTAL,
						   GridBagConstraints.CENTER,100,0,1,1,1,1,txtBookPrice);
			LayoutUtil.add(p,GridBagConstraints.NONE,
						   GridBagConstraints.CENTER,0,0,2,1,1,1,labBookPress);
			LayoutUtil.add(p,GridBagConstraints.HORIZONTAL,
						   GridBagConstraints.CENTER,100,0,3,1,1,1,txtBookPress);
			//注册事件侦听器
			btnOk.addActionListener(this);
			btnCancel.addActionListener(this);
			btnPre.addActionListener(this);
			btnNext.addActionListener(this);					
			btnOk.setIcon(new ImageIcon("image/ok20.gif"));
			btnCancel.setIcon(new ImageIcon("image/cancel20.gif"));
			btnPre.setIcon(new ImageIcon("image/pre20.gif"));
			btnNext.setIcon(new ImageIcon("image/next20.gif"));
			btnNext.setHorizontalTextPosition(SwingConstants.LEFT);			
			//在增加模式下前后移动按钮置为不可用
			//读者扩展该程序具有编辑功能时,可以将前后移动按钮置为可用
			if(s.equals("增加")){
				btnPre.setEnabled(false);
				btnNext.setEnabled(false);
			}			
			//面板ap中显示4个按钮
			JPanel ap=new JPanel();
			ap.setLayout(new GridBagLayout());
			LayoutUtil.add(ap,GridBagConstraints.NONE,
						   GridBagConstraints.CENTER,0,0,0,0,1,1,this.btnPre);
			LayoutUtil.add(ap,GridBagConstraints.NONE,
						   GridBagConstraints.CENTER,0,0,1,0,1,1,this.btnNext);
			LayoutUtil.add(ap,GridBagConstraints.HORIZONTAL,
						   GridBagConstraints.CENTER,100,0,2,0,1,1,new JLabel());
			LayoutUtil.add(ap,GridBagConstraints.NONE,
						   GridBagConstraints.CENTER,0,0,3,0,1,1,this.btnOk);
			LayoutUtil.add(ap,GridBagConstraints.NONE,
						   GridBagConstraints.CENTER,0,0,4,0,1,1,this.btnCancel);
		    getContentPane().add(p,BorderLayout.CENTER);
			getContentPane().add(ap,BorderLayout.SOUTH);
			//将对话框窗口定位在父窗口的居中位置
			setSizeAndPosition(550,120);			
			this.addWindowListener(new WindowAdapter(){
					public void  windowClosing(WindowEvent e){
						actionCode=CLOSE;
					}
				});
		}		
		//将对话框窗口定位在父窗口的居中位置
		public void setSizeAndPosition(int w,int h){
			this.setSize(w,h);
			Dimension d=f.getSize();
			Point pp=f.getLocation();
			this.setLocation(pp.x+(d.width-w)/2,pp.y+(d.height-h)/2);
		}
		public void actionPerformed(ActionEvent e){
			Object s=e.getSource();
			if(s==this.btnCancel)	{
				this.actionCode=this.CANCEL;
				this.setVisible(false);
			}
			else if(s==this.btnOk) okClicked();
		}								
		public String getID(){
			return txtID.getText().trim();
		}
		public String getBookName(){
			return txtBookName.getText().trim();
		}		
		//将图书单价由字符串类型转化为Double类型
		//如果不是合法的数值字符串,取值Double.NEGATIVE_INFINITY
		public Double getBookPrice(){
			double result=Double.NEGATIVE_INFINITY;
			try{
				result=Double.parseDouble(this.txtBookPrice.getText().trim());
			}catch(Exception e){
				result=Double.NEGATIVE_INFINITY;
			}
			return new Double(result);
		}
		public String getBookPress(){
			return txtBookPress.getText().trim();
		}
		public int getActionCode(){
			return this.actionCode;
		}
		public void okClicked()	{
			//图书编号不为空,且价格为数值类型时 隐藏对话框
			if(!this.txtID.getText().trim().equals("")){
				try{
				    Double.parseDouble(this.txtBookPrice.getText().trim());
				}catch(Exception e){
					JOptionPane.showMessageDialog(f,"价格非法!","提示",
									JOptionPane.INFORMATION_MESSAGE);	
				    return ;
				}
				this.actionCode=this.OK;
				this.setVisible(false);
			}
			else
				JOptionPane.showMessageDialog(f,"请设定图书编号!","提示",
											  JOptionPane.INFORMATION_MESSAGE);	
				   
		}
	}
}
class SearchDialog extends JDialog implements ActionListener{
	final  int OK=1;
    final  int CANCEL=-1;
    final  int CLOSE=0;			
	private int actionCode=CANCEL;
	private  JRadioButton radID=new JRadioButton("  图书编号  ");
	private JTextField txtID=new JTextField();
	private  JRadioButton radBookName=new JRadioButton("  图书名称  ");
	private JTextField txtBookName=new JTextField();
	private  JRadioButton radBookPress=new JRadioButton("  出  版  社  ");
	private JTextField txtBookPress=new JTextField();	
	private JButton btnOk=new JButton("确定(Yes)");
	private JButton btnCancel=new JButton("取消(Esc)");
    private JFrame f=null;
	public SearchDialog(JFrame f,String s,boolean b){
		super(f,s,b);
		this.f=f;
		ButtonGroup group=new ButtonGroup();		
		group.add(radID);
		group.add(radBookName);
		group.add(radBookPress);		
		txtID.setEditable(false);
		radBookName.setSelected(true);
		txtBookPress.setEditable(false);		
		radID.addActionListener(this);
		radBookName.addActionListener(this);
		radBookPress.addActionListener(this);		
		//面板p中显示查询条件
		JPanel p=new JPanel();
		p.setLayout(new GridBagLayout());
		LayoutUtil.add(p,GridBagConstraints.NONE,
					   GridBagConstraints.CENTER,0,0,0,0,1,1,radID);
		LayoutUtil.add(p,GridBagConstraints.HORIZONTAL,
					   GridBagConstraints.CENTER,100,0,1,0,1,1,txtID);
		LayoutUtil.add(p,GridBagConstraints.NONE,
					   GridBagConstraints.WEST,0,0,0,1,1,1,radBookName);
		LayoutUtil.add(p,GridBagConstraints.HORIZONTAL,
					   GridBagConstraints.CENTER,100,0,1,1,1,1,txtBookName);
		LayoutUtil.add(p,GridBagConstraints.NONE,
					   GridBagConstraints.CENTER,0,0,0,2,1,1,radBookPress);
		LayoutUtil.add(p,GridBagConstraints.HORIZONTAL,
					   GridBagConstraints.CENTER,100,0,1,2,1,1,txtBookPress);
		btnOk.setIcon(new ImageIcon("image/ok20.gif"));
		btnCancel.setIcon(new ImageIcon("image/cancel20.gif"));
		btnOk.addActionListener(this);
		btnCancel.addActionListener(this);		
		//面板ap中显示确定 取消按钮		
		JPanel ap=new JPanel();
		ap.add(btnOk);
		ap.add(btnCancel);		
		getContentPane().add(p,BorderLayout.CENTER);
		getContentPane().add(ap,BorderLayout.SOUTH);
		setSizeAndPosition(300,200);	
		this.addWindowListener(new WindowAdapter(){
					public void  windowClosing(WindowEvent e){
						actionCode=CLOSE;
					}
				});
	}	
	//将对话框窗口定位在父窗口的居中位置
	public void setSizeAndPosition(int w,int h){
		this.setSize(w,h);
		Dimension d=f.getSize();
		Point pp=f.getLocation();
		this.setLocation(pp.x+(d.width-w)/2,pp.y+(d.height-h)/2);
	}
	public void setTxtEditable(boolean b1,boolean b2,boolean b3){
		txtID.setEditable(b1);
		txtBookName.setEditable(b2);
		txtBookPress.setEditable(b3);
	}
	public void actionPerformed(ActionEvent e){
		Object s=e.getSource();
		if(s==this.radID)	setTxtEditable(true,false,false);
		else if(s==this.radBookName)	setTxtEditable(false,true,false);
		else if(s==this.radBookPress)	setTxtEditable(false,false,true);
		else if(s==this.btnOk){
			this.actionCode=this.OK;
			this.setVisible(false);
		}
		else if(s==this.btnCancel){
			this.actionCode=this.CANCEL;
			this.setVisible(false);
		}
	}
	public int getActionCode(){
		return actionCode;
	}
	public String getSQL(){
		String sql="select * from bookInfo where ";
		if(radID.isSelected())
			sql=sql+" bookID like '%"+txtID.getText().trim()+"%'";
		else if(radBookName.isSelected())
			sql=sql+" bookName like '%"+txtBookName.getText().trim()+"%'";
		else if(radBookPress.isSelected())
			sql=sql+" bookPress like '%"+txtBookPress.getText().trim()+"%'";
		return sql;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?