Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Chapter 13 Lab Advanced GUI Applications Lab Objectives Introduction In this lab

ID: 3559532 • Letter: C

Question

Chapter 13 Lab

Advanced GUI Applications

Lab Objectives

Introduction

In this lab we will be creating a simple note taking interface. It is currently a working program, but we will be adding features to it. The current program displays a window which has one item on the menu bar, Notes, which allows the user 6 choices. These choices allow the user to store and retrieve up to 2 different notes. It also allows the user to clear the text area or exit the program.

We would like to add features to this program which allows the user to change how the user interface appears. We will be adding another choice on the menu bar called Views, giving the user choices about scroll bars and the look and feel of the GUI.

Task #1 Creating a Menu with Submenus

menus. The three methods that we will be writing are createViews(), createScrollBars(), and createLookAndFeel(). The method headings with empty bodies are provided.

Explanation / Answer

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Iterator;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.jfree.ui.RefineryUtilities;

import com.googlecode.logVisualizer.Settings;
import com.googlecode.logVisualizer.logData.LogDataHolder;
import com.googlecode.logVisualizer.logData.turn.TurnInterval;
import com.googlecode.logVisualizer.parser.LogsCreator;
import com.googlecode.logVisualizer.util.TextLogCreator;

/**
* This class is ascension log notes editor, that gives the user a basic
* interface to manage log notes.
*/
public final class Notetaker extends JFrame {
    private final LogDataHolder log;

    private final JButton saveButton;

    private final TurnIntervalMenuList turnIntervalMenu;

    private final JTextArea turnIntervalPrintoutArea;

    private final JTextArea notesArea;

    private TurnIntervalContainer activeTurnInterval;

    /**
     * Creates the notes editor frame.
     *
     * @param log
     *            The log data whose notes should be managed.
     */
    public Notetaker(
                     final LogDataHolder log) {
        super("Notetaker for " + log.getLogName());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLayout(new BorderLayout(5, 25));

        this.log = log;
        saveButton = new JButton("Save log to file");
        turnIntervalMenu = new TurnIntervalMenuList(log);
        turnIntervalPrintoutArea = new JTextArea();
        notesArea = new JTextArea();
        getContentPane().add(createNotePanel(), BorderLayout.CENTER);
        getContentPane().add(createButtonPanel(), BorderLayout.SOUTH);
        addListeners();
        turnIntervalMenu.setSelectedIndex(0);
        turnIntervalPrintoutArea.setEditable(false);

        setSize(800, 600);
        RefineryUtilities.centerFrameOnScreen(this);
        setVisible(true);
    }

    private JPanel createNotePanel() {
        final JPanel notePanel = new JPanel(new BorderLayout());
        final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

        splitPane.setTopComponent(new JScrollPane(turnIntervalPrintoutArea));
        splitPane.setBottomComponent(new JScrollPane(notesArea));
        splitPane.setDividerLocation(250);

        notePanel.add(new JScrollPane(turnIntervalMenu), BorderLayout.WEST);
        notePanel.add(splitPane, BorderLayout.CENTER);

        return notePanel;
    }

