Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.*;
- /**
- * class extend Jframe
- * class implements Actionlistner
- */
- public class GUI extends JFrame implements ActionListener {
- /**
- * lage GUI
- * four buttons
- * create modelList
- */
- JButton leggTil, fjern, lagre, open;
- DefaultListModel m;
- JList list;
- GUI() {
- this.setSize(450, 400);
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setTitle("Bibliotek");
- this.setLayout(new FlowLayout());
- leggTil = new JButton("Legg til en ny bok");
- fjern = new JButton("Fjern bok");
- lagre = new JButton("Lagre");
- open = new JButton("Åpen");
- m = new DefaultListModel();
- list = new JList(m);
- this.add(list);
- this.add(leggTil);
- this.add(fjern);
- this.add(lagre);
- this.add(open);
- leggTil.addActionListener(this);
- lagre.addActionListener(this);
- fjern.addActionListener(this);
- open.addActionListener(this);
- this.setVisible(true);
- }
- @Override
- public void actionPerformed(ActionEvent e) {
- /**
- * to add elements to the list
- */
- if (e.getSource().equals(leggTil)) {
- //create an object of Bok class
- Bok b = new Bok();
- String navn = JOptionPane.showInputDialog(this, "" +
- "Skriv bok navn?");
- b.setNavn(navn);
- String Forfatter = JOptionPane.showInputDialog(this, "" +
- "Skriv forfatters navn?");
- b.setForfatter(Forfatter);
- int sider = Integer.parseInt(JOptionPane.showInputDialog(this, "" +
- "Skriv antall sider!"));
- b.setSider(sider);
- m.addElement(b);
- }
- /**
- * to save the added elements
- */
- if (e.getSource().equals(lagre)) {
- try {
- FileOutputStream fileOutputStream = new FileOutputStream("Bibliotek.txt");
- ObjectOutputStream o = new ObjectOutputStream(fileOutputStream);
- o.writeObject(m);
- o.close();
- fileOutputStream.close();
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- /**
- * to open the saved lists
- */
- if (e.getSource().equals(open)) {
- try {
- FileInputStream f = new FileInputStream("Bibliotek.txt");
- ObjectInputStream o = new ObjectInputStream(f);
- m = (DefaultListModel) o.readObject();
- list.setModel(m);
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- } catch (IOException e1) {
- e1.printStackTrace();
- } catch (ClassNotFoundException e1) {
- e1.printStackTrace();
- }
- }
- /**
- * to remov one or more selected from the list
- */
- if (e.getSource().equals(fjern)) {
- if (list.getSelectedIndex() != -1) {
- m.remove(list.getSelectedIndex());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement