Java Swing App - Trouble Navigating to Previous "screen/view"

28 views Asked by At

I am creating a simple app that interfaces with an AS400 database using JT400 library and swing components for the GUI. The goal is to list active jobs of AS400 user so user can click one to get a notification about it's status changes.

The basic flow is this:

  1. Input dialogue appears asking for username and password - click submit to sign in
  2. Dialogue goes away and Jframe (main screen) appears with a Jtable and Jbutton
  3. Select a row from table and click button to go to new screen
  4. New screen displays a message and a back button
  5. Clicking the back button takes you back to the main screen with the table and submit button
  6. Repeat steps 3-5 until you exit the application

I can get all the way to step 4 but cannot get the "back" button to revert the Jframe to its previous state displaying the Jtable and button on the "main" screen.

My code is below. There are a couple of button event listeners in "public TEST_GUI()" which are supposed to handle the screen changes. I think the issue is in one of these listeners.

package com.lprice.mvc;

import com.ibm.as400.access.*;

import javax.swing.*;
import java.awt.*;

import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.util.*;
import java.util.List;

public class TEST_GUI extends JFrame {
    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;
    final static boolean RIGHT_TO_LEFT = false;

    private JLabel lblUser;
    private JLabel lblPass;
    private JTable tblSpool;
    private AS400 as400;


