Close one JFrame before opening another JFrame - java

I want to close completely one JFrame before opening another .
Consider the code :
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
/**
*
* #author X
*
*/
class ServerConnect extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
/**
* Ctor
*/
ServerConnect()
{
this.setTitle("Sever Side Listener");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
gui.setSize(m_sizeX , m_sizeY);
this.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
this.setLocation(m_centerX , m_centerY);
this.setSize(m_sizeX , m_sizeY);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new ServerConnect();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton)
{
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try
{
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try
{
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
this.setVisible(false);
new ServerGUI(ip , s_port);
}
}
}
In actionPerformed() after the user had entered the IP number and port , I set the window to false , i.e :
this.setVisible(false); // don't show the current window
new ServerGUI(ip , s_port); // open another JFrame
I want to close the current JFrame completely, not to set its visibility to false.
How can I do that ?
Regards

Your problem appears that if you call close on the JFrame, the program will exit since you've set its setDefaultCloseOperation to setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);.
Options:
Use a different defaultCloseOperation, one that doesn't close the application, perhaps JFrame.DISPOSE_ON_CLOSE.
Use a JDialog initially instead of a JFrame. These types of windows can't shut down the application. Here is the JDialog and JOptionPane Tutorial
Don't swap JFrames at all, but rather swap views by using a CardLayout. The CardLayout Tutorial link
My own preference is to use a CardLayout as much as possible to avoid annoying the user who usually doesn't appreciate having a bunch of windows flung at him. I also use modal JDialogs when I want to get information from the user in a modal fashion, i.e., where the application absolutely cannot move forward until the user gives the requested information, and non-modal dialogs to present program state monitoring information for the user. I almost never use multiple JFrames in a single application.
Edit
As an aside, I almost never create classes that extend JFrame or any top-level window since I find that much too restricting. Instead most of my GUI type classes are geared towards creating JPanels. The advantage to this is then I can decide when and where I want to put the JPanel, and can change my mind at any time. It could go into a JFrame, a JDialog, a JOptionPane, be a card that is swapped in a CardLayout,... anywhere.
Edit 2
For example, here's a small program that uses your code, slightly modified, and puts it into a JDialog:
My code:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MyServerMain extends JPanel {
private JTextField serverIp = new JTextField(8);
private JTextField serverPort = new JTextField(8);
private ServerConnect serverConnect = new ServerConnect();
private JDialog serverConnectDialog = null;
public MyServerMain() {
serverIp.setFocusable(false);
serverPort.setFocusable(false);
add(new JLabel("Server IP:"));
add(serverIp);
add(new JLabel("Server Port:"));
add(serverPort);
add(new JButton(new SetUpServerAction("Set Up Server", KeyEvent.VK_S)));
}
private class SetUpServerAction extends AbstractAction {
public SetUpServerAction(String name, int keyCode) {
super(name);
putValue(MNEMONIC_KEY, keyCode);
}
#Override
public void actionPerformed(ActionEvent evt) {
if (serverConnectDialog == null) {
Window owner = SwingUtilities.getWindowAncestor(MyServerMain.this);
serverConnectDialog = new JDialog(owner, "Server Set Up",
ModalityType.APPLICATION_MODAL);
serverConnectDialog.getContentPane().add(serverConnect);
serverConnectDialog.pack();
serverConnectDialog.setLocationRelativeTo(owner);
}
serverConnectDialog.setVisible(true);
// when here, the dialog is no longer visible
// so extract information from the serverConnect object
serverIp.setText(serverConnect.getServerIp());
serverPort.setText(serverConnect.getServerPort());
}
}
private static void createAndShowGui() {
MyServerMain mainPanel = new MyServerMain();
JFrame frame = new JFrame("My Server Main");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Your modified code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class ServerConnect extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
ServerConnect() {
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3, 3));
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
gui.setSize(m_sizeX, m_sizeY);
setLayout(new BorderLayout()); // !!
add(gui, BorderLayout.CENTER);
JPanel labels = new JPanel(new GridLayout(0, 1));
JPanel controls = new JPanel(new GridLayout(0, 1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
this.setLocation(m_centerX, m_centerY);
this.setSize(m_sizeX, m_sizeY);
// !! this.pack();
// !! this.setVisible(true);
}
public static void main(String[] args) {
new ServerConnect();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton) {
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try {
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try {
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
// !! this.setVisible(false);
// !! new ServerGUI(ip , s_port);
// !!
Window ownerWindow = SwingUtilities.getWindowAncestor(this);
ownerWindow.dispose();
}
}
// !!
public String getServerIp() {
return m_serverIP.getText();
}
// !!
public String getServerPort() {
return m_serverPort.getText();
}
}

Hope this another_Frame frm = new another_Frame();
frm.setVisible(true);
this.dispose();// this represent the fram to close

Related

DriverManager won't seem to connect DB

I'm working on a school assignment for a client/server application and can't seem to connect using the JDBC DriverManager. I have set up the driver for the schema I am using, it351, and seem to have everything in order but it never fires through the connection to tell me it's connected. Any words of wisdom from the crowd? I do show the driver in the services task pane and I have saved my password so I don't have to share it with the class. Thanks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.sql.*;
public class GUI extends JFrame
{
private JButton custButton;
private JButton prodButton;
private JButton exitButton;
private JPanel p1;
private JPanel p2;
private JPanel p3;
private JTextArea data;
// private String message = ""; // message from server
private String localhost; // host server for this application
public GUI()
{
super( "Database Data Retrieval" );
setSize(825, 800);
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container c = new Container();
add(c);
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
// create and add jpanels for components
p1 = new JPanel(); //(new FlowLayout(FlowLayout.CENTER));
c.add(p1);
p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
c.add(p2);
p3 = new JPanel(new FlowLayout(FlowLayout.CENTER));
c.add(p3);
data = new JTextArea(35, 70);
JScrollPane dataScroll = new JScrollPane(data);
dataScroll.setPreferredSize(null);
p1.add(data);
p1.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
data.setBorder(BorderFactory.createLineBorder(Color.black));
data.setVisible(true);
// create buttons
p2.setBorder(BorderFactory.createTitledBorder( null, "Database Controls"));
custButton = new JButton( "Retrieve Customer Data");
p2.add (custButton);
p2.add(Box.createRigidArea(new Dimension(50,0)));
prodButton = new JButton( "Retrieve Product Data" );
p2.add(prodButton);
p2.add(Box.createVerticalGlue());
p2.add(Box.createHorizontalGlue());
exitButton = new JButton (" Exit ");
p3.add(exitButton);
p3.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));
// register events for buttons
ButtonHandler handler = new ButtonHandler();
custButton.addActionListener( handler );
prodButton.addActionListener( handler );
exitButton.addActionListener( handler );
}
private void displayMessage( final String messageToDisplay )
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run() // updates displayArea
{
data.append( messageToDisplay );
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
private void connect()
{
Connection conn = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/it351?zeroDateTimeBehavior=convertToNull", "root", ""); //Connect
displayMessage("******* Connection created successfully *******"); //informs user of connection
}
catch (Exception err)
{
}
}
private class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed( ActionEvent event )
{
if (event.getSource() == custButton)
{
displayMessage( "******* Attempting connection *******\n" );
connect();
}
if (event.getSource() == prodButton)
{
}
if (event.getSource() == exitButton)
{
System.exit(0);
}
}// end of actionperformed
}// end of buttonhandler
}// end of GUI class

