Help closing a gui

Need some help
I want to pop up a gui made in JOptionPane when I close the editor gui. Basically I want to ask the user to confirm the closing because the file has not been saved.
I wrote the code but it is not working (you can find the code in question in the InnerDestroyer class)
What am I missing??
import javax.swing.JScrollPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.logging.*;
* MyEditor class
public class MyEditor extends JFrame implements ActionListener
     public static final int WIDTH=600;
     public static final int HEIGHT = 620;
     public static final int LINES = 30;
     public static final int CHAR_PER_LINE = 53;
     private JTextArea theText;
      * Constructror,  creating the Text Editor GUI
     public MyEditor()
          setSize(WIDTH,HEIGHT);
          setTitle("My Editor");
          Container contentPane = getContentPane();
          contentPane.setLayout(new BorderLayout());
          JPanel buttonPanel = new JPanel();
          buttonPanel.setBackground(Color.white);
          buttonPanel.setLayout(new FlowLayout());
          JButton loadUrl = new JButton("Load URL");
          loadUrl.addActionListener(this);
          buttonPanel.add(loadUrl);
          JButton loadButton = new JButton("Load");
          loadButton.addActionListener(this);
          buttonPanel.add(loadButton);
          JButton saveButton = new JButton("Save");
          saveButton.addActionListener(this);
          buttonPanel.add(saveButton);
          contentPane.add(buttonPanel, BorderLayout.SOUTH);
          JPanel textPanel = new JPanel();
          textPanel.setBackground(Color.black);
          theText = new JTextArea(LINES, CHAR_PER_LINE);
          theText.setBackground(Color.white);
          textPanel.add(theText);
          contentPane.add(textPanel, BorderLayout.NORTH);
          JTextField textField = new JTextField(20);
          contentPane.add(textField, BorderLayout.CENTER);
          JScrollPane scrolledText = new JScrollPane(theText);
          textPanel.add(scrolledText);
          contentPane.add(textPanel, BorderLayout.NORTH);
          JMenu menu = new JMenu("File");
          JMenuItem m;
          m= new JMenuItem("Clear Text");
          m.addActionListener(this);
          menu.add(m);
          m= new JMenuItem("Exit Editor");
          m.addActionListener(this);
          menu.add(m);
          JMenuBar mBar = new JMenuBar();
          mBar.add(menu);
          setJMenuBar(mBar);
     public void actionPerformed(ActionEvent e)
          String actionCommand = e.getActionCommand();
          if (actionCommand.equals("Load"))
               try
                    JFileChooser chooser = new JFileChooser();
                    int returnVal = chooser.showOpenDialog(this);
                    if(returnVal == JFileChooser.APPROVE_OPTION)
                         FileReader freader = new FileReader(chooser.getSelectedFile());
                         BufferedReader breader = new BufferedReader (freader);
                         theText.setText("");
                         String line;
                         while ((line= breader.readLine()) !=null)
                              theText.append(line + "\n");
                         breader.close();
               catch(FileNotFoundException g)
                    String error1= "Error opening the file ";
                    String error2 = "or the file was not found";
                    theText.setText(error1 +" " + error2);
               catch(IOException g)
                    theText.setText("Error rerading from file");
          if (actionCommand.equals("Load URL"))
               try
                    JFileChooser chooser = new JFileChooser();
                    int returnVal = chooser.showOpenDialog(this);
                    if(returnVal == JFileChooser.APPROVE_OPTION)
                         FileReader freader = new FileReader(chooser.getSelectedFile());
                         BufferedReader breader = new BufferedReader (freader);
                         theText.setText("");
                         String line;
                         while ((line= breader.readLine()) !=null)
                              theText.append(line + "\n");
                              breader.close();
                    catch(FileNotFoundException g)
                         String error1= "Error opening the file ";
                         String error2 = "or the file was not found";
                         theText.setText(error1 +" " + error2);
                    catch(IOException g)
                         theText.setText("Error rerading from file");
          else if  (actionCommand.equals("Save"))
               try
                    JFileChooser chooser = new JFileChooser();
                    ExampleFileFilter filter = new ExampleFileFilter();
                     filter.addExtension("txt");
                        filter.addExtension("html");
                        filter.setDescription("txt & html files");
                        chooser.setFileFilter(filter);
                    int returnVal = chooser.showSaveDialog(this);
                    if(returnVal == JFileChooser.APPROVE_OPTION)
                         FileWriter fwriter = new FileWriter(chooser.getSelectedFile());
                         BufferedWriter bwriter = new BufferedWriter (fwriter);
                         bwriter.write(theText.getText());
                         bwriter.close();
               catch(IOException io)
                    theText.setText("Error saving!");
          else if(actionCommand.equals("Exit Editor"))
               System.exit(1);
          else if(actionCommand.equals("Clear Text"))
               theText.setText("");
          else
               theText.setText("Error in editor interface");
public class InnerDestroyer extends WindowAdapter
     public void windowClosing(WindowEvent e)
          JOptionPane op =new JOptionPane();
          JLabel  jl = new JLabel("Document has not been saved");
          op.showMessageDialog( null, jl, "Warning!", JOptionPane.QUESTION_MESSAGE);
          op.setVisible(true);
      *//*Main class, making the editor Gui visible**/
     public static void main(String[] args)
          MyEditor guiEditor = new MyEditor();
            guiEditor.setVisible(true);
}

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame {
  JCheckBox jcb = new JCheckBox("Check Me, Check Me!!!!");
  public Test() {
    Container content = getContentPane();
    content.setLayout(new FlowLayout());
    content.add(jcb);
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
     if (jcb.isSelected()) System.exit(0);
     else if (JOptionPane.showConfirmDialog(null,
           "You forgot to check the box!\nAre you sure you want to exit",
           "DUMB",JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE)==
          JOptionPane.OK_OPTION) System.exit(0);
    setSize(200, 200);
    setVisible(true);
  public static void main(String[] args){
    new Test();
}If you have a question about this, look at it again. If you still have a question, search the forums.

Similar Messages

  • Hi, can anyone help me out with this, I need some help on designing GUI for e-learning coursewares. Some tutorials or some helpful sites will do.

    I need some help with the GUI design.

    Have you tried the line inputs on the back of your FirePod? If you update its firmware (not sure if you will need to or not), I seem to remember hearing that the FirePod can run without FW connection, i.e. stand alone. In this mode with the outs from your mixer into line ins 1-2 (2nd from left on the back) it should work fine. I say should because I have never tried. However, these are used for returns from an external effects unit. I assume here, and the important word is assume, that there are two so that they can be used as a stereo send or as a mono send. Worth a try! Let us know how it goes.
    Best, Fred

  • Closing one GUI and opening another?

    Hi guys,
    (I didnt really know which forum to post this in, so apologies in advance if this is the wrong one).
    I have created a login screen for a system, LoginScreen.java, which accepts a username and password and checks these on the server for validity. This all works fine.
    Once an account is accepted as valid I would like for the login screen to close, and the actual main GUI, Client.java, to open.
    Can anyone tell me the code for doing this? (closing one GUI and opening another).
    Please ask if you need more information on my code.
    Many thanks!

    You can make the Client.java as your main program then just call the LoginScreen.java.
    import javax.swing.*;
    public class Client extends JFrame {
    public static void main (String[] args) {                     
         Login log = new Login();
         log.show();     
    // Here you can put validation if the user is valid before displaying the main GUI
    // If valid user
         Client clt = new Client();
    clt.show();     
    // } else {
    // System.exit(0);
    public Client() {
         super("Client Java");
         setSize(400, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    class Login extends JFrame {
    public Login() {
         super("Login Java");
         setSize(200, 300);
    }

  • Plz help with me gui problem(arraylist)

    my program
    stocksymbol ------------------ stockname ------------------ enter
    (label) (textfield) (label) (textfield) (button)
    create a gui application using jframe and jpanel so that user can enter stock details(symbol,name) when user press "enter(button)" the text entered in the textfield should be add to an arraylist.
    when we close the window ,we have to print the items present in the arraylist....
    i have created all the components but iam getting difficult in display the arraylist when i close the window
    i have created these classes
    public class Stock {?}
    public class StockEntryFrame extends JFrame {
    // code to allow the frame to handle a window closing event ? when the window is closed,
    // the stock list should be printed. ?
    public class StockEntryPanel extends JPanel {
    public StockEntryPanel(ArrayList<Stock> stockList) {
    can u plz help me how to diplay the contents in arraylist

    MY PROGRAM IS LIKE THIS:::::::::
    STOCKNAME-----------
    STOCKSYMBOL---------
    STOCK PRICE--------
    ENTER(BUTTON)
    WHEN USER ENTERS HIS INPUT IN THE TEXT BOX AND PRESS ENTER, THEN THE TEXT PRESENT IN THE TEXTBOX SHOULD BE ENTERED INTO AN ARRAYLIST.
    THIS IS A GUI PROGRAM......
    WHEN WE CLOSE THE FRAME ,WE HAVE TO DISPLAY THE CONTENTS PRESENT IN THE ARRAYLIST
    I HAVE CREATED THE PROGRAM LIKE THIS
    CLASS STOCKENTRYPANEL EXTENDS JPANEL
    //ADDING ALL THE COMPONETNS TO THE PANEL
    CLASS STOCKENTRY FRAME EXTENDS JFRAME
    //ADDING PANEL TO THE FRAME
    //I NEED THE CODE HERE
    WHEN WE CLOSE THE WINDOW THE ARRAYLIST DETAILS SHOULD BE PRINTED
    }

  • Help in understanding GUI's!!!

    Hi everyone, I'm new to this type of forum, but I figured it can't hurt to ask for help wherever I can find it. I'm in a Java II class right now, and I'm having a hard time understanding how to build a GUI. I created the programs provided in the book, but I keep getting an error upon compiling, "unreachable statement". I have included my code, I'm not sure how to paste it properly, so I'm sorry if it's hard to read. Please let me know if anyone can help me out here. I'm not sure how much it matters, but the Java Machine we are using is 1.4.2... Thanks for any help!!!
    **The first part is this: Rooms.java**
         Chapter 5:     Reserve a Party Room
         Programmer:     Sabrina M. Liberski
         Date:          December 16, 2007
         Filename:     Rooms.java
         Purpose:     This is an external class called by the Reservations.java program.
                        Its constructor method receives the number of nonsmoking and smoking rooms
                        and then creates an array of empty rooms.  The bookRoom() method accepts a
                        boolean value and returns a room number.
    public class Rooms
         //declare class variables
         int numSmoking;
         int numNonSmoking;
         boolean occupied[];
         public Rooms(int non, int sm)
              //construct an array of boolean values equal to the total number of rooms
              occupied = new boolean[sm+non];
              for(int i=0; i<(sm+non); i++)
                   occupied[i] = false; //set each occupied room to false or empty
              //initialize the number of smoking and nonsmoking rooms
              numSmoking = sm;
              numNonSmoking = non;
         public int bookRoom(boolean smoking)
              int begin, end, roomNumber=0;
              if(!smoking)
                   begin = 0;
                   end = numNonSmoking;
              else
                   begin = numNonSmoking;
                   end = numSmoking+numNonSmoking;
              for(int i=begin; i<end; i++)
                   if(!occupied) //if room is not occupied
                        occupied[i] = true;
                        roomNumber = i+1;
                        i = end; //to exit loop
              return roomNumber;
    }**The second part is:**  /*
         Chapter 5:     Reserve a Party Room
         Programmer:     Sabrina M. Liberski
         Date:          December 16, 2007
         Filename:     Reservations.java
         Purpose:     This program creates a windowed application to reserve a party room.
                        It calls an external class named Rooms.
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    public class Reservations extends Frame implements ActionListener
         Color lightRed = new Color(255, 90, 90);
         Color lightGreen = new Color(140, 215, 40);
         Rooms room = new Rooms(5,3);
         Panel roomPanel = new Panel();
              TextArea roomDisplay[] = new TextArea[9];
         Panel buttonPanel = new Panel();
              Button bookButton = new Button("Book Room");
         Panel inputPanel = new Panel();
              Label custNameLabel = new Label("Name:");
              TextField nameField = new TextField(15);
              Label custPhoneLabel = new Label("Phone number:");
              TextField phoneField = new TextField(15);
              Label numLabel = new Label("Number in party:");
              Choice numberOfGuests = new Choice();
              CheckboxGroup options = new CheckboxGroup();
                   Checkbox nonSmoking = new Checkbox("Nonsmoking", false, options);
                   Checkbox smoking = new Checkbox("Smoking", false, options);
                   Checkbox hidden = new Checkbox("", true, options);
         public Reservations()
              //set Layouts for frame and three panels
              this.setLayout(new BorderLayout());
                   roomPanel.setLayout(new GridLayout(2,4,10,10));
                   buttonPanel.setLayout(new FlowLayout());
                   inputPanel.setLayout(new FlowLayout());
              //add components to room panel
              for (int i=1; 1<9; i++)
                   roomDisplay[i] = new TextArea(null,3,5,3);
                   if (i<6)
                        roomDisplay[i].setText("Room " + i + " Nonsmoking");
                   else
                        roomDisplay[i].setText("Room " + i + " Smoking");
                   roomDisplay[i].setEditable(false);
                   roomDisplay[i].setBackground(lightGreen);
                   roomPanel.add(roomDisplay[i]);
              //add components to button panel
              buttonPanel.add(bookButton);
              //add components to input panel
              inputPanel.add(custNameLabel);
              inputPanel.add(nameField);
              inputPanel.add(custPhoneLabel);
              inputPanel.add(phoneField);
              inputPanel.add(numLabel);
              inputPanel.add(numberOfGuests);
                   for(int i = 8; i<=20; i++)
                        numberOfGuests.add(String.valueOf(i));
              inputPanel.add(nonSmoking);
              inputPanel.add(smoking);
              //add panels to frame
              add(buttonPanel, BorderLayout.SOUTH);
              add(inputPanel, BorderLayout.CENTER);
              add(inputPanel, BorderLayout.NORTH);
              bookButton.addActionListener(this);
              //overriding the windowClosing() method will allow the user to click the Close button
              addWindowListener(
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             System.exit(0);
         }//end of constructor method
         public static void main(String[] args)
              Reservations f = new Reservations();
              f.setBounds(200,200,600,300);
              f.setTitle("Reserve a Party Room");
              f.setVisible(true);
         } //end of main
         public void actionPerformed(ActionEvent e)
              if (hidden.getState())
                   JOptionPane.showMessageDialog(null, "You must select Nonsmoking or Smoking.", "Error", JOptionPane.ERROR_MESSAGE);
              else
                   int available = room.bookRoom(smoking.getState());
                   if (available > 0) //room is available
                        roomDisplay[available].setBackground(lightRed); //display room as occupied
                        roomDisplay[available].setText(
                                                                roomDisplay[available].getText() +
                                                                "\n" +
                                                                nameField.getText() +
                                                                " " +
                                                                phoneField.getText() +
                                                                "\nparty of " +
                                                                numberOfGuests.getSelectedItem()
                                                           ); //display info in room
                        clearFields();
                   else //room is not available
                        if (smoking.getState())
                             JOptionPane.showMessageDialog(null, "Smoking is full.", "Error", JOptionPane.INFORMATION_MESSAGE);
                        else
                             JOptionPane.showMessageDialog(null, "Nonsmoking is full.", "Error", JOptionPane.INFORMATION_MESSAGE);
                        hidden.setState(true);
                   } //end of else block that checks the available room number
              } //end of else block that checks the state of the hidden option button
         } //end of actionPerformed method
         //reset the text fields and choice component
         void clearFields()
              nameField.setText("");
              phoneField.setText("");
              numberOfGuests.select(0);
              nameField.requestFocus();
              hidden.setState(true);
         } //end of clearFields() method
    } //end of Reservations class                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    In order to display a component, that component has to be added to a container that is either that root container or has a parent container that is the root container. You have at least one JPanel, roomPanel, that is added to nothing. You will have to search through this to see if their are others.
    But more importantly, you are coding this all wrong. You need to code like so:
    1) create your class skeleton, see that it compiles and runs.
    2) add enough to make a JFrame appear, nothing more. Make sure it compiles, runs, and you see the frame.
    3) add code a little bit at a time, and after each addition, compile and run the code, make sure that you see any visual elements.
    4) repeat section 3 until project done.
    5) for larger projects, I create separate classes and run each one with its own main method to check it as I create it before adding it to the greater program.
    If you don't do it this way, you will end up with a mess where when you correct one error, three more show up.
    Also, I recommend that when an error or problem pops up like one did just now (invisible components) that you work on debugging it first for at least 1-2 hours before coming to the forum for answers. Otherwise you don't learn how to debug, an important skill to master.
    Edited by: petes1234 on Dec 17, 2007 10:11 AM

  • Need more help with a GUI

    It's the ever popular Inventory program again! I'm creating a GUI to display the information contained within an array of objects which, in this case, represent compact discs. I've received some good help from other's posts on this project since it seems there's a few of us working on the same one but now, since each person working on this project has programmed theirs differently, I'm stuck. I'm not sure how to proceed with my ActionListeners for the buttons I've created.
    Here's my code:
    // GUICDInventory.java
    // uses CD class
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class GUICDInventory extends JFrame
         protected JPanel panel; //panel to hold buttons
         protected JPanel cdImage; // panel to hold image
         int displayElement = 0;
         public String display(int element)
                   return CD2[element].toString();
              }//end method
         public static void main( String args[] )
              new GUICDInventory();
         }// end main
         public GUICDInventory()
              CD completeCDInventory[] = new CD2[ 5 ]; // creates a new 5 element array
             // populates array with objects that implement CD
             completeCDInventory[ 0 ] = new CD2( "Sixpence None the Richer" , "D121401" , 12 , 11.99, 1990 );
             completeCDInventory[ 1 ] = new CD2( "Clear" , "D126413" , 10 , 10.99, 1998 );
             completeCDInventory[ 2 ] = new CD2( "NewsBoys: Love Liberty Disco" , "2438-51720-2" , 10 , 12.99, 1999 );
             completeCDInventory[ 3 ] = new CD2( "Skillet: Hey You, I Love Your Soul" , "D122966" , 9 , 9.99, 1998 );
             completeCDInventory[ 4 ] = new CD2( "Michael Sweet: Real" , "020831-1376-204" , 15 , 12.99, 1995 );
             //declares totalInventoryValue variable
                 double totalInventoryValue = CD.calculateTotalInventory( completeCDInventory );
              final JTextArea textArea = new JTextArea(display(displayElement));
              final JButton prevBtn = new JButton("Previous");
              final JButton nextBtn = new JButton("Next");
              final JButton lastBtn = new JButton("Last");
              final JButton firstBtn = new JButton("First");
              prevBtn.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent ae)
                        displayElement = (//what goe here? ) % //what goes here?
                        textArea.setText(display(displayElement));// <--is this right?
              nextBtn.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent ae)
                          displayElement = (//what goes here? ) % //what goes here?
                        textArea.setText(display(displayElement));// <--is this right?
              firstBtn.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent ae)
                        displayElement = 0;
                        textArea.setText(display(displayElement));// <--is this right?
              lastBtn.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent ae)
                        displayElement = //what goes here?;
                        textArea.setText(display(displayElement));// <--is this right?
              JPanel panel = new JPanel(new GridLayout(1,2));
              panel.add(firstBtn); panel.add(nextBtn); panel.add(prevBtn); panel.add(lastBtn);
              JPanel cdImage = new JPanel(new BorderLayout());
              cdImage.setPreferredSize(new Dimension(600,400));
              JFrame      cdFrame = new JFrame();
              cdFrame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);
              cdFrame.getContentPane().add(panel,BorderLayout.SOUTH);
              cdFrame.getContentPane().add(new JLabel("",new ImageIcon("cd.gif"),JLabel.CENTER),BorderLayout.NORTH);
              cdFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cdFrame.pack();
              cdFrame.setSize(500,200);
              cdFrame.setTitle("Compact Disc Inventory");
              cdFrame.setLocationRelativeTo(null);
              cdFrame.setVisible(true);
         }//end GUICDInventory constructor
    } // end class GUICDInventory
    // CD2.java
    // subclass of CD
    public class CD2 extends CD
         protected int copyrightDate; // CDs copyright date variable declaration
         private double price2;
         // constructor
         public CD2( String title, String prodNumber, double numStock, double price, int copyrightDate )
              // explicit call to superclass CD constructor
              super( title, prodNumber, numStock, price );
              this.copyrightDate = copyrightDate;
         }// end constructor
         public double getInventoryValue() // modified subclass method to add restocking fee
            price2 = price + price * 0.05;
            return numStock * price2;
        } //end getInventoryValue
        // Returns a formated String contains the information about any particular item of inventory
        public String displayInventory() // modified subclass display method
              return String.format("\n%-22s%s\n%-22s%d\n%-22s%s\n%-22s%.2f\n%-22s%s%.2f\n%-22s%s%.2f\n%-22s%s%.2f\n  \n" ,
                                       "CD Title:", title, "Copyright Date:", copyrightDate, "Product Number:", prodNumber , "Number in Stock:",
                                       numStock , "CD Price:" , "$" , price , "Restocking fee (5%):", "$", price*0.05, "Inventory Value:" , "$" ,
                                       getInventoryValue() );
         } // end method
    }//end class CD2
    // CD.java
    // Represents a compact disc object
    import java.util.Arrays;
    class CD implements Comparable
        protected String title; // CD title (name of product)
        protected String prodNumber; // CD product number
        protected double numStock; // CD stock number
        protected double price; // price of CD
        protected double inventoryValue; //number of units in stock times price of each unit
        // constructor initializes CD information
        public CD( String title, String prodNumber, double numStock, double price )
            this.title = title; // Artist: album name
            this.prodNumber = prodNumber; //product number
            this.numStock = numStock; // number of CDs in stock
            this.price = price; //price per CD
        } // end constructor
        public double getInventoryValue()
            return numStock * price;
        } //end getInventoryValue
        //Returns a formated String contains the information about any particular item of inventory
        public String displayInventory()
              //return the formated String containing the complete information about CD
            return String.format("\n%-22s%s\n%-22s%s\n%-22s%.2f\n%-22s%s%.2f\n%-22s%s%.2f\n%-22s%s%.2f\n  \n" ,
                                       "CD Title:", title, "Product Number:", prodNumber , "Number in Stock:",
                                       numStock , "CD Price:" , "$" , price , "Restocking fee (5%):", "$", price*0.05, "Inventory Value:" , "$" ,
                                       getInventoryValue() );
        } // end method
        //method to calculate the total inventory of the array of objects
        public static double calculateTotalInventory( CD completeCDInventory[] )
            double totalInventoryValue = 0;
            for ( int count = 0; count < completeCDInventory.length; count++ )
                 totalInventoryValue += completeCDInventory[count].getInventoryValue();
            } // end for
            return totalInventoryValue;
        } // end calculateTotalInventory
         // Method to return the String containing the Information about Inventory's Item
         //as appear in array (non-sorted)
        public static String displayTotalInventory( CD completeCDInventory[] )
              //string which is to be returned from the method containing the complete inventory's information
              String retInfo = "\nInventory of CDs (unsorted):\n";
              //loop to go through complete array
              for ( int count = 0; count < completeCDInventory.length; count++ )
                   retInfo = retInfo + "Item# " + (count + 1);          //add the item number in String
                   retInfo = retInfo + completeCDInventory[count].displayInventory();     //add the inventory detail in String
              }// end for
              return retInfo;          //return the String containing complete detail of Inventory
        }// end displayTotalInventory
         public int compareTo( Object obj ) //overlaod compareTo method
              CD tmp = ( CD )obj;
              if( this.title.compareTo( tmp.title ) < 0 )
                   return -1; //instance lt received
              else if( this.title.compareTo( tmp.title ) > 0 )
                   return 1; //instance gt received
              return 0; //instance == received
              }// end compareTo method
         //Method to return the String containing the Information about Inventory's Item
         // in sorted order (sorted by title)
         public static String sortedCDInventory( CD completeCDInventory[] )
              //string which is to be returned from the method containing the complete inventory's information
              String retInfo = "\nInventory of CDs (sorted by title):\n";
              Arrays.sort( completeCDInventory ); // sort array
              //loop to go through complete array
              for( int count = 0; count < completeCDInventory.length; count++ )
                   retInfo = retInfo + "Item# " + (count + 1);     //add the item number in String
                   retInfo = retInfo + completeCDInventory[count].displayInventory(); //add the inventory detail in String
              return retInfo;     //return the String containing complete detail of Inventory
         } // end method sortedCDInventory
    } // end class CD

    nextBtn.addActionListener(new ActionListener()
         public void actionPerformed(ActionEvent ae)
                   displayElement = (//what goes here? ) % //what goes here?
                   textArea.setText(display(displayElement));// <--is this right?
    });Above is your code for the "Next" button.
    You ask the question "What goes here"? Well what do you think goes there?
    If you are looking at item 1 and you press the "Next" button do you not want to look at item 2?
    So the obvious solution would be to add 1 to the previous item value. Does that not make sense? What problem do you have when you try that code?????
    Next you say "Is this right"? Well how are we supposed to know? You wrote the code. We don't know what the code is supposed to do. Again you try it. If it doesn't work then describe the problem you are having. I for one can't execute your code because I don't use JDK5. So looking at the code it looks reasonable, but I can't tell by looking at it what is wrong. Only you can add debug statements in the code to see whats happening.
    If you want help learn to as a proper question and doen't expect us to spoon feed the code to you. This is your assignment, not ours. We are under no obligation to debug and write the code for you. The sooner you learn that, the more help you will receive.

  • I need help with my GUI Photo Album.

    Hello! I'm still learning bits about GUI and I need some assistance to make my basic program work. I've searched the forums to look at past Photo Album projects; they didn't help much or maybe I'm overlooking some things. Every time I click the "Next" button the image doesn't change. It may be a simple task to solve, but I'm really stumped! Sorry if it's such a stupid thing to ask. Thanks in advance.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class PhotoAlbum extends JPanel {
        int i = 1;
        JFrame frame = new JFrame("Photo Album");
        JButton next = new JButton("Next");
        ImageIcon icon = new ImageIcon("../Images/" + i + ".jpg");
        JLabel picture = new JLabel(icon);
        ButtonListener buttonListener = new ButtonListener();
        public PhotoAlbum() {
            frame.setSize(700, 600);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(new BorderLayout(5,5));
            frame.getContentPane().add(picture, BorderLayout.CENTER);
            frame.getContentPane().add(next, BorderLayout.SOUTH);
            next.addActionListener(buttonListener);
            frame.setVisible(true);
        class ButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() == next){
                    ++i;
    }

    WafflesNSyrup wrote:
    int i = 1;
    ImageIcon icon = new ImageIcon("../Images/" + i + ".jpg");
    ++i;
    So I understand that you originally thought incrementing (i) would somehow update (icon) since it uses (i) in an expression. But now you hopefully know this is not a magical expression language.
    I bet you would have also thought that this:
    int x = 1;
    int y = 2;
    int z = x + y;
    x = 42;
    y = 58;would have ended up with z having the value 100? It doesn't. It did the math once, when it executed the expression (x + y) and stored it in the variable (z). So z == 3, regardless of what happens to x or y after the fact.

  • SAPgui.exe is running even after closing the GUI components

    Hello All,
    Even after closing the SAP GUI components like Bex, WAD or RSA1 etc... i am able to see these processes are running under the Task Manager--> Processes....
    even if i try to restart the system, error messages are occuring...saying that SAP is still opend...
    Why it is happening, any ideas?
    Thanks,
    Ravi

    Hi Dirk,
    Thanks for your infomation. Infact, apart from this problem, i have the problem with saving the webtemplate. As it is taking much time to save a template after modifications, i had to terminate the wad process. It seems above 2 problems are related....any ideas?
    Thanks
    ravi
    Message was edited by: Ravi Pasumarty

  • Help starting with GUI

    I am working on programing a program for my department, Meteorology, at school so that I can download images every five minutes. I have a version of this that works in the command line, but I want to add a gui to it now. I am not really sure how to start. I know that I need a drop down box with all of the radar sites and their call numbers, and a radio button so they can select the type of image that the user wants to download. These two parts then make up the URL of the image so I can download it. I tried makeing a gui by making each one of these components a separate class. Basically, I am wondering if I should start off by making the GUI all one class, or if each peice of it should be its own class that then gets tied together in a different part of the program. any help with GUI would be great as I am new to this step of programing having only worked in Java command line and Fortran 77. Thanks
    Neil

    Hi,
    You can create a GUI from within one class. GUIs can be created for applications or applets. The following code is a simple GUI for an application using Swing components. You may need JDK 1.3.1_6.
    To make your GUI functional you would need to add or implement Event Handlers preferably using the delegation model. Each control(buttons, textfield, etc) you need to define the event object(button clicks), the event source(button), and an event handler(understands the event and executes code that processes the event).
    import javax.swing.*;
    public class Customer
    //Variable for frame window
    static JFrame frameObj;
    static JPanel panelObj;
    //Variables of labels
    JLabel labelCustName;
    JLabel labelCustCellNo;
    JLabel labelCustPackage;
    JLabel labelCustAge;
    //Variables for data entry controls
    JTextField textCustName;
    JTextField textCustCellNo;
    JComboBox comboCustPackage;
    JTextField textCustAge;
    public static void main(String args[])
         //Creating the JFrame object
         frameObj = new JFrame("Customer Details Form");
         //Setting the close option
         frameObj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Making the frame visible
         frameObj.setVisible(true);
    frameObj.setSize(300,300);
    Customer customerObj = new Customer();
    public Customer()
         //Add appropriate controls to the frame in the constructor
         //Create panel
         panelObj = new JPanel();
    frameObj.getContentPane().add(panelObj);
    //Setting close option
    frameObj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and add the appropriate controls
    //Initializing labels
    labelCustName = new JLabel("Customer Name: ");
    labelCustCellNo = new JLabel("Cell Number: ");
    labelCustPackage = new JLabel("Package: ");
    labelCustAge = new JLabel("Age: ");
    //Initializing data entry controls
    textCustName = new JTextField(30);
    textCustCellNo = new JTextField(15);
    textCustAge = new JTextField(2);
    String packages[] = {"Executive", "Standard"};
    comboCustPackage = new JComboBox(packages);
    //Adding controls for customer name
    panelObj.add(labelCustName);
    panelObj.add(textCustName);
    //Adding controls for cell number
    panelObj.add(labelCustCellNo);
    panelObj.add(textCustCellNo);
    //Adding controls for Package
    panelObj.add(labelCustPackage);
    panelObj.add(comboCustPackage);
    //Adding controls for customer age
    panelObj.add(labelCustAge);
    panelObj.add(textCustAge);

  • Help with SAP GUI on Trial VMWare Edition

    I currently have a trial version of NetWeaver installed (SAP NetWeaver 7.0.1 Java + ABAP Trial VMWare Edition), but having problems getting the GUI to work.  The VM is using GNOME 2.12.2.
    I'm currently having trouble with SAP GUI.  According to SAP help, a requirement to run SAP GUI for HTML is Windows NT 4.0.  Since I'm using GNOME, I tried to get the Java version to work.
    When I try to launch SAP GUI, it gives me the following error:
    http://i.imgur.com/0ZBVI.png
    I wasn't able to troubleshoot the error, so I'm in the process of uninstalling this version of SAP GUI, and try installing again.  However, I'm having trouble performing the uninstall.  I did some reading, and it says to either run the SAPsweep.exe utility or NWSapSetup.exe.  But I can't find either of them on my machine (tried doing a system search, no luck).
    I found this thread to be helpful: Re: sapsweep.exe for SAPGUI 7.10 ?, but I'm not running on Windows.
    Thanks in advance for any input

    Hello Anoop.
    The error occurs because you have selected OLE DB for OLAP Provider in the Business Explorer selection.
    You can tell this from the following line in your sapsetup
    00:43:58 NwSapsAtlC  1W  Marking package SAPGUI_7.30 ({57F4A687-AE41-4BEA-9553-F852C36F8C1E}) as disabled: selected node OLE DB for OLAP Provider ({5390360A-98D9-4377-BD41-9A147392D000}) has failing condition.
    Since you don't have Office installed,you cannot use the Business Explorer modules.
    Run the installation again only selecting the components you require.
    Jude

  • Please help with the GUI quiz question!

    Hi Folks,
    Please help me with the code for the following GUI.
    The display window of the application should have two panels at the top level (you could have multiple panels contained within a top-level panel). The first top level panel should have a grid or a border layout and should include apart from various label objects: 1) a textfield to store the info entered, 2) a combobox 3) a combobox or a list box , 4) a radio-button group , 5) a combo box 6) checkboxes for additional accessories, and 7) checkboxes .
    The second top-level panel that is placed at the bottom of the window should have a submit button, a clear button and a textarea for output.
    Thanks a lot.

    Please be a little more explicit about what you're doing, what you expect to happen, and what you actually observe.
    Please post a short, concise, executable example of what you're trying to do. This does not have to be the actual code you are using. Write a small example that demonstrates your intent, and only that. Wrap the code in a class and give it a main method that runs it - if we can just copy and paste the code into a text file, compile it and run it without any changes, then we can be sure that we haven't made incorrect assumptions about how you are using it.
    Post your code between [code] and [/code] tags. Cut and paste the code, rather than re-typing it (re-typing often introduces subtle errors that make your problem difficult to troubleshoot). Please preview your post when posting code.
    Please assume that we only have the core API. We have no idea what SomeCustomClass is, and neither does our collective compiler.
    If you have an error message, post the exact, complete error along with a full stack trace, if possible. Make sure you're not swallowing any Exceptions.
    Help us help you solve your problem.

  • Adding Help to a GUI

    I'm a bit new at making GUI's in java. I need to add a help option in my GUI by having a question mark at the right top corner of the window that once clicked when you hover over certain areas in the GUI it will provide help. does anyone know a good place for me to start looking (it's hard to google for it) or give me some starting code?
    Thank you

    Do you want one in the title bar? If so forget it. While you can do it, it would be very hard to do. (1)
    Having a "help" button somewhere else on the window would be easy.
    It could be done by having an action listener changing the mouse cuser on the Window curser, most likely to a custom curser. Then adding mouse listeners to everything that can be "helped". Which consumes the event (so the action listener on buttons is not fired), removes itself from all that it had been added to, and opens the help window for the object picked.
    1) To change the title bar requires JNI, or making a Custom L&F, and having that be able to add a "help" button

  • Need quick help closing port

    I have created a server.java and client.java
    The programs are not that good.
    However I have a problem
    I have ran my server a few times and each time need to use a diff port as the previous ones are being listnened to. Obviously from the last servers I ran.
    I have switched my comp off and on many times and these ports are still in use.
    Please help as I have no idea what is wrong.

    I don't have a copy of XP at hand, so I can only give you some generalities.
    Somewhere in the Control Panel, I think in the Administrative Tools folder, there should be a "Services" program that displays to some extent what programs you have running. Every program that's listening on a port should be listed in there.
    It sounds like XP thinks you've only temporarily suspended your server program. I won't guarantee that's the case, but that's what sounds reasonable, and as a result, it is saving those "open" port numbers just in case you decide to resume the program.
    If you have copies of server.java on that list (or rather, copies of the JVM), I would suggest closing all of your Java programs first, your web browsers to be on the safe side, and then "stop" and "remove" any remaining JVMs especially those that are tied to the ports you want to close.
    (And yes, you are discovering the hard way why it's crucial that you remember to close your ports. The simplest way to do so is to write a method that closes all ports, and include it inside each and every try...catch block, as well as your exit routine.)

  • Need help..anyone GUI Interfaces

    http://forum.java.sun.com/thread.jsp?forum=31&thread=472147&tstart=0&trange=15
    Can someone please help me with this program..I'm new to java and I don't understand GUI's. I read everything inside and out in my text book and still don't get how to convert my program into a gui interface...please help.

    Sorry i accidently posted twice...
    But here is my topic incase the link did not work. Thanks! Really desperate!
    Develop a Java application that will determine if a department store customer has exceeded the credit limit on a charge account. For each customer, the following facts are available:
    a) Account Balance
    b) Balance at the beginning of the month
    c) Total of all items charged by this customer this month
    d) Total of all credits applied to the customer&#8217;s account this month
    e) Allowed credit limit
    This program should input each of these facts from input dialogs as integers, calculate the new balance, display the new balance and determine if the new balance exceeds the customer&#8217;s credit limit. For those customers whose credit limit is exceeded, the program should display the message, &#8220;Credit limit exceeded.&#8221;
    Here is the program I wrote : (for the above criteria)
    // Credit.java
    // Program monitors accounts
    import java.awt.*;
    import javax.swing.JOptionPane;
    public class Credit {
    public static void main( String args[] )
    String inputString;
    int account, newBalance,
    oldBalance, credits, creditLimit, charges;
    inputString =
    JOptionPane.showInputDialog( "Enter Account (-1 to quit):" );
    while ( ( account = Integer.parseInt( inputString ) ) != -1 ) {
    inputString =
    JOptionPane.showInputDialog( "Enter Balance: " );
    oldBalance = Integer.parseInt( inputString );
    inputString =
    JOptionPane.showInputDialog( "Enter Charges: " );
    charges = Integer.parseInt( inputString );
    inputString =
    JOptionPane.showInputDialog( "Enter Credits: " );
    credits = Integer.parseInt( inputString );
    inputString =
    JOptionPane.showInputDialog( "Enter Credit Limit: " );
    creditLimit = Integer.parseInt( inputString );
    newBalance = oldBalance + charges - credits;
    String resultsString, creditStatusString;
    resultsString = "New balance is " + newBalance;
    if ( newBalance > creditLimit )
    creditStatusString = "CREDIT LIMIT EXCEEDED";
    else
    creditStatusString = "Credit Report";
    JOptionPane.showMessageDialog(
    null, resultsString,
    creditStatusString,
    JOptionPane.INFORMATION_MESSAGE );
    inputString =
    JOptionPane.showInputDialog( "Enter Account (-1 to quit):" );
    System.exit( 0 );
    AND I NEED TO MODIFY IT TO DO THE FOLLWOING: (I'M A NEWB AND IT'S TAKEN ME FOREVER JUST TO DO THE ABOVE..PLEASE ANY HELP WOULD BE GREAT!!
    Expand the above program.
    1) Design an appropriate GUI for input. You cannot use dialog boxes. Design functional window(s) from scratch. State your conditions in the boxed comment at the top of the class. Input will need a transaction date also for the CustomerHistory class.
    2) Add a customer # ( a unique identifier)
    3) Besides your GUI, you will want 2 other classes: Customer and CustomerHistory. CustomerHistory will serve as a mock database.
    4) CustomerHistory will hold the previous balance & allowed credit limit plus any credit violation history. Your CustomerHistory violations must be an array, so that it could be readily expandable.
    5) Some step-up is necessary &#8211; chose your own approach and document.
    6) Then run your system enough times to show the response when a customer exceeds THREE &#8216;over credit&#8217; limits. CustomerHistory violations should be printed out, as well as, our choice of a &#8216;dunning notice&#8217;. It cannot be the same as a simple one time exceeds limit. Also show a normal customer run. Prove to me your solution works!
    7) Draw the UML diagram of your interconnecting classes.

  • Help with Dynamic GUI

    I am trying to create a dynamic gui for a program that when given three names, it will make a list of matches ( wrestling ) against each other.. I got it so when you click foward once.. it brings up the specified amount of text fields.. but when i click previous, it does not pack it fully, and the buttonPanel does not go back to the minimal size, and keeps the whole frame long.
    [code="face.java"]import java.awt.*;
    import java.awt.Component.*;
    import java.awt.event.*;
    public class face extends GUIFrame implements WindowListener, ActionListener {
    static TextField[] nameFields;
    List howMany;
    TextArea finish;
    Button forward, back, startOver, print;
    Panel mainPanel, buttonPanel, numberPanel, namePanel, matchesPanel;
    GridBagLayout gbl;
    GridBagConstraints gbc;
    BorderLayout bpl, mpl;
    CardLayout cl;
    Choice numbers;
    public face() {
    super("Wrestling Order");
    gbl = new GridBagLayout();
    gbc = new GridBagConstraints();
    setLayout(gbl);
    mainPanel = new Panel();
    buttonPanel = new Panel();
    bpl = new BorderLayout();
    back = new Button("Previous");
    back.setEnabled(false);
    back.addActionListener(this);
    back.setActionCommand("numOf");
    buttonPanel.setLayout(bpl);
    buttonPanel.add(back, BorderLayout.WEST);
    forward = new Button("Forward");
    forward.addActionListener(this);
    forward.setActionCommand("names");
    buttonPanel.add(forward, BorderLayout.EAST);
    startOver = new Button("Start Over");
    buttonPanel.add(startOver, BorderLayout.SOUTH);
    //mainPanel
    numberPanel = new Panel();
    numbers = new Choice();
    numbers.add("3");
    numbers.add("4");
    numbers.add("5");
    numberPanel.setLayout(bpl);
    numberPanel.add(numbers, BorderLayout.CENTER);
    cl = new CardLayout();
    mainPanel.setLayout(cl);
    mainPanel.add("numbers", numberPanel);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbl.setConstraints(mainPanel, gbc);
    add(mainPanel);
    gbc.gridx = 0;
    gbc.gridy = 5;
    gbl.setConstraints(buttonPanel, gbc);
    add(buttonPanel);
    addWindowListener(this);
    pack();
    setVisible(true);
    public Panel makeNamePanel(int numOfNames) {
    gbl = new GridBagLayout();
    gbc = new GridBagConstraints();
    gbc.gridx = 1;
    gbc.gridy = GridBagConstraints.RELATIVE;
    nameFields = new TextField[numOfNames];
    Panel makePanel = new Panel();
    for (int x=0; x < nameFields.length; x++) {
    nameFields[x] = new TextField(20);
    makePanel.add(nameFields[x]);
    return makePanel;
    public void windowClosing(WindowEvent e) {
    dispose();
    System.exit(0);
    public void windowOpened(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand() == "names") {
    namePanel = makeNamePanel(Integer.parseInt(numbers.getItem(numbers.getSelectedIndex())));
    mainPanel.add("name", namePanel);
    cl.next(mainPanel);
    forward.setActionCommand("final");
    pack();
    back.setEnabled(true);
    if (e.getActionCommand() == "numOf") {
    cl.previous(mainPanel);
    pack();
    forward.setActionCommand("names");
    back.setEnabled(false);
    that is the face.java .. it extends GUIFrame.. which is as follows..
    * GUIFrame
    * An extension of Frame that uses a WindowAdapter to
    * handle the WindowEvents and is centered.
    import java.awt.*;
    import java.awt.event.*;
    public class GUIFrame extends Frame {
      public GUIFrame(String title) {
        super(title);
        setBackground(SystemColor.control);
        addWindowListener(new WindowAdapter() {
          //only need to override the method needed
          public void windowClosing(WindowEvent e) {
            dispose();
            System.exit(0);
      /* Centers the Frame when setVisible(true) is called */
      public void setVisible(boolean visible) {
        if (visible) {
          Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
          setLocation((d.width - getWidth())/2,
                      (d.height - getHeight())/2);
        super.setVisible(visible);
    }If you could help me out.. Thanks..

    Have you tried using some other layouts... GridBagLayout is a complicated thing to figure out... Might be easier to use some nested panels with different layouts... Particularly, look at SpringLayout.

Maybe you are looking for