94 lines
2.9 KiB
Java
94 lines
2.9 KiB
Java
package aufgabe1;
|
|
|
|
import javax.swing.*;
|
|
import java.awt.event.*;
|
|
import java.util.Optional;
|
|
|
|
public class BookDatabaseViewer extends JDialog {
|
|
private JPanel contentPane;
|
|
private JButton buttonOK;
|
|
private JButton buttonCancel;
|
|
private JComboBox<String> comboBoxTitle;
|
|
private JTextField textFieldTitle;
|
|
private JTextField textFieldAuthor;
|
|
private JTextField textFieldVerlag;
|
|
private JTextField textFieldValue;
|
|
private JButton verfuegbarkeitPruefenButton;
|
|
|
|
private final BookDatabase bookDatabase;
|
|
|
|
private Optional<Book> currentBook = Optional.empty();
|
|
|
|
public BookDatabaseViewer(BookDatabase bookDatabase) {
|
|
setContentPane(contentPane);
|
|
setModal(true);
|
|
getRootPane().setDefaultButton(buttonOK);
|
|
setTitle("Book Database");
|
|
|
|
this.bookDatabase = bookDatabase;
|
|
|
|
buttonOK.addActionListener(e -> onOK());
|
|
|
|
buttonCancel.addActionListener(e -> onCancel());
|
|
|
|
textFieldValue.setEditable(false);
|
|
textFieldVerlag.setEditable(false);
|
|
textFieldAuthor.setEditable(false);
|
|
textFieldTitle.setEditable(false);
|
|
|
|
// call onCancel() when cross is clicked
|
|
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
|
|
addWindowListener(new WindowAdapter() {
|
|
public void windowClosing(WindowEvent e) {
|
|
onCancel();
|
|
}
|
|
});
|
|
|
|
// call onCancel() on ESCAPE
|
|
contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
|
|
comboBoxTitle.addActionListener(e -> {
|
|
SwingUtilities.invokeLater(this::selectTitle);
|
|
});
|
|
verfuegbarkeitPruefenButton.addActionListener(this::checkAvailability);
|
|
|
|
bookDatabase.getTitles().forEach(comboBoxTitle::addItem);
|
|
|
|
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
|
|
pack();
|
|
setLocationByPlatform(true);
|
|
setVisible(true);
|
|
}
|
|
|
|
private void checkAvailability(ActionEvent actionEvent) {
|
|
if (currentBook.isPresent()) {
|
|
var book = currentBook.get();
|
|
|
|
JOptionPane.showMessageDialog(this, "Is the book available? " + (book.available() ? "Yes" : "No"));
|
|
}
|
|
}
|
|
|
|
private void selectTitle() {
|
|
var title = (String) this.comboBoxTitle.getSelectedItem();
|
|
currentBook = bookDatabase.getBook(title);
|
|
|
|
if (currentBook.isPresent()) {
|
|
var book = currentBook.get();
|
|
|
|
this.textFieldTitle.setText(book.title());
|
|
this.textFieldAuthor.setText(book.author());
|
|
this.textFieldValue.setText(String.format("%.2f€", book.value()));
|
|
this.textFieldVerlag.setText(book.verlag());
|
|
}
|
|
}
|
|
|
|
private void onOK() {
|
|
// add your code here
|
|
dispose();
|
|
}
|
|
|
|
private void onCancel() {
|
|
// add your code here if necessary
|
|
dispose();
|
|
}
|
|
}
|