Form that has either a Comic Book object or a Novel object

Sorry if I'm double positing but I totally suck at Java.
I am trying to make my form have the ability to change dynamically if you select a radio button. The functions save, delete, new will remain the same but the contents of the body e.g. the UPC will change to ISBN of the novel and the other fields.
Is there a way to when you press Novel to load the items from Novel to replace Comic book items?
I tried to separate but I've hit a block and with my limited skills unsure what to do.
I just want it to be able to change it so that it works.
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.MenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
public class FormFictionCatelogue extends JFrame implements ActionListener {
// Constants
// =========
private final String FORM_TITLE = "Fiction Adiction Catelogue";
private final int X_LOC = 400;
private final int Y_LOC = 80;
private final int WIDTH = 600;
private final int HEIGHT = 450;
private String gradeCode;
//final static String filename = "data/comicBookData.txt";
private JButton firstPageButton;
private JButton backPageButton;
private JButton forwardPageButton;
private JButton lastPageButton;
private JRadioButton comicBookRadioButton;
private JRadioButton novelRadioButton;
private final String FIRSTPAGE_BUTTON_TEXT = "|<";
private final String BACKPAGE_BUTTON_TEXT = "<";
private final String FORWARDPAGE_BUTTON_TEXT = ">";
private final String LASTPAGE_BUTTON_TEXT = ">|";
private final String COMICBOOK_BUTTON_TEXT = "Comic";
private final String NOVEL_BUTTON_TEXT = "Novel";
private final String SAVE_BUTTON_TEXT = "Save";
private final String EXIT_BUTTON_TEXT = "Exit";
private final String CLEAR_BUTTON_TEXT = "Clear";
private final String FIND_BUTTON_TEXT = "Find";
private final String DELETE_BUTTON_TEXT = "Delete";
private final String ADDPAGE_BUTTON_TEXT = "New";
// Attributes
private JTextField upcTextField;
private JTextField isbnTextField;
private JTextField titleTextField;
private JTextField issueNumTextField;
private JTextField bookNumTextField;
private JTextField writerTextField;
private JTextField authorTextField;
private JTextField artistTextField;
private JTextField publisherTextField;
private JTextField seriesTextField;
private JTextField otherBooksTextField;
private JTextField gradeCodeTextField;
private JTextField charactersTextField;
private JButton saveButton;
private JButton deleteButton;
private JButton findButton;
private JButton clearButton;
private JButton exitButton;
private JButton addPageButton;
FictionCatelogue fc;
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) {
try {
FormFictionCatelogue form = new FormFictionCatelogue();
form.fc = new FictionCatelogue();
form.setVisible(true);
//comicBook selected by default
form.populatefields(form.fc.returnComic(0));
//if novel is selected change fields to novel and populate
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
/**
*
*/
public FormFictionCatelogue() {
// Set form properties
// ===================
setTitle(FORM_TITLE);
setSize(WIDTH, HEIGHT);
setLocation(X_LOC, Y_LOC);
// Create and set components
// -------------------------
// Create panels to hold components
JPanel menuBarPanel = new JPanel();
JPanel fieldsPanel = new JPanel();
JPanel buttonsPanel = new JPanel();
JPanel navigationPanel = new JPanel();
//JPanel radioButtonsPanel = new JPanel();
ButtonGroup bG = new ButtonGroup();
// Set the layout of the panels
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
// Menu
JMenuBar menubar = new JMenuBar();
ImageIcon icon = new ImageIcon("exit.png");
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenu about = new JMenu("About");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit", icon);
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JMenuItem eMenuItem1 = new JMenuItem("Reports", icon);
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Reports are located here");
eMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
//calls reports
//System.exit(0);
}
});
file.add(eMenuItem);
about.add(eMenuItem1);
menubar.add(file);
menubar.add(about);
setJMenuBar(menubar);
setTitle("Menu");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//if comic is selected
ComicBookFields(fieldsPanel);
//else
//NovelFields(fieldsPanel);
// Buttons
comicBookRadioButton = new JRadioButton(COMICBOOK_BUTTON_TEXT);
novelRadioButton = new JRadioButton(NOVEL_BUTTON_TEXT);
bG.add(comicBookRadioButton);
bG.add(novelRadioButton);
this.setLayout(new FlowLayout());
this.add(comicBookRadioButton);
this.add(novelRadioButton);
comicBookRadioButton.setSelected(true);
bG.add(comicBookRadioButton);
bG.add(novelRadioButton);
addPageButton = new JButton(ADDPAGE_BUTTON_TEXT);
buttonsPanel.add(addPageButton);
saveButton = new JButton(SAVE_BUTTON_TEXT);
buttonsPanel.add(saveButton);
clearButton = new JButton(CLEAR_BUTTON_TEXT);
buttonsPanel.add(clearButton);
deleteButton = new JButton(DELETE_BUTTON_TEXT);
buttonsPanel.add(deleteButton);
findButton = new JButton(FIND_BUTTON_TEXT);
buttonsPanel.add(findButton);
exitButton = new JButton(EXIT_BUTTON_TEXT);
buttonsPanel.add(exitButton);
firstPageButton = new JButton(FIRSTPAGE_BUTTON_TEXT);
navigationPanel.add(firstPageButton);
backPageButton = new JButton(BACKPAGE_BUTTON_TEXT);
navigationPanel.add(backPageButton);
forwardPageButton = new JButton(FORWARDPAGE_BUTTON_TEXT);
navigationPanel.add(forwardPageButton);
lastPageButton = new JButton(LASTPAGE_BUTTON_TEXT);
navigationPanel.add(lastPageButton);
// Get the container holding the components of this class
Container con = getContentPane();
// Set layout of this class
con.setLayout(new BorderLayout());
con.setLayout( new FlowLayout());
// Add the fieldsPanel and buttonsPanel to this class.
// con.add(menuBarPanel, BorderLayout);
con.add(fieldsPanel, BorderLayout.CENTER);
con.add(buttonsPanel, BorderLayout.LINE_END);
con.add(navigationPanel, BorderLayout.SOUTH);
//con.add(radioButtonsPanel, BorderLayout.PAGE_START);
// Register listeners
// ==================
// Register action listeners on buttons
saveButton.addActionListener(this);
clearButton.addActionListener(this);
deleteButton.addActionListener(this);
findButton.addActionListener(this);
exitButton.addActionListener(this);
firstPageButton.addActionListener(this);
backPageButton.addActionListener(this);
forwardPageButton.addActionListener(this);
lastPageButton.addActionListener(this);
addPageButton.addActionListener(this);
comicBookRadioButton.addActionListener(this);
novelRadioButton.addActionListener(this);
// Exit program when window is closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void Radiobutton (){
this.add(comicBookRadioButton);
this.add(novelRadioButton);
comicBookRadioButton.setSelected(true);
this.setVisible(true);
}
// Populate the fields at the start of the application
public void populatefields(ComicBook cb) {
String gradecode;
// radio button selection = comic do this
if (cb != null) {
upcTextField.setText(cb.getUpc());
titleTextField.setText(cb.getTitle());
issueNumTextField.setText(Integer.toString(cb.getIssuenumber()));
writerTextField.setText(cb.getWriter());
artistTextField.setText(cb.getArtist());
publisherTextField.setText(cb.getPublisher());
gradecode = cb.getGradeCode();
gradeCodeTextField.setText(cb.determineCondition(gradecode));
charactersTextField.setText(cb.getCharacters());
}
//radio button selection = novel do this
// Exit program when window is closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
/**
*
*/
public void actionPerformed(ActionEvent ae) {
try {
if(ae.getActionCommand().equals(COMICBOOK_BUTTON_TEXT)){
//FormFictionCatelogue form = new FormFictionCatelogue();
//form.populatefields(form.fc.returnObject(0));
//ComicBookFields(fieldsPanel);
populatefields(fc.returnComic(0));
} else if (ae.getActionCommand().equals(NOVEL_BUTTON_TEXT)) {
} else if (ae.getActionCommand().equals(SAVE_BUTTON_TEXT)) {
save();
} else if (ae.getActionCommand().equals(CLEAR_BUTTON_TEXT)) {
clear();
} else if (ae.getActionCommand().equals(ADDPAGE_BUTTON_TEXT)) {
add();
} else if (ae.getActionCommand().equals(DELETE_BUTTON_TEXT)) {
delete();
} else if (ae.getActionCommand().equals(FIND_BUTTON_TEXT)) {
find();
} else if (ae.getActionCommand().equals(EXIT_BUTTON_TEXT)) {
exit();
} else if (ae.getActionCommand().equals(FIRSTPAGE_BUTTON_TEXT)) {
// first record
populatefields(fc.firstRecord());
} else if (ae.getActionCommand().equals(FORWARDPAGE_BUTTON_TEXT)) {
// next record
populatefields(fc.nextRecord());
} else if (ae.getActionCommand().equals(BACKPAGE_BUTTON_TEXT)) {
// previous record
populatefields(fc.previousRecord());
} else if (ae.getActionCommand().equals(LASTPAGE_BUTTON_TEXT)) {
// last record
populatefields(fc.lastRecord());
} else {
throw new Exception("Unknown event!");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error!",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
void clear() {
upcTextField.setText("");
titleTextField.setText("");
issueNumTextField.setText("");
writerTextField.setText("");
artistTextField.setText("");
gradeCodeTextField.setText("");
publisherTextField.setText("");
charactersTextField.setText("");
}
private void exit() {
System.exit(0);
}
void add() {
try{
clear();
ComicBook cb = new ComicBook();
fc.add(cb);
fc.lastRecord();
} catch (Exception e){
e.printStackTrace();
}
}
void save() throws Exception {
// if radio button = comic do this
ComicBook cb = new ComicBook();
String condition;
if (upcTextField.getText().length() == 16) {
//searches if there is another record if()
cb.setUpc(upcTextField.getText());
} else {
throw new Exception("Upc is not at required length ");
}
cb.setTitle(titleTextField.getText());
cb.setIssuenumber(Integer.parseInt(issueNumTextField.getText()));
cb.setWriter(writerTextField.getText());
cb.setArtist(artistTextField.getText());
cb.setPublisher(publisherTextField.getText());
condition = cb.determineString(gradeCodeTextField.getText());
if (condition.equals("Wrong Input")) {
throw new Exception("Grade code is not valid");
} else {
cb.setGradeCode(condition);
}
cb.setCharacters(charactersTextField.getText());
fc.save(cb);
// if radio button = novels do this
}
private void delete() throws Exception {
fc.delete();
populatefields(fc.getCurrentRecord());
}
private void find() {
// from
// http://www.roseindia.net/java/example/java/swing/ShowInputDialog.shtml
String str = JOptionPane.showInputDialog(null, "Enter some text : ",
"Comic Book Search", 1);
if (str != null) {
ComicBook cb = new ComicBook();
cb = fc.search(str);
if (cb != null) {
populatefields(cb);
} else {
JOptionPane.showMessageDialog(null, "No comic books found ",
"Comic Book Search", 1);
}
}
}
public JPanel ComicBookFields(JPanel fieldsPanel) {
// Create components and add to panels for ComicBook
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
fieldsPanel.setLayout(fieldsPanelLayout);
fieldsPanel.add(new JLabel("UPC: "));
upcTextField = new JTextField(20);
fieldsPanel.add(upcTextField);
fieldsPanel.add(new JLabel("Title: "));
titleTextField = new JTextField(20);
fieldsPanel.add(titleTextField);
fieldsPanel.add(new JLabel("Issue Number: "));
issueNumTextField = new JTextField(20);
fieldsPanel.add(issueNumTextField);
fieldsPanel.add(new JLabel("Writer: "));
writerTextField = new JTextField(20);
fieldsPanel.add(writerTextField);
fieldsPanel.add(new JLabel("Artist: "));
artistTextField = new JTextField(20);
fieldsPanel.add(artistTextField);
fieldsPanel.add(new JLabel("Publisher: "));
publisherTextField = new JTextField(20);
fieldsPanel.add(publisherTextField);
fieldsPanel.add(new JLabel("Grade Code: "));
gradeCodeTextField = new JTextField(20);
fieldsPanel.add(gradeCodeTextField);
fieldsPanel.add(new JLabel("Characters"));
charactersTextField = new JTextField(20);
fieldsPanel.add(charactersTextField);
return fieldsPanel;
}
public JPanel NovelFields(JPanel fieldsPanel) {
// Create components and add to panels for ComicBook
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
fieldsPanel.setLayout(fieldsPanelLayout);
fieldsPanel.add(new JLabel("ISBN: "));
isbnTextField = new JTextField(20);
fieldsPanel.add(isbnTextField);
fieldsPanel.add(new JLabel("Title: "));
titleTextField = new JTextField(20);
fieldsPanel.add(titleTextField);
fieldsPanel.add(new JLabel("Book Number: "));
bookNumTextField = new JTextField(20);
fieldsPanel.add(bookNumTextField);
fieldsPanel.add(new JLabel("Author: "));
authorTextField = new JTextField(20);
fieldsPanel.add(authorTextField);
fieldsPanel.add(new JLabel("Publisher: "));
publisherTextField = new JTextField(20);
fieldsPanel.add(publisherTextField);
fieldsPanel.add(new JLabel("Series: "));
seriesTextField = new JTextField(20);
fieldsPanel.add(seriesTextField);
fieldsPanel.add(new JLabel("Other Books"));
otherBooksTextField = new JTextField(20);
fieldsPanel.add(otherBooksTextField);
return fieldsPanel;
}
}
To swap forms you can use a CardLayout.
Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
The example from the tutorial switches when you make a selection from a combo box. In your case you would change the panel when you click on the radio button. So you might also want to read the section from the tutorial on How to Use Buttons.
Otherwise you can switch JPanels on JRadioButton selection like this:
You've got a JPanel called displayPanel which contains the ComicPanel by default, if you select the Novel RadioButton the displayPanel gets cleared and the NovelPanel will be added.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class AddNovelOrComicPanel extends JPanel implements ActionListener {
private JPanel selectPanel;
private JPanel displayPanel;
private JPanel buttonPanel;
private JRadioButton comic;
private JRadioButton novel;
// we need this ButtonGroup to take care about unselecting the former selected JRadioButton
ButtonGroup radioButtons;
public AddNovelOrComicPanel() {
this.setLayout(new BorderLayout());
initComponents();
this.add(selectPanel, BorderLayout.NORTH);
this.add(displayPanel, BorderLayout.CENTER);
}
/**
* Initializes all Components
*/
private void initComponents() {
selectPanel = new JPanel(new GridLayout(1, 2));
comic = new JRadioButton("Comic");
comic.setSelected(true);
comic.addActionListener(this);
novel = new JRadioButton("Novel");
novel.addActionListener(this);
radioButtons = new ButtonGroup();
radioButtons.add(comic);
radioButtons.add(novel);
selectPanel.add(comic);
selectPanel.add(novel);
displayPanel = new JPanel();
displayPanel.add(new ComicPanel());
}
#Override
public void actionPerformed(ActionEvent e) {
// if comic is selected show the ComicPanel in the displayPanel
if(e.getSource().equals(comic)) {
displayPanel.removeAll();
displayPanel.add(new ComicPanel());
}
// if novel is selected show the NovelPanel in the displayPanel
if(e.getSource().equals(novel)) {
displayPanel.removeAll();
displayPanel.add(new NovelPanel());
}
// revalidate all to show the changes
revalidate();
}
}
/**
* The NovelPanel class
* it contains all the Items you need to register a new Novel
*/
class NovelPanel extends JPanel {
public NovelPanel() {
this.add(new JLabel("Add your Novel components here"));
}
}
/**
* The ComicPanel class
*/
class ComicPanel extends JPanel {
public ComicPanel() {
this.add(new JLabel("Add your Comic components here"));
}
}
So it is your choice what you want to do. Possible is nearly everything ;)
Patrick

Which timer to use for GUI in Java

I have been trying to find the best timer to use for the following code (note this is a simplified version of my overall program). My hope is to run a method after 3 seconds.
The problem is with the actionPerformed, checkBlankLogin, and resetLoginBlank and putting a timer to delay resetLoginBlank from happening 3 seconds after checkBlankLogin has happened. But I want all methods in the class Outerframe to continuously run. So checkBlankLogin will keep checking if its blank until the person inputs the information for a "Valid Input" and the Login innerframe will close. But I don't know how to do that... Any help there also?
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import java.io.*;
import java.io.File;
import java.util.*;
import java.io.FileNotFoundException;
class OuterFrame extends JFrame implements ActionListener
{
Container pane; // container
JDesktopPane outframe; // outer frame
JInternalFrame login; // login frame
//pieces of login frame
JLabel loginLBLtitle;
JPanel loginPanel;
JLabel loginLBLname;
JLabel loginBlankName;
JLabel loginLBLpass;
JLabel loginBlankPass;
JTextField loginTXT;
JPasswordField loginPASS;
JButton loginBUT;
JInternalFrame apple;
OuterFrame()
{
//set up for Outer Frame
super("Application");
setSize(450,240);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outframe = new JDesktopPane();
outframe.setBackground(Color.BLUE);
//set up for Container
pane = getContentPane();
setContentPane(pane);
pane.add(outframe);
//Login Inner Frame
login = new JInternalFrame();
login.setSize(400,200);
login.setLocation(20,20);
login.setTitle("Member Login");
loginLBLtitle = new JLabel("Sign in with netid and your password.");
Font loginFontbody = new Font("SansSerif", Font.PLAIN, 12);
Font loginFonthead = new Font("SansSerif", Font.BOLD, 13);
loginLBLtitle.setFont(loginFonthead);
loginLBLname=new JLabel("User Name:");
loginLBLname.setFont(loginFontbody);
loginLBLpass=new JLabel("Password: ");
loginLBLpass.setFont(loginFontbody);
loginBUT=new JButton("Login");
loginBUT.setFont(loginFontbody);
loginBUT.addActionListener(this);
loginTXT=new JTextField(20);
loginPASS=new JPasswordField(20);
loginBlankName=new JLabel("");
loginBlankPass=new JLabel("");
loginPanel=new JPanel();
loginPanel.add(loginLBLtitle);
loginPanel.add(loginLBLname);
loginPanel.add(loginTXT);
loginPanel.add(loginBlankName);
loginPanel.add(loginLBLpass);
loginPanel.add(loginPASS);
loginPanel.add(loginBlankPass);
loginPanel.add(loginBUT);
//panel.add(lblmess);
login.add(loginPanel);
login.setVisible(true);
//Add Login to Outer Frame
outframe.add(login);
outframe.setSelectedFrame(login);
pane.add(outframe, BorderLayout.CENTER);
setVisible(true);
loginTXT.requestFocus();
}
public void actionPerformed(ActionEvent e)
{
//problem area
if(e.getSource()==loginBUT)
{
String uname=loginTXT.getText();
String passw=new String(loginPASS.getPassword());
int i=0;
while(i!=5)
{
if(checkBlankLogin(uname,passw,loginBlankName,loginBlankPass))
{
resetLoginBlank(loginBlankName,loginBlankPass);
}
else
{
if(!validateUser("accounts.txt",uname,passw,loginLBLtitle))
{
}
}
}
}
public void resetLoginBlank(JLabel loginBlankName, JLabel loginBlankPass)
{
loginBlankName.setText("");
loginBlankPass.setText("");
}
public void resetLoginTitle(JLabel loginBlankTitle)
{
loginBlankTitle.setText("Sign in with netid and your password.");
loginBlankTitle.setForeground(Color.BLACK);
}
public boolean checkBlankLogin(String name, String passw, JLabel loginBlankName, JLabel loginBlankPass)
{
boolean isBlank=false;
if(name.length()<1)
{
loginBlankMess("User name is required.",loginBlankName);
isBlank=true;
}
if(passw.length()<1)
{
loginBlankMess("Password is required.",loginBlankPass);
isBlank=true;
}
return isBlank;
}
public void loginBlankMess(String mess, JLabel lbl)
{
lbl.setText(mess);
lbl.setForeground(Color.RED);
}
public boolean validateUser(String filename, String name, String password, JLabel title)
{
boolean valid = false;
try
{
File file = new File(filename);
Scanner scanner = new Scanner(file);
ArrayList<String> fileInfo = new ArrayList<String>();
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
fileInfo.add(line);
}
String fullLogin = name + " " + password;
if(fileInfo.contains(fullLogin))
{
//loginBlankMess("Valid login",namemess);
valid=true;
}
if(!valid)
{
loginBlankMess("Please enter valid netid and password.", title);
resetLoginTitle(title);
}
}
catch(Exception ie)
{
System.exit(1);
}
return valid;
}
}
public class TheProgram
{
public static void main(String[] args)
{
new OuterFrame();
}
}`
I would check out the following resource (assuming you using Swing for your UI):
How to Use Swing Timers (Oracle)
Swing timers are the easiest in your case. You make your class implement ActionListener, and create a timer object. The timer will call the actionPerformed method when it expires.
import javax.swing.Timer;
class OuterFrame extends JFrame implements ActionListener{
Timer timer = null;
public void actionPerformed(ActionEvent e) {
if(e.getSource()==loginBUT){
//If the action came from the login button
if (checkBlankLogin()){
timer = new Timer(3000, this);
timer.setRepeats(false);
timer.setInitialDelay(3000);
timer.start();
} else if (timer != null){
timer.stop();
}
}else if(e.getSource()==timer){
//If the action came from the timer
resetLoginBlank(namemess,passwmess));
}
}
}

GUI is frozen whent he ftp site is not connected

Here is my main class:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.io.*;
import java.lang.Process.*;
public class FTP {
public static void main (String []args)
{
Runnable runner = new Runnable(){
public void run()
{
LookAndFeel nimbusLook = new LookAndFeel();
nimbusLook.NimbusLookAndFeel();
JFrame frame = new JFrame("BNA FTP Diagnose");
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(540, 420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(150, 150);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
final JMenuItem exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
JMenu helpMenu = new JMenu("Help");
menuBar.add(new JPanel());
menuBar.add(helpMenu);
final JMenuItem aboutMenuItem = new JMenuItem("About");
helpMenu.add(aboutMenuItem);
JPanel titlePanel = new JPanel(new BorderLayout());
frame.add(titlePanel, BorderLayout.NORTH);
JLabel titleLabel = new JLabel("FTP Diagnose", JLabel.CENTER);
titleLabel.setFont(new Font(null, Font.BOLD, 14));
titleLabel.setForeground(Color.BLUE);
titlePanel.add(titleLabel);
JPanel gridPanel = new JPanel(new GridLayout(1, 1));
frame.add(gridPanel);
JPanel vendorPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
gridPanel.add(vendorPanel);
final String vendor [] = {"LLesiant" ,"WK-CCH", "Proquest", "Notes", "Research Institute of America", "Thomson",
"BNAI PDF Processing", " TM Portfolios to Indexing", "Postscript to PRODLOGIN1", "www.firstdoor.net", "psp.bna.com", "WEST", "LexisNexis", "McArdle Printing Company",
"Breaking News Email", "Ex Libris", "Pandora", "Bloomberg Law", "Acquire Media Site 1", "Acquire Media Site 2", "Quicksite", "QA Quicksite"};
final JComboBox vendorList = new JComboBox(vendor);
vendorPanel.add(vendorList);
JPanel diagnoseButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
gridPanel.add(diagnoseButtonPanel);
final JButton diagnoseButton = new JButton("Diagnose");
diagnoseButtonPanel.add(diagnoseButton);
JPanel centerPanel = new JPanel(new BorderLayout());
frame.add(centerPanel, BorderLayout.SOUTH);
JPanel commandPanel = new JPanel(new GridLayout(1, 0));
centerPanel.add(commandPanel);
final JTextArea commandResultArea = new JTextArea(7, 0);
JScrollPane scroll = new JScrollPane(commandResultArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
commandPanel.add(scroll);
commandResultArea.setEditable(false);
ActionListener buttonListener = new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
int selectedIndex = vendorList.getSelectedIndex();
String llesiant = "ftp.llesiant.com";
String wkCCH = "FTP1.cch.com";
String proquest = "ftp.proquest.com";
String notes = "notes5.bna.com";
//String lineThree = null;
CommandClass readCommand = new CommandClass();
if (selectedIndex == 0)
{
commandResultArea.setText(readCommand.getCommand(llesiant)); //these return strings
}
else if (selectedIndex == 1)
{
commandResultArea.setText(readCommand.getCommand(wkCCH));
}
else if (selectedIndex == 2)
{
commandResultArea.setText(readCommand.getCommand(proquest));
}
else if (selectedIndex == 3)
{
commandResultArea.setText(readCommand.getCommand(notes));
}
}
};
diagnoseButton.addActionListener(buttonListener);
ActionListener exitListener = new ActionListener (){
public void actionPerformed(ActionEvent el)
{
if (el.getSource()== exitMenuItem)
{
JOptionPane.showMessageDialog(null, "FTP Program will exit now!");
System.exit(0);
}
}
};
exitMenuItem.addActionListener(exitListener);
ActionListener aboutListener = new ActionListener()
{
public void actionPerformed(ActionEvent al)
{
if (al.getSource()== aboutMenuItem)
{
JOptionPane.showMessageDialog(null, "This Software was made for Editors to. \nDiagnose BNA Bloomberg client FTP site.");
}
}
};
aboutMenuItem.addActionListener(aboutListener);
}
};
EventQueue.invokeLater(runner);
}
}
Here is my Look and feel class:
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class LookAndFeel {
public void NimbusLookAndFeel()
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
}
}
Here is my CommandClass:
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class CommandClass {
public String getCommand(String ftpSite){
String command = "ftp ";
StringBuffer output = new StringBuffer();
try{
Process p = Runtime.getRuntime().exec(command +ftpSite);
InputStreamReader ir = new InputStreamReader (p.getInputStream());
int outputChar = 0;
while((outputChar = ir.read()) != -1){
output.append((char)outputChar);
if(!ir.ready()){ // If the next read is not guarenteed, come out of loop.
break;
}
}
ir.close();
JOptionPane.showMessageDialog(null, "FTP is connected");
}catch (IOException e){
e.printStackTrace();
}
return output.toString();
}
}
I have this FTP GUI which suppose to connect to an FTP site and return the status. If it's connected it shows the connection prompt.
I got the JTextArea to show the message when the FTP connection is established, but when it's not connected to the ftp site such as my 4th ftp site which is notes5.bna.com it freezes the program. Also a small problem is if you have the program FTP to a site like this "shlfsdklaflkhasdlhfas". It returns the ftp site is not found only after the JOptionPane shows that FTP is connected. I am not sure what's wrong with it.
The reason that notes5.bna.com is freezing is that the site is not responding to FTP connection requests. As you are simply using Runtime#exec to make the connection, this will block indefinitely for a response. Consider using a 3rd party FTP client such as Apache FTPClient which allows you to specify a connection timeout.
A related issue is that some sites are requesting a username & password for access. Again FTPClient allows you to provide login details.
Last but not least, don't let heavyweight non-UI tasks freeze your Swing application. Swing has mechanisms to deal with these such as SwingWorker objects.
Related Swingworker Network Example

Changing the active "card" in a Java card layout, from another class

I'm trying to build a small inventory application in Java, that switches views (or pages) based on the card layout. For the standard change the user will use the menu at the top of the app, and that works fine.
But, one one of my screens the user will enter an item ID number to check. If that ID number is not found in the database, the app should switch to the New Item page. This is where I'm at a loss. I've tried to change the currently viewed card but nothing seems to be getting it.
Forgive me if this is a basic question (as well as poorly written Java :) ), I'm teaching myself Java as I write this app. Attached I'm adding part of the main class (InventoryTrackingSystem) and the GUI class (the one that is trying to change the view).
/***** The MAIN class **********/
package inventorytrackingsystem;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.rmi.*;
public class InventoryTrackingSystem implements ItemListener {
JPanel mainPanel;
JFrame frame;
JPanel cards = new JPanel(new CardLayout());; //a panel that uses CardLayout
final static String MAINPANEL = "Main";
final static String CHECKITEMSPANEL = "Check Items";
final static String NEWITEMPANEL = "New Item";
final static String CHECKOUTITEMPANEL = "Check Out Item";
final static String ITEMINFOPANEL = "Item Information";
final static String LISTALLITEMSPANEL = "List All Items";
JPanel comboBoxPane;
private JComboBox cb;
static String comboBoxItems[] = {MAINPANEL,CHECKITEMSPANEL,NEWITEMPANEL,CHECKOUTITEMPANEL,ITEMINFOPANEL,LISTALLITEMSPANEL};
public static void main(String[] args) {
InventoryTrackingSystem ITS = new InventoryTrackingSystem();
/* Use an appropriate Look and Feel */
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
// javax.swing.SwingUtilities.invokeLater(new Runnable() {
// public void run() {
ITS.createAndShowGUI();
// }
// });
}
public void addComponentToPane(Container pane){
//Put the JComboBox in a JPanel to get a nicer look.
comboBoxPane = new JPanel(); //use FlowLayout
cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
cb.setVisible(false);
//Create the "cards".
JPanel main = new guiBuilder().buildGui("main");
JPanel checkItems = new guiBuilder().buildGui("checkItems");
JPanel newItems = new guiBuilder().buildGui("newItems");
JPanel checkOutItems = new guiBuilder().buildGui("checkOutItems");
JPanel itemInfo = new guiBuilder().buildGui("itemInfo");
JPanel listAllItems = new guiBuilder().buildGui("listAllItems");
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(main, MAINPANEL);
cards.add(checkItems, CHECKITEMSPANEL);
cards.add(newItems, NEWITEMPANEL);
cards.add(checkOutItems, CHECKOUTITEMPANEL);
cards.add(itemInfo, ITEMINFOPANEL);
cards.add(listAllItems, LISTALLITEMSPANEL);
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("Inventory Tracking System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
Menu m1 = new Menu("Options");
MenuItem mi1_0 = new MenuItem("Main Page");
mi1_0.setActionCommand("main");
mi1_0.addActionListener(new menuListener());
MenuItem mi1_1 = new MenuItem("Check Item");
mi1_1.setActionCommand("checkItem");
mi1_1.addActionListener(new menuListener());
MenuItem mi1_2 = new MenuItem("Add New Item");
mi1_2.setActionCommand("addItem");
mi1_2.addActionListener(new menuListener());
MenuItem mi1_3 = new MenuItem("List All Items");
mi1_3.setActionCommand("listAllItems");
mi1_3.addActionListener(new menuListener());
MenuItem mi1_4 = new MenuItem("Check Out Item");
mi1_4.setActionCommand("checkOutItem");
mi1_4.addActionListener(new menuListener());
MenuItem mi1_5 = new MenuItem("Exit");
mi1_5.setActionCommand("exit");
mi1_5.addActionListener(new menuListener());
Menu m2 = new Menu("Help");
MenuItem mi2_0 = new MenuItem("About");
mi2_0.setActionCommand("about");
mi2_0.addActionListener(new menuListener());
m1.add(mi1_0);
m1.add(mi1_1);
m1.add(mi1_2);
m1.add(mi1_3);
m1.add(mi1_4);
m1.add(mi1_5);
m2.add(mi2_0);
MenuBar mb = new MenuBar();
frame.setMenuBar(mb);
mb.add(m1);
mb.add(m2);
//Create and set up the content pane.
//InventoryTrackingSystem setGUI = new InventoryTrackingSystem();
addComponentToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setSize(780, 830);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
public void windowClosed(WindowEvent we){
System.exit(0);
}
});
}
class menuListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
String thisAction=ev.getActionCommand();
if(thisAction.equals("main")){
cb.setSelectedItem(MAINPANEL);
}else if(thisAction.equals("checkItem")){
//change GUI
cb.setSelectedItem(CHECKITEMSPANEL);
}else if(thisAction.equals("addItem")){
//change GUI
cb.setSelectedItem(NEWITEMPANEL);
}else if(thisAction.equals("checkOutItem")){
//change GUI
cb.setSelectedItem(CHECKOUTITEMPANEL);
}else if(thisAction.equals("listAllItems")){
//change GUI
cb.setSelectedItem(LISTALLITEMSPANEL);
}else if(thisAction.equals("exit")){
System.exit(0);
}else if(thisAction.equals("about")){
JOptionPane.showMessageDialog(frame, "About This App");
}
}
}
public void swapView(String s){
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, s);
}
}
/***** The GUI class **********/
package inventorytrackingsystem;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Image.*;
import java.awt.image.BufferedImage.*;
import javax.imageio.*;
import com.sun.jimi.core.*;
public class guiBuilder {
JLabel itemIdLabel;
JTextField itemID;
JButton checkIt;
JButton getSignature;
mySqlStuff sql=new mySqlStuff();
public JPanel buildGui(String guiType){
JPanel thisGUI;
if(guiType.equals("main")){
thisGUI=mainGUI();
}else if(guiType.equals("checkItems")){
thisGUI=checkItemsGUI();
}else if(guiType.equals("newItems")){
thisGUI=newItemsGUI();
}else if(guiType.equals("checkOutItems")){
thisGUI=checkOutItemsGUI();
}else if(guiType.equals("itemInfo")){
thisGUI=itemInfoGUI();
}else if(guiType.equals("listAllItems")){
thisGUI=listAllItemsGUI();
}else{
thisGUI=mainGUI();
}
return thisGUI;
} /* close buildGui() Method */
private JPanel mainGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
private JPanel checkItemsGUI(){
JPanel thisPanel = new JPanel();
JPanel itemSection=new JPanel();
JPanel exitSection=new JPanel();
itemIdLabel=new JLabel("Enter/Scan Item ID");
itemID=new JTextField(4);
itemID.addKeyListener(new myItemIdListener());
checkIt=new JButton("Check Item");
checkIt.addActionListener(new myItemCheckListener());
itemSection.add(itemIdLabel);
itemSection.add(itemID);
itemSection.add(checkIt);
JButton exitButton=new JButton("Exit");
exitButton.addActionListener(new exitButtonListener());
exitSection.add(exitButton);
thisPanel.add(itemSection);
thisPanel.add(exitSection);
return thisPanel;
}
private JPanel newItemsGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
private JPanel checkOutItemsGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
private JPanel itemInfoGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
private JPanel listAllItemsGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
class myItemIdListener implements KeyListener{
boolean keyGood=false;
public void keyPressed(KeyEvent keyEvent){
int keyCode=keyEvent.getKeyCode();
if((keyCode>=48 && keyCode<=57) || (keyCode>=96 && keyCode<=105)){
keyGood=true;
}
}
public void keyReleased(KeyEvent keyEvent){
int keyCode=keyEvent.getKeyCode();
if((keyCode>=48 && keyCode<=57) || (keyCode>=96 && keyCode<=105)){
printIt("Released",keyEvent);
}else if(keyCode==10){
checkIt.doClick();
}
}
public void keyTyped(KeyEvent keyEvent){
int keyCode=keyEvent.getKeyCode();
if((keyCode>=48 && keyCode<=57) || (keyCode>=96 && keyCode<=105)){
printIt("Typed",keyEvent);
}
}
private void printIt(String title,KeyEvent keyEvent){
int keyCode=keyEvent.getKeyCode();
String keyText=KeyEvent.getKeyText(keyCode);
String currentData;
if(title.equals("Pressed")){
keyGood=true;
}else if(title.equals("Released")){
System.out.println(title+ " -> "+keyCode+" / "+keyText);
}else if(title.equals("Typed")){
System.out.println(title+ " -> "+keyCode+" / "+keyText);
}
try{
String text=itemID.getText();
if(text.length()==4){
checkIt.doClick();
}else{
System.out.println("currentlLength: "+itemID.getText().length());
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
/**** THIS IS WHERE THE SWAP VIEW IS CALLED ****/
class myItemCheckListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
String itemNum=itemID.getText();
itemID.setText("");
System.out.println("Checking ID#: "+itemNum);
ArrayList checkData=new ArrayList(sql.checkInventoryData(itemNum));
if(checkData.get(0).toString().equals("[NULL]")){
System.out.println("New Item -> "+checkData.get(0).toString());
InventoryTrackingSystem ITS = new InventoryTrackingSystem();
ITS.swapView("NEWITEMPANEL");
}else{
System.out.println("Item Exists -> "+checkData.get(0).toString());
}
System.out.println(checkData);
}
}
class signaturePadButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
signaturePadStuff signature = new signaturePadStuff();
while(signature.imageFileMoved==false){
// wait for the signature to be collected and the image moved to the server.
}
System.out.println(signature.newFileName);
}
}
class exitButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
System.exit(0);
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getResource(path);
if(imgURL != null){
return new ImageIcon(imgURL, description);
}else{
System.err.println("Couldn't find file: " + path);
return null;
}
}
class submitItemButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
String errorMsg = "";
String[] formResults = new String[25];
}
}
class clearFormButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
return;
}
}
}
With this code in your actionPerformed method...
InventoryTrackingSystem ITS = new InventoryTrackingSystem();
ITS.swapView("NEWITEMPANEL");
...you are calling swapView on a new instance of InventoryTrackingSystem (which is not the one you created in main and for which the UI is showing on the screen).
-edited-
you need an instance of InventoryTrackingSystem in your action listener
you can for example store it in a member variable of myItemCheckListener like this:
class myItemCheckListener implements ActionListener{
private InventoryTrackingSystem its;
// constructor takes its instance as argument
public myItemCheckListener(InventoryTrackingSystem its){
// ...assigns it to the member variable
this.its = its;
}
public void actionPerformed(ActionEvent ev){
// call swapView on the correct instance of InventoryTrackingSystem
its.swapView()
}
}
Of course, since your action listener is created in guiBuilder.buildGui() / checkItemsGUI() you will need the ITS instance there, too.
BTW:
It is not really necessary to create new guiBuilder instances like this:
JPanel main = new guiBuilder().buildGui("main");
...
JPanel listAllItems = new guiBuilder().buildGui("listAllItems");
instead you could:
guiBuilder builder = new guiBuilder();
builder.buildGui("main");
builder.build("whatever");

Categories