java实现图形界面设计
需求1:对应数据库建立相关表并连接
需求2:GUI组件选择以及界面的实现
需求3:功能实现:
1.从文件中读取初始数据:单击“从文件中读取记录”,使用字符流从'book.txt'文件中读取图书信息,显示到JList中
实现的代码:
//从文件中读取初始数据按钮监听器
Read.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(".\\src\\Final\\book.txt"));
String data;
while ((data=br.readLine())!=null){
model.addElement(data);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if(br!=null){
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
});
2.添加记录:检查左侧图书容器输入信息的完整性,并将其追加到图书列表到 JList 或 JTable 中与(1)初始数据一起显示。可以多次添加记录。
实现代码:
//添加记录按钮监听器功能实现
Add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Book book = new Book();
try {
book.setISBN(ISBNTxt.getText());
book.setBookName(BookNameTxt.getText());
book.setPublisher((String)jComboBox.getSelectedItem());
if(Chinese.isSelected()){
book.setType("中文");
} else if(English.isSelected()){
book.setType("英文");
}else{
JOptionPane.showMessageDialog(null
,"输入有误","书本添加"
,JOptionPane.WARNING_MESSAGE);
}
book.setPrice(Double.parseDouble(PriceTxt.getText()));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null
,"输入有误","书本添加"
,JOptionPane.WARNING_MESSAGE);
}
model.addElement(book.toString());
B.addElement(book);
}
});
3.写入数据库:将JList中的数据写入到数据库中(未实现将文件中读取的记录写入到数据库中)写入数据库后 会清空JList中所有数据
实现代码:
Write.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
//定义驱动
Connection conn = DriverManager.getConnection(url,useName,password);
//定义Statement
Statement stmt = conn.createStatement();
//获取每个数据
int size= B.size();
for(int i = 0;i<size;i++){
Book object = B.elementAt(i);
String sql = "insert into book values('"+object.getISBN()+"','"+object.getBookName()+"','"+object.getPublisher()+"','"+object.getType()+"',"+object.getPrice()+")";
//执行sql语句
stmt.execute(sql);
//添加成功
System.out.println("添加成功");
}
stmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
model.clear();
B.clear();
}
}
});
4.按出版社查询:在最左侧的”图书”的出版社列表框中,选择某出版社,单击”按出版社查询”时,按照该出版社进行查询,将查询后的结果显示在 JList 中
通过数据库进行查询
实现代码:
Research.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//定义驱动
Connection conn = null;
try {
conn = DriverManager.getConnection(url,useName,password);
//定义Statement
Statement stmt = conn.createStatement();
//定义sql语句
String choice = (String) jComboBox.getSelectedItem();
if(choice.equals("高等教育出版社")){
String sql1 = "select * from book where publisher = '高等教育出版社'";
ResultSet rs1 = stmt.executeQuery(sql1);
while(rs1.next()){
String BookName = rs1.getString("title");
String isbn = rs1.getString("isbn");
String publisher = rs1.getString("publisher");
String type = rs1.getString("language");
double price = rs1.getDouble("price");
String total = isbn+","+BookName+","+publisher+","+type+","+price;
model.addElement(total);
}
}
if (choice.equals("机械工业出版社")){
String sql2 = "select * from book where publisher = '机械工业出版社'";
ResultSet rs2 = stmt.executeQuery(sql2);
while(rs2.next()){
String BookName = rs2.getString("title");
String isbn = rs2.getString("isbn");
String publisher = rs2.getString("publisher");
String type = rs2.getString("language");
double price = rs2.getDouble("price");
String total = isbn+","+BookName+","+publisher+","+type+","+price;
model.addElement(total);
}
}
if (choice.equals("清华大学出版社")){
String sql3 = "select * from book where publisher = '清华大学出版社'";
ResultSet rs3 = stmt.executeQuery(sql3);
while(rs3.next()){
String BookName = rs3.getString("title");
String isbn = rs3.getString("isbn");
String publisher = rs3.getString("publisher");
String type = rs3.getString("language");
double price = rs3.getDouble("price");
String total = isbn+","+BookName+","+publisher+","+type+","+price;
model.addElement(total);
}
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
});
5.线程:利用线程实现倒计时功能
A.要求在程序中自动计算出当前时刻到 2023 年
5
月
1
日的时间间 隔(单位为秒),以此间隔作为倒计时初始值。
B.点击“开始倒计时”开始计时并以 1
秒的间隔不断更新时间,按 钮标题变为“停止倒计时”; 单击“停止倒计时”按钮,则中止计时,按 钮标题变为“开始倒计时”。
实现代码:
线程类(Runnable接口):
class ThreadDown implements Runnable{
//判断进程是否停止
boolean stop = true;
//计算倒计时时间
int num = 0;
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,2023);
calendar.set(Calendar.MONTH,5);
calendar.set(Calendar.DAY_OF_MONTH,1);
num = (int) ((calendar.getTimeInMillis() - System.currentTimeMillis())/1000);
while(true){
if(!stop){
//计算倒计时还有多久
num = num-1;
DownCountTxt.setText(num+"(秒)"); //显示的作用
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
ThreadDown threadDown = new ThreadDown();
Thread t = new Thread(threadDown);
//实现倒计时
Down.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(!threadDown.stop){
Down.setText("开始倒计时");
threadDown.stop = !threadDown.stop;
}else{
Down.setText("停止倒计时");
threadDown.stop = !threadDown.stop;
}
}
});
//驱动线程
t.start();
源码:
package Final;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Vector;
public class FinalTest {
//框架组件
JFrame jFrame = new JFrame("图形界面");
Vector<Book> B =new Vector<>();
//数据库登入
private String url = "jdbc:mysql://localhost:3306/mydb?";
private String useName = "root";
private String password = "自己的对应数据库";
//标签组件
JLabel ISBN = new JLabel("ISBN");
JLabel BookName = new JLabel("书名");
JLabel Price = new JLabel("价格");
JLabel DownCount = new JLabel("距离2023年五一假期还有:");
//列表框组件
DefaultListModel model = new DefaultListModel();
JList jList = new JList(model);
//选择框组件
String []publisher = {"高等教育出版社","清华大学出版社","机械工业出版社"};
JComboBox jComboBox = new JComboBox(publisher);
//选择按钮组件
JRadioButton Chinese = new JRadioButton("中文",false);
JRadioButton English = new JRadioButton("英文",false);
ButtonGroup bg = new ButtonGroup();
//滑动框组件
JScrollPane jScrollPane = new JScrollPane();
//文本行组件
JTextField ISBNTxt = new JTextField(10);
JTextField BookNameTxt = new JTextField(10);
JTextField PriceTxt = new JTextField(10);
JTextField DownCountTxt = new JTextField();
//按钮组件
JButton Read = new JButton("从文件中读取记录");
JButton Add = new JButton("添加记录");
JButton Write = new JButton("写入数据库");
JButton Research = new JButton("按出版社查询");
JButton Down = new JButton("开始倒计时");
//容器组件
JPanel PanelTotal = new JPanel();
JPanel PanelLeft = new JPanel();
JPanel PanelLeft1 = new JPanel();
JPanel PanelLeft2 =new JPanel();
JPanel PanelLeft3 = new JPanel();
JPanel PanelLeft4 = new JPanel();
JPanel PanelLeft5 =new JPanel();
JPanel PanelMiddle = new JPanel();
JPanel PanelMiddleSouth = new JPanel();
JPanel PanelRight =new JPanel();
JPanel PanelRightMiddle = new JPanel();
JPanel PanelRightSouth = new JPanel();
JPanel PanelRightNorth = new JPanel();
JPanel Left = new JPanel();
//有关线程
ThreadDown threadDown = new ThreadDown();
Thread t = new Thread(threadDown);
public void init(){
//组装组件
//PanelTotal.setLayout(new FlowLayout(FlowLayout.LEFT));
PanelTotal.setLayout(new GridLayout(1,3));
//组装左侧组件
PanelLeft.setLayout(new GridLayout(5,1));
//左侧第一组
PanelLeft1.setLayout(new FlowLayout(FlowLayout.LEFT));
PanelLeft1.add(ISBN);
PanelLeft1.add(ISBNTxt);
PanelLeft.add(PanelLeft1);
//左侧第二组
PanelLeft2.setLayout(new FlowLayout(FlowLayout.LEFT));
PanelLeft2.add(BookName);
PanelLeft2.add(BookNameTxt);
PanelLeft.add(PanelLeft2);
//左侧第三组
PanelLeft3.setLayout(new FlowLayout(FlowLayout.LEFT));
PanelLeft3.add(jComboBox);
PanelLeft.add(PanelLeft3);
//左侧第四组
bg.add(Chinese);
bg.add(English);
PanelLeft4.setLayout(new FlowLayout(FlowLayout.LEFT));
PanelLeft4.add(Chinese);
PanelLeft4.add(English);
PanelLeft.add(PanelLeft4);
//左侧第五组
PanelLeft5.setLayout(new FlowLayout(FlowLayout.LEFT));
PanelLeft5.add(Price);
PanelLeft5.add(PriceTxt);
PanelLeft.add(PanelLeft5);
//将左侧总框架加入到总框架中
PanelLeft.setBorder(new TitledBorder("图书"));
PanelTotal.add(PanelLeft);
//组装中部框架
PanelMiddle.setLayout(new BorderLayout());
//中部中间
jScrollPane.add(jList);
jScrollPane.setViewportView(jList);
PanelMiddle.add(jScrollPane,BorderLayout.CENTER);
//中部最底下
PanelMiddleSouth.setLayout(new FlowLayout(FlowLayout.LEFT));
//从文件中读取初始数据按钮监听器
Read.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(".\\src\\Final\\book.txt"));
String data;
while ((data=br.readLine())!=null){
model.addElement(data);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if(br!=null){
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
});
PanelMiddleSouth.add(Read);
//添加记录按钮监听器功能实现
Add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Book book = new Book();
try {
book.setISBN(ISBNTxt.getText());
book.setBookName(BookNameTxt.getText());
book.setPublisher((String)jComboBox.getSelectedItem());
if(Chinese.isSelected()){
book.setType("中文");
} else if(English.isSelected()){
book.setType("英文");
}else{
JOptionPane.showMessageDialog(null
,"输入有误","书本添加"
,JOptionPane.WARNING_MESSAGE);
}
book.setPrice(Double.parseDouble(PriceTxt.getText()));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null
,"输入有误","书本添加"
,JOptionPane.WARNING_MESSAGE);
}
model.addElement(book.toString());
B.addElement(book);
}
});
PanelMiddleSouth.add(Add);
//写入到数据库
Write.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
//定义驱动
Connection conn = DriverManager.getConnection(url,useName,password);
//定义Statement
Statement stmt = conn.createStatement();
//获取每个数据
int size= B.size();
for(int i = 0;i<size;i++){
Book object = B.elementAt(i);
String sql = "insert into book values('"+object.getISBN()+"','"+object.getBookName()+"','"+object.getPublisher()+"','"+object.getType()+"',"+object.getPrice()+")";
//执行sql语句
stmt.execute(sql);
//添加成功
System.out.println("添加成功");
}
stmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
model.clear();
B.clear();
}
}
});
//实现啊按出版社查询按钮功能监听器
PanelMiddleSouth.add(Write);
//实现按出版社查询
Research.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//定义驱动
Connection conn = null;
try {
conn = DriverManager.getConnection(url,useName,password);
//定义Statement
Statement stmt = conn.createStatement();
//定义sql语句
String choice = (String) jComboBox.getSelectedItem();
if(choice.equals("高等教育出版社")){
String sql1 = "select * from book where publisher = '高等教育出版社'";
ResultSet rs1 = stmt.executeQuery(sql1);
while(rs1.next()){
String BookName = rs1.getString("title");
String isbn = rs1.getString("isbn");
String publisher = rs1.getString("publisher");
String type = rs1.getString("language");
double price = rs1.getDouble("price");
String total = isbn+","+BookName+","+publisher+","+type+","+price;
model.addElement(total);
}
}
if (choice.equals("机械工业出版社")){
String sql2 = "select * from book where publisher = '机械工业出版社'";
ResultSet rs2 = stmt.executeQuery(sql2);
while(rs2.next()){
String BookName = rs2.getString("title");
String isbn = rs2.getString("isbn");
String publisher = rs2.getString("publisher");
String type = rs2.getString("language");
double price = rs2.getDouble("price");
String total = isbn+","+BookName+","+publisher+","+type+","+price;
model.addElement(total);
}
}
if (choice.equals("清华大学出版社")){
String sql3 = "select * from book where publisher = '清华大学出版社'";
ResultSet rs3 = stmt.executeQuery(sql3);
while(rs3.next()){
String BookName = rs3.getString("title");
String isbn = rs3.getString("isbn");
String publisher = rs3.getString("publisher");
String type = rs3.getString("language");
double price = rs3.getDouble("price");
String total = isbn+","+BookName+","+publisher+","+type+","+price;
model.addElement(total);
}
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
});
PanelMiddleSouth.add(Research);
PanelMiddle.add(PanelMiddleSouth,BorderLayout.SOUTH);
//将中部框架加入到总框架中
PanelTotal.add(PanelMiddle);
//组装右侧
PanelRight.setLayout(new BorderLayout());
//右部上方
PanelRightNorth.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelRightNorth.add(DownCount);
PanelRight.add(PanelRightNorth,BorderLayout.NORTH);
//右部中间
//DownCountTxt.setForeground(Color.white);
DownCountTxt.setPreferredSize(new Dimension(300,100));
DownCountTxt.setBackground(Color.CYAN);
DownCountTxt.setFont(new Font("宋体",Font.PLAIN,30));
PanelRightMiddle.add(DownCountTxt,BorderLayout.CENTER);
PanelRight.add(PanelRightMiddle,BorderLayout.CENTER);
//右部下方
//实现倒计时
Down.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(!threadDown.stop){
Down.setText("开始倒计时");
threadDown.stop = !threadDown.stop;
}else{
Down.setText("停止倒计时");
threadDown.stop = !threadDown.stop;
}
}
});
//驱动线程
t.start();
PanelRightSouth.add(Down,BorderLayout.CENTER);
PanelRight.add(PanelRightSouth,BorderLayout.SOUTH);
//将右侧加入到总容器中
PanelRight.setBorder(new TitledBorder("假期倒计时"));
PanelTotal.add(PanelRight);
//将总框架加入到jframe中
jFrame.add(PanelTotal);
//基本操作
jFrame.pack();
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ThreadDown implements Runnable{
//判断进程是否停止
boolean stop = true;
//计算倒计时时间
int num = 0;
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,2023);
calendar.set(Calendar.MONTH,5);
calendar.set(Calendar.DAY_OF_MONTH,1);
num = (int) ((calendar.getTimeInMillis() - System.currentTimeMillis())/1000);
while(true){
if(!stop){
//计算倒计时还有多久
num = num-1;
DownCountTxt.setText(num+"(秒)"); //显示的作用
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread extends Thread{
@Override
public void run(){
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(new File(".\\src\\result.txt")));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
new FinalTest().init();
}
}
class Book{
String BookName;
String ISBN;
String Publisher;
String Type;
double price;
public Book() {
}
public Book(String BookName, String ISBN, String Publisher, String Type, double price) {
this.BookName = BookName;
this.ISBN = ISBN;
this.Publisher = Publisher;
this.Type = Type;
this.price = price;
}
public String getBookName() {
return BookName;
}
public void setBookName(String BookName) {
this.BookName = BookName;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public String getPublisher() {
return Publisher;
}
public void setPublisher(String Publisher) {
this.Publisher = Publisher;
}
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString() {
return ISBN+","+BookName+","+Publisher+","+Type+","+price;
}
}
此处的数据库需要自己连接自己对应的数据库
MyThread类此处并没有使用
因为做的时间比较短,注释比较少,同时界面设计不太美观,有任何问题欢迎交流