我正在使用GUI实现不同方法的库系统类。
我成功制作了所有文字字段和按钮等。
现在,问题是按钮无效。
要么制作这两个类的对象还是存在一些问题,或者从TabbedPane中获取动作事件有些不同,我无法弄清楚。
以下是我的代码示例。没有把所有代码放在一起,因为这太长了。
公共类RunProgram扩展JFrame实现ActionListener {
private static final int WIDTH = 400;
private static final int HEIGHT = 430;
private static final int NUMBER_OF_DIGITS = 30;
private long accessionNumber = 1001;
LibrarySystem ITLib = new LibrarySystem(); //object of LibrarySystem class to be able to use methods in actionListener method.
public RunProgram(){//构造函数
setTitle("Welcome to Library");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setLayout(new BorderLayout());
Container container = getContentPane();
JTabbedPane Pane = new JTabbedPane();
........
public void actionPerformed(ActionEvent e){
String actionCommand = e.getActionCommand();
switch (actionCommand) {
case "Add Book":
String t = title.getText();
String a1 = author1.getText();
String a2 = author2.getText();
String p = publisher.getText();
int py = stringToInt(yop.getText());
String isbn = ISBN.getText();
Book newBook = new Book(t, a1, a2, p, py, isbn, accessionNumber);
if (ITLib.addBook(newBook)) {
title.setText("Book added successfully.");
aNum.setText(Long.toString(accessionNumber));
accessionNumber++;
} else
title.setText("Book already exists!");
break;
case "Delete Book": {
long an = stringToLong(aNum.getText());
if (ITLib.deleteBook(an))
aNum.setText("Book deleted successfully.");
else
aNum.setText("Book doesn't exist!");
break; }
public static void main(String[] args) {
RunProgram RLibrary = new RunProgram();
RLibrary.setVisible(true);
}
请帮忙。 (PS。我只是一个初学者,我们在保护代码方面没有做太多工作,因此大多数编码都采用直接方法。)
答案 0 :(得分:0)
我认为您应该在每个按钮上设置ActionCommand,然后添加ActionListener
public class RunProgram extends JFrame implements ActionListener {
public RunProgram () {
// to do logic to initialise
initComponents();
}
public void initComponents() {
JButton addbook = new JButton("Add Book");
addbook.setActionCommand("Add Book");
addbook.addActionListener(this);
// add code to initialise button and add them to correct tabbed pane
}
}