gpt4 book ai didi

java - 使用新输入更新 JList

转载 作者:行者123 更新时间:2023-12-01 19:01:09 24 4
gpt4 key购买 nike

基本上,我的项目是创建一个简单的图书馆系统,任何给定的用户一次最多可以借出三本书。我使用 BreezySwing 来完成此操作(因为我需要这样做)并使用 JList 列出当前取出的书籍。

要归还书籍,用户在列表中单击要归还的书籍,然后单击“归还”按钮。但是,我不知道如何让 JList 正常工作。

如何向列表添加新信息?

这是我到目前为止的代码:

import java.util.*;
import javax.swing.*;
import BreezySwing.*;

public class ClientGUI extends GBFrame {
private JButton returnBook, takeOutBook;
private JLabel title, author;
private JTextField titleInput, authorInput;
private int bookCount = 0;
DefaultListModel books = new DefaultListModel();
private JList booksOut = new JList(books);

public ClientGUI(){
title = addLabel("Title: ",1,1,1,1);
author = addLabel("Author: ",2,1,1,1);
titleInput = addTextField("",1,2,2,1);
authorInput = addTextField("",2,2,2,1);
returnBook = addButton("Return",3,1,1,1);
takeOutBook = addButton("Take Out",3,2,1,1);
booksOut = addList(4,1,2,1);
returnBook.setEnabled(false);
books.addElement("Book - Author");
}

public void buttonClicked(JButton buttonObj){
if(buttonObj == takeOutBook){
if(bookCount < 3){
String titleAdd = titleInput.getText();
String authorAdd = authorInput.getText();
books.addElement(titleAdd + "By: " + authorAdd);
bookCount++;

if(bookCount == 0){
takeOutBook.setEnabled(true);
returnBook.setEnabled(false);
} else if(bookCount == 3){
takeOutBook.setEnabled(false);
returnBook.setEnabled(true);
} else {
takeOutBook.setEnabled(true);
returnBook.setEnabled(true);
}
} else if(bookCount == 3){
JOptionPane.showMessageDialog(null, "Please return a book first", "Invalid Choice", JOptionPane.INFORMATION_MESSAGE);
}
} else if(buttonObj == returnBook){
//int n = (Integer) books.getSelectedValue();
//books.remove(n);
bookCount--;
if(bookCount == 0){
takeOutBook.setEnabled(true);
returnBook.setEnabled(false);
} else if(bookCount == 3){
takeOutBook.setEnabled(false);
returnBook.setEnabled(true);
} else {
takeOutBook.setEnabled(true);
returnBook.setEnabled(true);
}
}
}

public static void main(String args[]){
ClientGUI GUI = new ClientGUI();
GUI.setSize(300,275);
GUI.setTitle("Library");
GUI.setVisible(true);
}
}

基本上,我需要做的就是让 JList 正常工作。剩下的我可以完成。谢谢。

最佳答案

尝试DefaultListModel.addElement

它将触发更新事件以响应列表

更新

如果不知道 BreezySwing 如何工作,我会专注于这一行......

booksOut = addList(4, 1, 2, 1);

鉴于我相信代码中其他行正在执行的操作,这似乎是“创建”一个新的 Jlist 并返回它(应用布局)。

这意味着 booksOut 使用的模型不再是 books 模型。

尝试添加

booksOut.setModel(books);

addList 行之后看看是否有帮助

关于java - 使用新输入更新 JList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12233525/

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