    public TEST_GUI() throws PropertyVetoException, AS400SecurityException, ObjectDoesNotExistException, IOException, InterruptedException, ErrorCompletingRequestException {
        // set up Jframe
        super("Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);

        // create JPanel to use as main screen
        Container firstPane = this.getContentPane();
        firstPane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        if (shouldFill) {
            //natural height, maximum width
            c.fill = GridBagConstraints.HORIZONTAL;
        }
        if (RIGHT_TO_LEFT) {
            firstPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }

        lblUser = new JLabel("Username:");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        firstPane.add(lblUser, c);

        tblSpool = new JTable();
        JScrollPane scrollPane = new JScrollPane(tblSpool);
        scrollPane.setForeground(Color.blue);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = 1;
        c.weighty = 2.5;
        firstPane.add(scrollPane, c);

        JButton btnSubmit = new JButton("Submit");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = 2;
        firstPane.add(btnSubmit, c);

        // create table row select logic
        tblSpool.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting() && tblSpool.getSelectedRow() != -1) {
                System.out.println(tblSpool.getValueAt(tblSpool.getSelectedRow(), 0).toString());
            }
        });

        // create button click action
        btnSubmit.addActionListener(e -> {
            System.out.println("clicked submit");

            // Hide the current JPanel
            firstPane.setVisible(false);

            // Create a new JPanel for the message
            JPanel panelSubmitMsg = new JPanel();
            panelSubmitMsg.setLayout(new BorderLayout());

            // Create a JLabel with the message
            JLabel messageLabel = new JLabel("Beginning JOB monitor for the following JOB: {jobNameHere}");
            messageLabel.setHorizontalAlignment(JLabel.CENTER);
            panelSubmitMsg.add(messageLabel, BorderLayout.CENTER);

            // Create a JButton to go back to the previous JPanel
            JButton backButton = new JButton("Back");
            backButton.addActionListener(backEvent -> {
                System.out.println("clicked the back button");

                // Show the previous JPanel
                firstPane.setVisible(true);

                // Remove the messagePanel from the JFrame
                this.getContentPane().remove(panelSubmitMsg);

                // Repaint the JFrame to reflect the changes
                this.revalidate();
                this.repaint();
            });
            panelSubmitMsg.add(backButton, BorderLayout.SOUTH);

            // Add the new JPanel to your existing JFrame
            this.setContentPane(panelSubmitMsg);

            // Repaint the JFrame to reflect the changes
            this.revalidate();
            this.repaint();

            // Run your background process here
        });



        // ========================================
        // create panel to use in credential dialog
        // ========================================
        JTextField userField = new JTextField(5);
        JPasswordField passField = new JPasswordField(5);

        JPanel myPanel = new JPanel(new GridBagLayout());
        c = new GridBagConstraints();

        c.fill = GridBagConstraints.HORIZONTAL;

        c.gridx = 0;
        c.gridy = 0;
        myPanel.add(new JLabel("Username:"), c);

        c.gridx = 1;
        c.weightx = 0.2;
        myPanel.add(Box.createHorizontalStrut(5), c);

        c.gridx = 2;
        c.weightx = 0.5;
        myPanel.add(userField, c);

        c.gridy = 1;
        c.gridx = 0;
        myPanel.add(new JLabel("password:"), c);

        c.gridx = 1;
        c.weightx = 0.2;
        myPanel.add(Box.createHorizontalStrut(5), c);

        c.weightx = 0.5;
        c.gridx = 2;
        myPanel.add(passField, c);

        int result = JOptionPane.showConfirmDialog(null, myPanel,
                "Enter username and password", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            System.out.println("user input received");
            lblUser.setText("Username:  " + userField.getText());
            AS400 as400 = new AS400("database name",userField.getText(),new String(passField.getPassword()));
            updateSpoolTable(as400);
            setVisible(true);
        }

    }

    public AS400 getConnection() {
        return as400;
    }

    /**
     * Fetches current job information for the user in the given AS400 instance
     * @param as400  the AS400 instance to be used to grab job information
     */
    private void updateSpoolTable(AS400 as400) throws PropertyVetoException, AS400SecurityException, ObjectDoesNotExistException, IOException, InterruptedException, ErrorCompletingRequestException {
        // Create list of all jobs on server
        JobList jList = new JobList(as400);
        System.out.println("Created list of all jobs on system");


        // Filter job list to current user only
        jList.addJobSelectionCriteria(JobList.SELECTION_USER_NAME, JobList.SELECTION_USER_NAME_CURRENT); // Filter job list to active user
        jList.addJobSelectionCriteria(JobList.SELECTION_PRIMARY_JOB_STATUS_OUTQ, false); // Filter job list to active only
        System.out.println("Job list filtered to current user");


        // Create enumeration of job list
        Enumeration jobs = jList.getJobs();

        // Iterate through job list enumeration to print the status of each job
        System.out.println("Beginning iteration through user jobs");

        // Get username
        String userName = as400.getUserId();

        // Create array of values (will be used to populate the dialogue window)
        java.util.List<String> columns = new ArrayList<>();
        List<String[]> values = new ArrayList<>();

        // Add values to array
        columns.add("Job Name");
        columns.add("Job Number");
        columns.add("Start Date");

        if (jobs.hasMoreElements()) {
            while (jobs.hasMoreElements()) {
                Job job = (Job) jobs.nextElement(); // Advance the enumeration forward
                String jName = job.getName(); // Get job name
                String jNum = job.getNumber(); // Get job number
                Date jDate = job.getDate(); // Get date
                values.add(new String[]{jName, jNum, jDate.toString()});
            }
        } else {
            messageBox("User \"" + userName + "\" does not have any active jobs.");
            System.out.println("class \"messageBox\" is complete");
            System.exit(1);
        }

        //print contents of horizon job array list to console
        for (String[] arr : values) {
            System.out.println(Arrays.toString(arr));
        }

        System.out.println("Iteration complete");

        // Create a dataset. Will be added to table in next step
        TableModel tableModel = new DefaultTableModel(values.toArray(new Object[][]{}), columns.toArray());

        // Populate swing table with dataset
        tblSpool.setModel(tableModel);

        pack();
    }

    public void messageBox (String message){
        String html = "<html><body style='width: %1spx'>%1s";

        JOptionPane.showMessageDialog(
                null, String.format(html, 300, message));

        System.out.println("User clicked \"OK\"");


    }

    public static void main(String[] args) throws PropertyVetoException, AS400SecurityException, ObjectDoesNotExistException, IOException, InterruptedException, ErrorCompletingRequestException {
        new TEST_GUI();
    }
}
0

There are 0 answers