gpt4 book ai didi

java - JTable 中的有条件按钮/复选框

转载 作者:行者123 更新时间:2023-12-01 17:22:56 25 4
gpt4 key购买 nike

我正在为一个学校项目制作一个图书馆系统。在我的搜索函数中,我有一个 SQL 查询,该查询会输出到结果集中,然后用于创建 DefaultTableModel,而 DefaultTableModel 又用于更新表并显示搜索结果。

此搜索的代码如下:

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;

public class Search
{
private final String searchTerm, fileDir, table, defOrder;
private String condition;
private final String [] bookColumnNames;
private final boolean showLoaned, showDistinct;

public Search(String term, String dir, String tbl, String order, boolean showLoan, boolean distinct)
{
this.bookColumnNames = new String[]{"Title", "Author", "Genre", "ISBN", "Checkout"};
searchTerm = term;
fileDir = dir;
table = tbl;
showLoaned = showLoan;
showDistinct = !distinct;
defOrder = order;
}

DefaultTableModel searchBooks()
{
DefaultTableModel res = new DefaultTableModel();

for (String columnName : bookColumnNames)
{
res.addColumn(columnName);
}

if(isISBN(searchTerm))condition = "ISBN LIKE '" + searchTerm + "*'";
else if(showLoaned)condition = "Title LIKE '" + searchTerm + "*' OR Author LIKE '" + searchTerm + "*' OR Genre LIKE '" + searchTerm + "*'";
else condition = "(Title LIKE '" + searchTerm + "*' OR Author LIKE '" + searchTerm + "*' OR Genre LIKE '" + searchTerm + "*') AND Loaned = No";

String defaultQuery;
if(showDistinct) defaultQuery = "SELECT DISTINCT Title, Author, Genre, ISBN from " + table + " WHERE " + condition + " " + defOrder + ";";
else defaultQuery = "SELECT Title, Author, Genre, ISBN from " + table + " WHERE " + condition + " " + defOrder + ";";

ResultSet resSet = search(defaultQuery);

int columns = 4;

try
{
while (resSet.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = resSet.getObject(i);
}

res.insertRow(resSet.getRow()-1,row);
}
}
catch(SQLException e)
{
}

return res;
}

ResultSet search(String defQuery)
{
ResultSet res = null;
try
{
Connection connection = DriverManager.getConnection("jdbc:ucanaccess://" + fileDir);
PreparedStatement prepState = connection.prepareStatement(defQuery);
res = prepState.executeQuery();
}
catch(SQLException e)
{
System.out.println(e);
}
return res;
}

private boolean isISBN(String term)
{
boolean check = true;

if(term.length() == 13)
{
for(int i = 1; i <= term.length(); i++)
{
if(!Character.isDigit(term.charAt(i - 1)))
{
check = false;
break;
}
}
}
else
{
check = false;
}

return check;
}

更新表格的代码在这里:

private void searchBarButtonActionPerformed(java.awt.event.ActionEvent evt) 
{
search = new Search(searchBar.getText(), config.get("databaseFileDirectory"),"tblBooks", config.get("defaultBookSort"), showLoaned.isSelected(), showDistinct.isSelected());
DefaultTableModel model = search.searchBooks();
searchResults.setModel(model);

numSearchResults.setText(model.getRowCount() + " result(s) found");
}

有没有办法根据书是否被借出在表格的最后一列中放置一个按钮/复选框?如果是这样,我将如何使该按钮发挥作用,以便将特定的表条目添加到二维对象数组或列表中以创建购物车?此按钮/复选框应放置在“结帐”列中。

如果我的方法效率低下/考虑不周,我深表歉意。我从事 Java 开发只有 1.5 年左右,这是我的第一个主要项目。任何有关逻辑解决方案或实际代码的建议将不胜感激。

最佳答案

I am making a library system for a school project.

处理大型 Java 应用程序时,简化编码的一种方法是使用 model / view / controller图案。通过分离关注点,您可以一次专注于应用程序的一个部分。

好吧,我要做一些假设。假设图书馆有书。

那么,让我们创建一个类来保存一本书。该类是一个普通的 Java 类。它与 Swing 或任何类型的 GUI 无关。它是完全独立的。我们称之为模型类。

此类是应用程序模型的一部分。还会有其他类来描述库的其他方面,

import java.util.ArrayList;
import java.util.List;

public class Book {

private final String title;
private final String isbn;

private List<String> author;
private List<String> genre;

public Book(String title, String isbn) {
this.title = title;
this.isbn = isbn;
this.author = new ArrayList<>();
this.genre = new ArrayList<>();
}

public String getTitle() {
return title;
}

public void addAuthor(String author) {
this.author.add(author);
}

public List<String> getAuthor() {
return author;
}

public String getIsbn() {
return isbn;
}

public void addGenre(String genre) {
this.genre.add(genre);
}

public List<String> getGenre() {
return genre;
}

}

在Java中,类名是TitleCase。方法名称和字段名称采用驼峰命名法。

Book中的一切类(class)与一本书有关。为了收集书籍,我们将创建一个 List<Book>在不同的模型类中。

一本书只有一个标题。它可以有一个副标题,但我选择不包含副标题字段。如果需要,您可以添加字幕字段。

一本书有一个或多个作者。

一本书有一个 ISBN 代码。

一本书可以分为一种或多种类型。

现在,我们仍然需要为顾客树立榜样。从逻辑上讲,这将是 Patron类(class)。

import java.util.ArrayList;
import java.util.List;

public class Patron {

private String name;
private String address;
private String phoneNumber;

private List<Book> checkedOut;

public Patron(String name, String address, String phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.checkedOut = new ArrayList<>();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public List<Book> getCheckedOut() {
return checkedOut;
}

public void addCheckedOut(Book checkedOut) {
this.checkedOut.add(checkedOut);
}

public void removeCheckedOut(Book returned) {
this.checkedOut.remove(returned);
}
}

我想您已经了解了应用程序模型的想法。

首先,创建完整的应用程序模型。

其次,从应用程序模型创建 SQL 表。创建 SQL包含所有 SQL 代码的类。我没有看到足够的代码来创建 SQL为你上课。

第三,创建 Swing GUI。您可以在此步骤中使用 Swing 默认模型。

这是我的一个 SQL 类,可让您了解如何编写 SQL 类的代码。我正在使用MySQL。您应该始终使用准备好的语句来防止 SQL injection attacks .

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.amazon.ask.model.User;
import com.ggl.bible.reader.model.Book;
import com.ggl.bible.reader.model.Verse;
import com.ggl.bible.reader.model.VerseKey;

public class SQL {

private Connection connection;

public boolean connect() {
try {
String[] params = createConnectionStrings();
connection = DriverManager.getConnection(params[0],
params[1], params[2]);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}

private String[] createConnectionStrings() {
String[] connection = new String[3];
String host = "bible-database.caaitaoyrsgp.us-east-1."
+ "rds.amazonaws.com";
String port = "3306";
String user = "ggleblanc";
String useSSL = "?useSSL=false";
String schema = "/bible";
String password = "******************";
String driver = "jdbc:mysql://" + host + ":" + port;
driver += schema + useSSL;
connection[0] = driver;
connection[1] = user;
connection[2] = password;
return connection;
}

public void close() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

public Optional<Timestamp> selectLastCreated() {
StringBuilder builder = new StringBuilder();
builder.append("SELECT `timestamp` ");
builder.append(" FROM `bible`.`lastCreated` ");
builder.append(" ORDER BY `timestamp` DESC ");
builder.append(" LIMIT 0, 1; ");
String sql = builder.toString();

try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
rs.next();
Optional<Timestamp> timestamp = Optional.of(
rs.getTimestamp(1));
rs.close();
return timestamp;
} catch (SQLException e) {
e.printStackTrace();
return Optional.empty();
}

}

public List<Book> selectBooks() {
List<Book> books = new ArrayList<>();
StringBuilder builder = new StringBuilder();
builder.append("SELECT `bookId`, `bookShortName`, ");
builder.append(" `bookName` ");
builder.append(" FROM `bible`.`book`; ");
String sql = builder.toString();

try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
int bookID = rs.getInt("bookID");
String bookShortName = rs.getString(
"bookShortName");
String bookName = rs.getString("bookName");
Book book = new Book(bookID, bookShortName,
bookName);
books.add(book);
}
rs.close();
return books;
} catch (SQLException e) {
e.printStackTrace();
return new ArrayList<Book>();
}
}

public int selectLastChapter(int bookID) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT MAX(`chapter`) ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `bookID` = ? ");
String sql = builder.toString();

try {
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, bookID);
ResultSet rs = statement.executeQuery();
rs.next();
int result = rs.getInt(1);
rs.close();
return result;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}

public int selectLastVerse(int bookID, int chapter) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT MAX(`verse`) ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `bookID` = ? ");
builder.append(" AND `chapter` = ? ");
String sql = builder.toString();

try {
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, bookID);
statement.setInt(2, chapter);
ResultSet rs = statement.executeQuery();
rs.next();
int result = rs.getInt(1);
rs.close();
return result;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}

public List<Verse> selectPassage(VerseKey startVerseKey,
VerseKey endVerseKey) {
List<Verse> verses = new ArrayList<>();
String[] sql = new String[2];

StringBuilder builder = new StringBuilder();
builder.append("SELECT `verseID` ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `bookID` = ? ");
builder.append(" AND `chapter` = ? ");
builder.append(" AND `verse` = ?; ");
sql[0] = builder.toString();

builder = new StringBuilder();
builder.append("SELECT `bookID`, `chapter`, `verse`, "
+ "`text` ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `verseID` BETWEEN ? AND ? ");
sql[1] = builder.toString();

try {
PreparedStatement statement =
connection.prepareStatement(sql[0]);
statement.setInt(1, startVerseKey.getBookID());
statement.setInt(2, startVerseKey.getChapter());
statement.setInt(3, startVerseKey.getVerse());
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return verses;
}
int startIndex = rs.getInt("verseID");
rs.close();

statement.setInt(1, endVerseKey.getBookID());
statement.setInt(2, endVerseKey.getChapter());
statement.setInt(3, endVerseKey.getVerse());
rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return verses;
}
int endIndex = rs.getInt("verseID");
rs.close();

statement = connection.prepareStatement(sql[1]);
statement.setInt(1, startIndex);
statement.setInt(2, endIndex);
rs = statement.executeQuery();
while (rs.next()) {
int bookID = rs.getInt("bookID");
int chapter = rs.getInt("chapter");
int verseNum = rs.getInt("verse");
String text = rs.getString("text");
Verse verse = new Verse(bookID, chapter,
verseNum, text);
verses.add(verse);
}
rs.close();
return verses;
} catch (SQLException e) {
e.printStackTrace();
return new ArrayList<Verse>();
}
}

public Optional<Verse> selectNextVerse(VerseKey verseKey) {
String[] sql = new String[2];

StringBuilder builder = new StringBuilder();
builder.append("SELECT `verseID` ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `bookID` = ? ");
builder.append(" AND `chapter` = ? ");
builder.append(" AND `verse` = ?; ");
sql[0] = builder.toString();

builder = new StringBuilder();
builder.append("SELECT `bookID`, `chapter`, "
+ "`verse`, `text` ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `verseID` = ? ");
sql[1] = builder.toString();

try {
PreparedStatement statement =
connection.prepareStatement(sql[0]);
statement.setInt(1, verseKey.getBookID());
statement.setInt(2, verseKey.getChapter());
statement.setInt(3, verseKey.getVerse());
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return Optional.empty();
}
int verseID = rs.getInt("verseID");
rs.close();

statement = connection.prepareStatement(sql[1]);
statement.setInt(1, verseID + 1);
rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return Optional.empty();
}
int bookID = rs.getInt("bookID");
int chapter = rs.getInt("chapter");
int verseNum = rs.getInt("verse");
String text = rs.getString("text");
Verse verse = new Verse(bookID, chapter,
verseNum, text);
rs.close();
return Optional.of(verse);
} catch (SQLException e) {
e.printStackTrace();
return Optional.empty();
}
}

public int selectVisitCount(User user) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT `numberOfVisits` ");
builder.append(" FROM `bible`.`archive` ");
builder.append(" WHERE `userID` = ?; ");
String sql = builder.toString();
String userID = user.getUserId();

try {
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return -1;
}
int result = rs.getInt(1);
rs.close();
return result;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}

public int[] selectPassageChapter(User user) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT `passageBookID`, "
+ "`passageChapter`, ");
builder.append(" `passageVerse` ");
builder.append(" FROM `bible`.`archive` ");
builder.append(" WHERE `userID` = ?; ");
String sql = builder.toString();
String userID = user.getUserId();

try {
int[] output = {-1, -1, -1};
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return output;
}
output[0] = rs.getInt("passageBookID");
output[1] = rs.getInt("passageChapter");
output[2] = rs.getInt("passageVerse");
rs.close();
return output;
} catch (SQLException e) {
e.printStackTrace();
int[] output = {-1, -1, -1};
return output;
}
}

public int[] selectReadingChapter(User user) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT `readingBookID`, "
+ "`readingChapter`, ");
builder.append(" `readingStartVerse`, "
+ "`readingEndVerse` ");
builder.append(" FROM `bible`.`archive` ");
builder.append(" WHERE `userID` = ?; ");
String sql = builder.toString();
String userID = user.getUserId();

try {
int[] output = {-1, -1, -1, -1};
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return output;
}
output[0] = rs.getInt("readingBookID");
output[1] = rs.getInt("readingChapter");
output[2] = rs.getInt("readingStartVerse");
output[3] = rs.getInt("readingEndVerse");
rs.close();
return output;
} catch (SQLException e) {
e.printStackTrace();
int[] output = {-1, -1, -1, -1};
return output;
}
}

public void insertArchiveRow(User user) {
StringBuilder builder = new StringBuilder();
builder.append("INSERT INTO `bible`.`archive` ");
builder.append(" (`archiveID`, `numberOfVisits`, ");
builder.append(" `readingBookID`, `readingChapter`, ");
builder.append(" `readingStartVerse`, "
+ "`readingEndVerse`, ");
builder.append(" `passageBookID`, ");
builder.append(" `passageChapter`, `passageVerse`, ");
builder.append(" `lastVisitTimeStamp`, `userID`) ");
builder.append("VALUES (DEFAULT, ?, ?, ?, "
+ "?, ?, ?, ?, ?, ");
builder.append(" CURRENT_TIMESTAMP, ?); ");
String sql = builder.toString();
String userID = user.getUserId();

try {
connection.setAutoCommit(false);
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, 1);
statement.setInt(2, 0);
statement.setInt(3, 0);
statement.setInt(4, 0);
statement.setInt(5, 0);
statement.setInt(6, 0);
statement.setInt(7, 0);
statement.setInt(8, 0);
statement.setString(9, userID);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}

public void updateVisitCount(User user) {
StringBuilder builder = new StringBuilder();
builder.append("UPDATE `bible`.`archive` ");
builder.append("SET `numberOfVisits` = "
+ "`numberOfVisits` + 1, ");
builder.append(" `lastVisitTimestamp` = "
+ "CURRENT_TIMESTAMP ");
builder.append("WHERE `userID` = ? ");
String sql = builder.toString();
String userID = user.getUserId();

try {
connection.setAutoCommit(false);
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setString(1, userID);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}

public void updatePassageChapter(User user,
VerseKey verseKey) {
StringBuilder builder = new StringBuilder();
builder.append("UPDATE `bible`.`archive` ");
builder.append("SET `passageBookID` = ?, ");
builder.append(" `passageChapter` = ?, ");
builder.append(" `passageVerse` = ? ");
builder.append("WHERE `userID` = ? ");
String sql = builder.toString();
String userID = user.getUserId();

try {
connection.setAutoCommit(false);
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, verseKey.getBookID());
statement.setInt(2, verseKey.getChapter());
statement.setInt(3, verseKey.getVerse());
statement.setString(4, userID);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}

public void updateReadingChapter(User user,
VerseKey verseKey, int endVerse) {
StringBuilder builder = new StringBuilder();
builder.append("UPDATE `bible`.`archive` ");
builder.append("SET `readingBookID` = ?, ");
builder.append(" `readingChapter` = ?, ");
builder.append(" `readingStartVerse` = ?, ");
builder.append(" `readingEndVerse` = ? ");
builder.append("WHERE `userID` = ? ");
String sql = builder.toString();
String userID = user.getUserId();

try {
connection.setAutoCommit(false);
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, verseKey.getBookID());
statement.setInt(2, verseKey.getChapter());
statement.setInt(3, verseKey.getVerse());
statement.setInt(4, endVerse);
statement.setString(5, userID);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}

}

关于java - JTable 中的有条件按钮/复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61258729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com