    private JPanel createButtonPanel() {
        final JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 200, 0));
        final JButton closeButton = new JButton("Close window");

        saveButton.setPreferredSize(new Dimension(0, 40));
        closeButton.setPreferredSize(new Dimension(0, 40));
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(
                                        final ActionEvent e) {
                if (activeTurnInterval != null)
                    activeTurnInterval.setNotes(notesArea.getText());

                dispose();
            }
        });

        buttonPanel.add(saveButton);
        buttonPanel.add(closeButton);

        return buttonPanel;
    }

    private void addListeners() {
        turnIntervalMenu.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(
                                     final ListSelectionEvent lse) {
                if (!lse.getValueIsAdjusting()) {
                    if (activeTurnInterval != null)
                        activeTurnInterval.setNotes(notesArea.getText());

                    activeTurnInterval = turnIntervalMenu.getCurrentlySelectedTurnInterval();
                    turnIntervalPrintoutArea.setText(activeTurnInterval.getTurnIntervalPrintout());
                    notesArea.setText(activeTurnInterval.getNotes());
                }
            }
        });
        saveButton.addActionListener(new ActionListener() {
            public void actionPerformed(
                                        final ActionEvent e) {
                if (activeTurnInterval != null)
                    activeTurnInterval.setNotes(notesArea.getText());

                new SaveDialog();
            }
        });
    }

    /**
     * Just a little helper class make instantiation of the turn interval menu a
     * little nicer.
     */
    private static final class TurnIntervalMenuList extends JList {

        /**
         * Creates the turn interval menu.
         *
         * @param log
         *            The log data whose notes should be managed.
         */
        TurnIntervalMenuList(
                             final LogDataHolder log) {
            super(new DefaultListModel());
            setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

            final Iterator<String> turnRundownListIndex = TextLogCreator.getTurnRundownList(log)
                                                                        .iterator();
            for (final TurnInterval ti : log.getTurnsSpent())
                ((DefaultListModel) getModel()).addElement(new TurnIntervalContainer(ti,
                                                                                     turnRundownListIndex.next()));
        }

        TurnIntervalContainer getCurrentlySelectedTurnInterval() {
            if (isSelectionEmpty())
                throw new IllegalStateException("No turn interval is currently selected.");

            return (TurnIntervalContainer) ((DefaultListModel) getModel()).get(getSelectedIndex());
        }
    }

    /**
     * The dialog that is seen when one wants to save the log to a file.
     */
    private final class SaveDialog extends JDialog {
        private final JTextField directoryLocationField = new JTextField(Settings.getSettingString("Parsed logs saving location"));

        /**
         * Creates and shows the save dialog in the centre of the screen. Please
         * note that this dialog is also modal on the notes editor frame.
         */
        SaveDialog() {
            super(Notetaker.this, true);
            setTitle("Choose saving directory for the ascension log");
            setLayout(new BorderLayout(0, 10));

            getContentPane().add(createDirectoryFinderPanel(), BorderLayout.CENTER);
            getContentPane().add(createButtonPanel(), BorderLayout.SOUTH);

            pack();
            setSize(500, getSize().height);
            RefineryUtilities.centerFrameOnScreen(this);
            setVisible(true);
        }

        private JPanel createDirectoryFinderPanel() {
            final JPanel panel = new JPanel(new GridBagLayout());
            final JButton directoryChooserButton = new JButton("Find Directory");
            GridBagConstraints gbc;

            gbc = new GridBagConstraints();
            gbc.gridx = 1;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            gbc.insets = new Insets(10, 10, 5, 0);
            panel.add(directoryLocationField, gbc);

            gbc = new GridBagConstraints();
            gbc.gridx = 2;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.EAST;
            gbc.insets = new Insets(10, 25, 5, 10);
            panel.add(directoryChooserButton, gbc);

            File logsDirectory = new File(directoryLocationField.getText());
            if (!logsDirectory.exists())
                logsDirectory = null;

            final JFileChooser directoryChooser = new JFileChooser(logsDirectory);
            directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            directoryChooserButton.addActionListener(new ActionListener() {
                public void actionPerformed(
                                            final ActionEvent e) {
                    final int state = directoryChooser.showOpenDialog(null);
                    if (state == JFileChooser.APPROVE_OPTION)
                        directoryLocationField.setText(directoryChooser.getSelectedFile()
                                                                       .getAbsolutePath());
                }
            });

            return panel;
        }

        private JPanel createButtonPanel() {
            final JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 100, 0));
            final JButton closeButton = new JButton("Cancel");
            final JButton saveButton = new JButton("OK");

            saveButton.setPreferredSize(new Dimension(0, 30));
            saveButton.addActionListener(new ActionListener() {
                public void actionPerformed(
                                            final ActionEvent e) {
                    try {
                        String filePath = directoryLocationField.getText();
                        if (!filePath.endsWith(File.separator))
                            filePath += File.separator;

                        final File logsDest = new File(filePath
                                                       + LogsCreator.getParsedLogNameFromCondensedMafiaLog(log.getLogName())
                                                       + ".txt");
                        if (logsDest.exists())
                            logsDest.delete();
                        logsDest.createNewFile();

                        final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(logsDest),
                                                                                      50000));
                        writer.print("[code]" + TextLogCreator.getTextualLog(log) + "[/code]");
                        writer.close();

                        Settings.setSettingString("Parsed logs saving location",
                                                  directoryLocationField.getText());
                    } catch (final IOException e1) {
                        JOptionPane.showMessageDialog(null,
                                                      "A problem occurred while creating the log.",
                                                      "Error occurred",
                                                      JOptionPane.ERROR_MESSAGE);
                        e1.printStackTrace();
                    }
                    dispose();
                }
            });
            closeButton.setPreferredSize(new Dimension(0, 30));
            closeButton.addActionListener(new ActionListener() {
                public void actionPerformed(
                                            final ActionEvent e) {
                    dispose();
                }
            });

            buttonPanel.add(saveButton);
            buttonPanel.add(closeButton);

            return buttonPanel;
        }
    }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote