ActionEvents

I am a student working on a simple project, or so I thought. I have to design a calculator using Swing. I have the application set up, but I need help understanding actionEvents. My GUI looks good, all buttons have actionEvents attached to them, my LCD display works fine, but I have one major problem.
I am trying to set up my actionEvents like this.
I have one set declared within my Calculator class that simply adds a number to a string, so if the user pushes "1", then "2", then "7", my string will be 127.
I have another class that implements actionListener and is used for the plus, minus, divide, etc. buttons. This class saves the current string in the LCD display and then clears the LCD display.
I plan on using this structure, but don't know if it is a good setup or not. I would also like to know how I can pass strings between these classes. For example, when a user pushes the "+" button, the actionListener function that is called is outside of my Calculator Class. Therefore, I have to pass the LCDdisplay to this function. I would then like to save the LCDdisplay string, clear it, and pass back the what I saved. Can I do this.
Any help would be greatly appreciated.
Thanks,
Cleatis

I am a student working on a simple project, or so I thought. I have to design a calculator using Swing. I have the application set up, but I need help understanding actionEvents. My GUI looks good, all buttons have actionEvents attached to them, my LCD display works fine, but I have one major problem.
I am trying to set up my actionEvents like this.
I have one set declared within my Calculator class that simply adds a number to a string, so if the user pushes "1", then "2", then "7", my string will be 127.
I have another class that implements actionListener and is used for the plus, minus, divide, etc. buttons. This class saves the current string in the LCD display and then clears the LCD display.
I plan on using this structure, but don't know if it is a good setup or not. I would also like to know how I can pass strings between these classes. For example, when a user pushes the "+" button, the actionListener function that is called is outside of my Calculator Class. Therefore, I have to pass the LCDdisplay to this function. I would then like to save the LCDdisplay string, clear it, and pass back the what I saved. Can I do this.
Any help would be greatly appreciated.
Thanks,
Cleatis

Similar Messages

  • ActionListeners and ActionEvents

    Alright guys I am building myself a GUI and am using ActionListeners and ActionEvents however I'm not exactly sure what these 2 things do. I know they are used for buttons seeing as all of my buttons implement them but what specifically do they do. How does the ActionListener link to the ActionEvent???

    Check this out:
    http://java.sun.com/docs/books/tutorial/uiswing/learn/index.html
    You definitely need an overview of event-based programming to get a start with Swing. Also, make sure you understand anonymous classes (a type of inner class), as they are used extensively throughout Swing (especially in sample code), and are quite confusing if you don't know what they are!
    Nick

  • Can't run ActionEvents from Eclipse compiler!

    Hello, Ladies and Gentleman
    I am new to Java and having serious problems running ActionEvents. For example:
    package JavaAIO;
    import javax.swing.*;
    import java.awt.event.*;
    public class ClickMe extends JFrame{
         public static void main(String[] args){
              new ClickMe();
         private JButton button;
         public ClickMe(){
              this.setSize(400,200);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setTitle("I'm Listening again!");
              ClickListener cl = new ClickListener();
              JPanel panel = new JPanel();
              JButton button = new JButton("Good Times!");
              button.addActionListener(cl);
              panel.add(button);
              this.add(panel);
              this.setVisible(true);
         private class ClickListener implements ActionListener {
              private int count = 0;
              public void actionPerformed(ActionEvent e){
                   if(e.getSource()== button){
                        count++;
                        if (count == 1)
                             button.setText("Hell yeah!");
                        else
                             button.setText("It's been" + count + "times!");
    This code will give me a nice JFrame with a button labeled 'Good Times' but no subsequent onClick result. Any ideas? Is it me? Is it Eclipse Ganymede?
    Thanks so much for all of your help! :D

    Alright!
    First of all, thank you ALL for your help! I am still a bit confused though.
    package JavaAIO;
    import javax.swing.;
    import java.awt.event.;
    public class ClickMe extends JFrame{
    public static void main(String[] args){
    new ClickMe();
    private JButton button;
    public ClickMe(){
    this.setSize(400,200);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("I'm Listening again!");
    ClickListener cl = new ClickListener();
    JPanel panel = new JPanel();
    JButton *button* = new JButton("Good Times!");
    *button*.addActionListener(cl);
    panel.add(button);
    this.add(panel);
    this.setVisible(true);
    private class ClickListener implements ActionListener {
    private int count = 0;
    public void actionPerformed(ActionEvent e){
    if(e.getSource()== button){
    count++;
    if (count == 1)
    *button*.setText("Hell yeah!");
    else
    *button*.setText("It's been" + count + "times!");
    }There should be four: one to declare the setText intially, JButton *button* = new JButton("Good Times!");one to add the ActionListener method, *button*.addActionListener(cl);one to change it onClickif (count == 1)
    *button*.setText("Hell yeah!");and the fourth to change it to display the "count" variable.{code*button*.setText("It's been" + count + "times!");} It appears, in going back over the code, that I had declared it twice. Would that be necessary?  Good times, and thanks to everyone again!
    Oh, by the way, I can't get ActionListener to work on any JFrame projects! AHHH!    :O                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JTextField ActionEvents

    Hi everyone,
    I'm working on an applet that contains 3 Jpanels. One of the Jpanels, called infoarea, has a JTextField called typein- the idea being that the user can enter one word at a time, which then gets stored in an array of Strings.
    I've tried to get infoarea to listen for typein ActionEvents, with the following... (Infoarea is a nested class within the applet)
    class Infoarea extends JPanel
         implements ActionListener{
    Infoarea(){
              typein.addActionListener(this);
    public void actionPerformed(ActionEvent evt){
              userword [userfound] = evt.getActionCommand();
              userfound ++;
    ......rest of class.... }
    The applet compiles OK, but when I try to display it on a webpage I get a null point exception, and a message saying that the applet has not been init()ed. If I remove the above code, the remaining applet displays without a problem.
    I have tried getting the applet itself to listen to the typein JTextField, but I get the same results. One of the other JPanels in the applet is listening for its own MouseEvents, though I can't see why this would cause a conflict.
    Hopefully I'm being dense and making a very silly mistake.
    Can anyone offer me some advice ?? Thanks.

    The constructor for InfoArea must be getting called before typein gets initialized. typein.addActionListener(this); is probably what is causing the exception due to typein being null. I suggest adding your Infoarea object as the actionListener to typein inside you init() method, after you set the value of the typein variable.

  • ActionEvents and the Toolkit's SelectiveAWTEventListener

    Does anyone know why normal ActionEvents are not delivered to the SelectiveAWTEventListener?
    I have a button on a form that has an ActionListener registered and the button works fine. However if I install a SelectiveAWTEventListener viaToolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.ACTION_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK);I never see ActionEvents.
    I delved through the Java 1.5 code and found that this is correct behaviour - the standard listeners to ActionEvents are called directly off the fireActionPerformed() method of AbstractButton as a result of BasicButtonListener.mouseReleased(). SelectiveAWTEventListener.eventDispatched() is not called.
    What I'm trying actually to detect is when the dialog is about to close. I've tried using the AWT WINDOW_CLOSING event, but that is only fired when the user clicks the window's close icon. AWT WINDOW_CLOSED is (unsurprisingly) only fired after the window has closed.
    I guess at this stage my only option is to listen for MOUSE_RELEASED, but that will give false positives, so I'll have to confirm somehow that the window really is going to close as a result of the MOUSE_RELEASED, and I also need to handle keyboard entry. Yuck!

    I also want to capture JOptionPane events such as OK, Cancel, Yes, No, etc, which cause the dialog to close.
    I've had an idea, and that is to listen for WINDOW_OPENING events on dialogs, and then walk the hierarchy of the dialog's components looking for JButtons. I can then register myself as a listener to ActionEvents on all the buttons, and that way I can detect when any of them is clicked or activated say by Enter.
    The whole point of this exercise is to add window-closing behaviour to all JOptionPane-generated dialogs. As I don't want to subclass or manipulate the JOptionPane class itself in any way, I am restricted to what is possible externally.

  • JLabel to hear ActionEvents?

    I'm writing a GUI prototype in a team for a project. In our paper-design we used quite a few "hyperlinks" and assumed that we would be able to just use JLabels and add an ActionListener.
    It's now that we've found out addActionListener() doesn't exist in JLabel and need a way for a JLabel to know if it's been clicked or to find a similar component which can provide this behaviour.
    JLabel can accept HTML as its label and also hyperlinks in that text, is there any way of finding out if one of those hyperlinks was clicked?
    I looked a JMenuItem but can't override it's background colour or centre alignment.
    I tried extending JAbstractButton and using setLabel to no avail.
    I'd really appreciate any suggestions to solve this problem quickly.
    Thanks
    Alex Ellis

    I'd really appreciate any suggestions to solve this problem quickly.Searching the forum before posting is always a good idea.
    I used "hyperlink label" to search the forums and found several suggestions.

  • JComponent actionevents

    Hi,
    I am having some problem with actionevets. Here are the details-
    I have a tree class, which uses Jtree with few supplimentary functions. Tree represents a 2-D data, very similar to FolderList in My Computer (Windows). The program is an applet which loads and saves data from files.
    The only the main program has access to the database, instance of a table and the tree. User changes database the main program changes tree and table to display the data. If a node is selected, the table should be displaying the contents of the datastructure the node is representing.
    Now since tree is an instance in a program, when selection is changed 'valueChanged TreeSelectionEvent' is triggered within the instance. I want my main program to notice this action and inform table to change its contents accordingly.
    Please let me know if I can accomplish this without making too many changes in my overall program design.
    Thanks,
    Kunal

    Add the main class as ActionListener to the Tree Instance.. Once a event is triggered, the listener (main class or a innerclass) is notified, you can then notify the tables, databases or whatever you want..
    Cheers
    -P

  • ActionEvents gets reversed when retrieved.. why?

    hi all,
    recently when i added 2 instances of action listeners to a component it performed the actions in the reverse order which i added them in. after analysing the source of java's EventListnerList class i realised that in there the listeners are maintained as an array of objects and when a developer calls the getActionListeners() method it returns the listeners in the reverse order by going from the last element to the first element in the object array maintained in the EventListenerList class.. i want to know why this has been done like this? is there a special need or a use of this? what have they tried to achieve by returning the listeners in the reverse order?
    thanks
    Charith

    hi all,
    recently when i added 2 instances of action listeners
    to a component it performed the actions in the
    reverse order which i added them in. AFAIK, the API does not give any guarantees at all regarding the order in which listeners are notified, so you shouldn't write code that depends on any particular order. The current implementation apparently notifies the listeners in reversed order, but in the next Java version this could very well have changed (at least in theory :-) to some other order; maybe the order in which they were added, or maybe a completely random order.
    If you really need two ActionListeners to be notified in a particular order, the safest (?) way is to encapsulate them in one listener object:
    final ActionListener first = ...
    final ActionListener second = ...
    ActionListener firstFirstThenSecond = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            first.actionPerformed(e);
            second.actionPerformed(e);
    };Then add the encapsulating listener to the event-generating component.

  • Loosing ActionEvents when trapping MouseEvents

    Hi there!
    Hope someone's got an explanation for this: I need to implement a JPanel subclass that keeps track of all mouse events issued within the application. If, however, I register an instance of this class as AWTEventListener, all ActionCommands issued by JPopupMenus seem to get lost. Seems to be the panel's processEvent(AWTEvent e) method's fault, as you can easily see by commenting out the corresponding line in the listing below.
    I am looking forward to your replies!
    Regards -
    Torsten
    ---[snipp!]---
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MyFrame extends JFrame
                         implements MouseListener, ActionListener {
      private JMenu myPopup; // the little demo popup menu
      public static void main (String[] argv) {
        MyFrame f = new MyFrame();
        f.setLocation(100, 100);
        f.setSize(300,200);
        f.setVisible(true);
      //--- the panel that wants to catch just _every_ mouse event
      class MyPanel extends JPanel
                    implements AWTEventListener {
        MyPanel() {
          super();
          // tell the event queue to inform this class of all mouse events
          getToolkit().addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK);
        //--- implementation of AWTEventListener
        public void eventDispatched(AWTEvent e) {
    /**** comment out to see the difference! ****/
          processEvent(e);
      //--- the actual application
      public MyFrame() {
        super("My Frame");
        // create the demo menu
        myPopup = new JMenu();
        JMenuItem mi = new JMenuItem("Foo");
        mi.addActionListener(this);
        myPopup.add(mi);
        mi = new JMenuItem("Bar");
        mi.addActionListener(this);
        myPopup.add(mi);
        // add a MyPanel instance
        getContentPane().setLayout(new FlowLayout());
        MyPanel p = new MyPanel();
        getContentPane().add(p, "CENTER");
        // required for menu popupping (or uppopping? ;-)
        addMouseListener(this);
      // decide here whether or not to display myPopup menu
      public void processMouseEvent(MouseEvent e) {
        if (e.isPopupTrigger()) {
          myPopup.getPopupMenu().show(e.getComponent(), e.getX(), e.getY());
        super.processMouseEvent(e);
      //--- implementation of MouseListener
      public void mouseClicked(MouseEvent e) {}
      public void mousePressed(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      //--- implementation of ActionListener
      public void actionPerformed(ActionEvent e) {
        // display the action command issued by myPopup menu
        System.out.println("Action: "+e.getActionCommand());
    }

    Thanks for all your comments - meanwhile I solved the problem myself.
    Torsten

  • Listening to ActionEvents of other classes

    Hi. I have 2 classes. CLASSA needs to listen to button click on CLASSB and make some changes in CLASSA. How will CLASSA know that a ButtonB in CLASSB has been clicked?
    How can I achieve this?.
    thanks

    Well,
    it won't do you no harm if you go and read the sections
    relative to the listeners in the swing tuto :
    http://java.sun.com/docs/books/tutorial/uiswing/events/index.html
    anyway:
    button.addActionListener(classA);
    ClassA implements ActionListener
    and specifies the behaviour of
    public void actionPerformed(ActionEvent e)
    One learns more by searching than having
    the answer served on a dish.
    regards

  • HELP... How can i implement this into my code

    Hello :) I'm writing a simple game here is the code now all it does right now is it writes out the values of the cards on the screen in an applet however I want it to display card images from http://www.waste.org/~oxymoron/cards
    i can't get it to use the string values and give me the card images instead of simple text... please help a woman in trouble ;O) thank you
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    //import java.applet.*;
    ///import java.util.*;
    public class HighLowGUI extends JApplet {
       public void init() {
             // The init() method lays out the applet.
             // A HighLowCanvas occupies the CENTER position of the layout.
             // On the bottom is a panel that holds three buttons.  The
             // HighLowCanvas object listens for ActionEvents from the
             // buttons and does all the real work of the program.
          setBackground( new Color(130,50,40) );
          HighLowCanvas board = new HighLowCanvas();
          getContentPane().add(board, BorderLayout.CENTER);
          JPanel buttonPanel = new JPanel();
          buttonPanel.setBackground( new Color(220,200,180) );
          getContentPane().add(buttonPanel, BorderLayout.SOUTH);
          JButton higher = new JButton( "Deal" );
          higher.addActionListener(board);
          buttonPanel.add(higher);
          JButton newGame = new JButton( "New Game" );
          newGame.addActionListener(board);
          buttonPanel.add(newGame);
       }  // end init()
       class HighLowCanvas extends JPanel implements ActionListener {
            // A nested class that displays the cards and does all the work
             // of keeping track of the state and responding to user events.
          Deck deck;       // A deck of cards to be used in the game.
          Hand hand;       // The cards that have been dealt.
          String message;  // A message drawn on the canvas, which changes
                           //    to reflect the state of the game.
          boolean gameInProgress;  // Set to true when a game begins and to false
                                   //   when the game ends.
          Font bigFont;      // Font that will be used to display the message.
          Font smallFont;    // Font that will be used to draw the cards.
          HighLowCanvas() {
                // Constructor.  Creates sets the foreground and
                // background colors, and starts the first game.
          setBackground( new Color(0,120,0) );
             setForeground( Color.yellow);
                     //  smallFont = new Font("SansSerif", Font.PLAIN, 12);
                      // bigFont = new Font("Serif", Font.BOLD, 14);
            doNewGame();
          } // end constructor
          public void actionPerformed(ActionEvent evt) {
                 // Respond when the user clicks on a button by calling
                 // the appropriate procedure.  Note that the canvas is
                 // registered as a listener in applet's init() method.
             String command = evt.getActionCommand();
             if (command.equals("Deal"))
                doDeal();
             else if (command.equals("New Game"))
                doNewGame();
          } // end actionPerformed()
          void doDeal() {
                   // Called by actionPerformmed() when user clicks "Higher" button.
                   // Check the user's prediction.  Game ends if user guessed
                   // wrong or if the user has made three correct predictions.
             if (gameInProgress == false) {
                   // If the game has ended, it was an error to click "Higher",
                   // So set up an error message and abort processing.
                message = "Click \"New Game\" to start a new game!";
                repaint();
                return;
             hand.addCard( deck.dealCard() );     // Deal a card to the hand.
             int cardCt = hand.getCardCount();
             Card thisCard = hand.getCard( cardCt - 1 );  // Card just dealt.
             Card prevCard = hand.getCard( cardCt - 2 );  // The previous card.
             if ( thisCard.getValue() < prevCard.getValue() ) {
                gameInProgress = false;
                message = "Too bad! You lose.";
             else if ( thisCard.getValue() == prevCard.getValue() ) {
                gameInProgress = false;
                message = "Too bad!  You lose"; // on ties
             else if ( cardCt == 4) {    //CHANGED+++++++++++++++++=
                gameInProgress = false;
               message = "You win! Hurra! ";
             else {
                message = "Got it right!  Try for " + cardCt + " Press  -Deal- ";
             repaint();
          } // end
          void doNewGame() {
                 // Called by the constructor, and called by actionPerformed() if
                 // the use clicks the "New Game" button.  Start a new game.
             if (gameInProgress) {
                     // If the current game is not over, it is an error to try
                     // to start a new game.
                message = "You still have to finish this game! Press   -Deal-";
                repaint();
                return;
             deck = new Deck();   // Create the deck and hand to use for this game.
             hand = new Hand();
             deck.shuffle();
             hand.addCard( deck.dealCard() );  // Deal the first card into the hand.
             message = "Deal your cards";
             gameInProgress = true;
             repaint();
          } // end doNewGame()
          public void paintComponent(Graphics g) {
                // This method draws the message at the bottom of the
                // canvas, and it draws all of the dealt cards spread out
                // across the canvas.  If the game is in progress, an
                // extra card is dealt representing the card to be dealt next.
             super.paintComponent(g);
                  g.setFont(bigFont);
                  g.drawString(message,10,135);
                  g.setFont(smallFont);
             int cardCt = hand.getCardCount();
                  for (int i = 0; i < cardCt; i++)
                        drawCard(g, hand.getCard(i), 10 + i * 90, 10);
             if (gameInProgress)
                drawCard(g, null, 10 + cardCt * 90, 10);
          } // end paintComponent()
          void drawCard(Graphics g, Card card, int x, int y) {
                  // Draws a card as a 80 by 100 rectangle with
                  // upper left corner at (x,y).  The card is drawn
                  // in the graphics context g.  If card is null, then
                  // a face-down card is drawn.  (The cards are
                  // rather primitive.)
             if (card == null) {      // Draw a face-down card
                g.setColor(Color.blue);
                g.fillRect(x,y,80,100);
                g.setColor(Color.white);
                g.drawRect(x+3,y+3,73,93);
                g.drawRect(x+4,y+4,71,91);
             else {
                g.setColor(Color.white);
                g.fillRect(x,y,80,100);
                g.setColor(Color.gray);
                g.drawRect(x,y,79,99);
                g.drawRect(x+1,y+1,77,97);
             if (card.getSuit() == Card.DIAMONDS || card.getSuit() == Card.HEARTS)
                g.setColor(Color.red);
             else
                g.setColor(Color.black);
                g.drawString(card.getValueAsString(), x + 10, y + 30);
                g.drawString("of", x+ 10, y + 50);
                g.drawString(card.getSuitAsString(), x + 10, y + 70);
          } // end drawCard()
       } // end nested class HighLowCanvas
    } // end class HighLowGUI
       An object of class card represents one of the 52 cards in a
       standard deck of playing cards.  Each card has a suit and
       a value.
    public class Card {
        public final static int SPADES = 0,       // Codes for the 4 suits.
                                HEARTS = 1,
                                DIAMONDS = 2,
                                CLUBS = 3;
        public final static int ACE = 1,          // Codes for the non-numeric cards.
                                JACK = 11,        //   Cards 2 through 10 have their
                                QUEEN = 12,       //   numerical values for their codes.
                                KING = 13;
        private final int suit;   // The suit of this card, one of the constants
                                  //    SPADES, HEARTS, DIAMONDS, CLUBS.
        private final int value;  // The value of this card, from 1 to 11.
        public Card(int theValue, int theSuit) {
                // Construct a card with the specified value and suit.
                // Value must be between 1 and 13.  Suit must be between
                // 0 and 3.  If the parameters are outside these ranges,
                // the constructed card object will be invalid.
            value = theValue;
            suit = theSuit;
        public int getSuit() {
                // Return the int that codes for this card's suit.
            return suit;
        public int getValue() {
                // Return the int that codes for this card's value.
            return value;
        public String getSuitAsString() {
                // Return a String representing the card's suit.
                // (If the card's suit is invalid, "??" is returned.)
            switch ( suit ) {
               case SPADES:   return "Spades";
               case HEARTS:   return "Hearts";
               case DIAMONDS: return "Diamonds";
               case CLUBS:    return "Clubs";
               default:       return "??";
        public String getValueAsString() {
                // Return a String representing the card's value.
                // If the card's value is invalid, "??" is returned.
            switch ( value ) {
               case 1:   return "A";
               case 2:   return "2";
               case 3:   return "3";
               case 4:   return "4";
               case 5:   return "5";
               case 6:   return "6";
               case 7:   return "7";
               case 8:   return "8";
               case 9:   return "9";
               case 10:  return "10";
               case 11:  return "J";
               case 12:  return "Q";
               case 13:  return "K";
               default:  return "??";
        public String toString() {
               // Return a String representation of this card, such as
               // "10 of Hearts" or "Queen of Spades".
            return getValueAsString() + " of " + getSuitAsString();
    } // end class Card
        An object of type Deck represents an ordinary deck of 52 playing cards.
        The deck can be shuffled, and cards can be dealt from the deck.
    public class Deck {
        private Card[] deck;   // An array of 52 Cards, representing the deck.
        private int cardsUsed; // How many cards have been dealt from the deck.
        public Deck() {       // Create an unshuffled deck of cards.
           deck = new Card[52];
           int cardCt = 0;    // How many cards have been created so far.
           for ( int suit = 0; suit <= 3; suit++ ) {
              for ( int value = 1; value <= 13; value++ ) {
                 deck[cardCt] = new Card(value,suit);
                 cardCt++;
           cardsUsed = 0;
        public void shuffle() {
              // Put all the used cards back into the deck, and shuffle it into
              // a random order.
            for ( int i = 51; i > 0; i-- ) {
                int rand = (int)(Math.random()*(i+1));
                Card temp = deck;
    deck[i] = deck[rand];
    deck[rand] = temp;
    cardsUsed = 0;
    public int cardsLeft() {
    // As cards are dealt from the deck, the number of cards left
    // decreases. This function returns the number of cards that
    // are still left in the deck.
    return 52 - cardsUsed;
    public Card dealCard() {
    // Deals one card from the deck and returns it.
    if (cardsUsed == 52)
    shuffle();
    cardsUsed++;
    return deck[cardsUsed - 1];
    } // end class Deck
    An object of type Hand represents a hand of cards. The maximum number of
    cards in the hand can be specified in the constructor, but by default
    is 5. A utility function is provided for computing the value of the
    hand in the game of Blackjack.
    import java.util.Vector;
    public class Hand {
    private Vector hand; // The cards in the hand.
    public Hand() {
    // Create a Hand object that is initially empty.
    hand = new Vector();
    public void clear() {
    // Discard all the cards from the hand.
    hand.removeAllElements();
    public void addCard(Card c) {
    // Add the card c to the hand. c should be non-null. (If c is
    // null, nothing is added to the hand.)
    if (c != null)
    hand.addElement(c);
    public void removeCard(Card c) {
    // If the specified card is in the hand, it is removed.
    hand.removeElement(c);
    public void removeCard(int position) {
    // If the specified position is a valid position in the hand,
    // then the card in that position is removed.
    if (position >= 0 && position < hand.size())
    hand.removeElementAt(position);
    public int getCardCount() {
    // Return the number of cards in the hand.
    return hand.size();
    public Card getCard(int position) {
    // Get the card from the hand in given position, where positions
    // are numbered starting from 0. If the specified position is
    // not the position number of a card in the hand, then null
    // is returned.
    if (position >= 0 && position < hand.size())
    return (Card)hand.elementAt(position);
    else
    return null;
    public void sortBySuit() {
    // Sorts the cards in the hand so that cards of the same suit are
    // grouped together, and within a suit the cards are sorted by value.
    // Note that aces are considered to have the lowest value, 1.
    Vector newHand = new Vector();
    while (hand.size() > 0) {
    int pos = 0; // Position of minimal card.
    Card c = (Card)hand.elementAt(0); // Minumal card.
    for (int i = 1; i < hand.size(); i++) {
    Card c1 = (Card)hand.elementAt(i);
    if ( c1.getSuit() < c.getSuit() ||
    (c1.getSuit() == c.getSuit() && c1.getValue() < c.getValue()) ) {
    pos = i;
    c = c1;
    hand.removeElementAt(pos);
    newHand.addElement(c);
    hand = newHand;
    public void sortByValue() {
    // Sorts the cards in the hand so that cards of the same value are
    // grouped together. Cards with the same value are sorted by suit.
    // Note that aces are considered to have the lowest value, 1.
    Vector newHand = new Vector();
    while (hand.size() > 0) {
    int pos = 0; // Position of minimal card.
    Card c = (Card)hand.elementAt(0); // Minumal card.
    for (int i = 1; i < hand.size(); i++) {
    Card c1 = (Card)hand.elementAt(i);
    if ( c1.getValue() < c.getValue() ||
    (c1.getValue() == c.getValue() && c1.getSuit() < c.getSuit()) ) {
    pos = i;
    c = c1;
    hand.removeElementAt(pos);
    newHand.addElement(c);
    hand = newHand;

    Please don't crosspost. It cuts down on the effectiveness of responses, leads to people wasting their time answering what others have already answered, makes for difficult discussion, and is generally just annoying and bad form.

  • A question about ActionListener and MouseListener

    Hi,
    my question here is when we should implement a MouseListener and when we should use ActionListener instead.
    I know ActionEvent is fired when a action performed, for instance, a button was pressed down, but I think by implementing a MouseListener, we can use its mouseClicked(MouseEvent e) method to do the same job as the actionPerformed method.
    So, what's the difference between a actionevent(button has been pressed down)and a mouse event(click on a button)? And when we should use them?

    Using the ActionListener actionCommand is the normal paradigm for button clicks.
    ActionEvents, ChangeEvents etc are much higher-level than MouseEvents. And you should use the highest level of abstraction that provides sufficient specificity.
    When adding MouseListener to an component you actully let the system do more work then needed.
    ( you have the mouseEntered, mousePressed, mouseClicked, mouseReleased, ..)
    Every button click will "generate" three mouse events... pressed, released and clicked.
    good luck!

  • One reason why commandLink doesn't work in dataTable

    Ok, so I think I've got an explanation why commandLink doesn't work in dataTable when the model bean is request scoped. Maybe somebody can tell me if I'm wrong.
    I have a model bean that generates table rows based on some input criteria (request parameters).
    So, we validate the inputs, apply them to the bean and render the page. Once the inputs have been applied to the bean, a request for table rows returns rows, no problem.
    However, we put a commandLink in each row, so we can expand the details. Maybe we even get smart and repeat the input row-generating criteria as a hidden field in the page.
    Unfortunately, when the user hits the commandLink, the list page simply refreshes, maybe even w/out table rows. The user doesn't get the details page as expected.
    Why not?
    Because: in the DECODE phase (even before validation and before "immediate" values have had their valueChangeListeners called), we ask the model bean for the table rows, so we can decode the commandLinks. Unfortunately, in "decode" phase, the request-scoped model bean has not had its row-generating criteria updated (that happens in the "update model" normally, or at the END of the decode phase if we got cute by (1) setting the "immediate" attribute on the row-generating criteria to "true" AND (2) set a valueChangeListener to allow us to update the model bean early. The END of the decode phase isn't good enough -- in the middle of that phase, when we're attempting to deocde commandLinks, the model bean has no citeria, so there's no row data. No row data means no iteration over commandLinks to decode them and queue ActionEvents. So, we march through the rest of the phases, process no events, and return to the screen of origin (the list screen) with no errors.
    So, what's the solution?
    One solution is to make the model bean session-scoped. Fine, maybe we can store a tiny bit of data in it (the search criteria), so it's not such a memory drag to have it live in the session forever. How do we get that data in? A managed property in faces-config.xml with value #{param.PARENT_KEY} won't work because it's assigning request-scoped data to a session-scoped holder. JBoss balks, and rightly so. Do we write code in the model bean that pulls the request parameter out of thin air? (FacesContext.getExternalContext()....) I don't really like to code the name of a specific http request parameter into the bean, I think it's the job of the JSP or faces-config.xml to achieve that binding (request parameter to model propery). Plus, I'd be sad to introduce a dependency on Faces in what was previously just a bean.
    Is there a better way?
    In my particular situation, we're grafting some Faces pages onto an already-existing non-Faces application. I don't get the luxury of presenting the user an input field and binding it to a bean. All I've got to work with is a request parameter.
    Hmm, I guess I just answered my own question. if all I've got to work with is a request parameter, some ugliness is inevitable, I guess.
    I guess the best fix is to cheat and have the bean constructor look for a request parameter. If it finds it, it initializes the criteria field (which, in my case, is the key of an object that has a bunch of associated objects (the rows data), but could be more-general d/b search criteria).
    (I looked at the "repeater" example code in the RI, but it basically statically-generates its data and then uses 100% Faces (of course) to manage the paging (where "page number" is essentially the "criteria").
    Comments? Did I miss something obvious?
    John.

    ...or I could just break down and do the thing I was hoping to avoid (outputLink instead of commandLink):
    <h:outputLink value="/faces/Detail.jsp">
      <f:param name="PARENT_KEY" value="#{bean.parentKey}"/>
      <h:outputText value="#{bean.label}"/>
    </h:outputLink>It's still a "hardcoded" parameter name, but at least the binding is in the JSP and faces-config.xml, not the bean Java code.

  • How do i make Images show ?

    Hello :) I'm writing a simple game but I am having so much trouble with it :( here is the code now all it does right now is it writes out the values of the cards on the screen in an applet however I want it to display card images from http://www.waste.org/~oxymoron/cards
    i can't get it to use the string values and give me the card images instead of text... please help a woman in trouble ;O) thank you
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    //import java.applet.*;
    ///import java.util.*;
    public class HighLowGUI extends JApplet {
    //private HighLowGUI label = new HighLowGUI("Socrates");      // CyberPet
        //private JLabel nameLabel = new JLabel("Hi! My name is ");
        //private TextField stateField = new TextField(12);      // A TextField
       public void init() {
             // The init() method lays out the applet.
             // A HighLowCanvas occupies the CENTER position of the layout.
             // On the bottom is a panel that holds three buttons.  The
             // HighLowCanvas object listens for ActionEvents from the
             // buttons and does all the real work of the program.
          setBackground( new Color(130,50,40) );
          HighLowCanvas board = new HighLowCanvas();
          getContentPane().add(board, BorderLayout.CENTER);
          JPanel buttonPanel = new JPanel();
          buttonPanel.setBackground( new Color(220,200,180) );
          getContentPane().add(buttonPanel, BorderLayout.SOUTH);
          JButton higher = new JButton( "Deal" );
          higher.addActionListener(board);
          buttonPanel.add(higher);
          JButton newGame = new JButton( "New Game" );
          newGame.addActionListener(board);
          buttonPanel.add(newGame);
         // JLabel nameLabel = new JLabel("Hi! My name is ");
       }  // end init()
       class HighLowCanvas extends JPanel implements ActionListener {
             private Image eatImg, eat2Img, sleepImg, happyImg;     // Images for animation
            // A nested class that displays the cards and does all the work
             // of keeping track of the state and responding to user events.
          Deck deck;       // A deck of cards to be used in the game.
          Hand hand;       // The cards that have been dealt.
          String message;  // A message drawn on the canvas, which changes
                           //    to reflect the state of the game.
          boolean gameInProgress;  // Set to true when a game begins and to false
                                   //   when the game ends.
          Font bigFont;      // Font that will be used to display the message.
          Font smallFont;    // Font that will be used to draw the cards.
          HighLowCanvas() {
                // Constructor.  Creates sets the foreground and
                // background colors, and starts the first game.
          setBackground( new Color(0,120,0) );
             setForeground( Color.yellow);
                     //  smallFont = new Font("SansSerif", Font.PLAIN, 12);
                      // bigFont = new Font("Serif", Font.BOLD, 14);
            doNewGame();
          } // end constructor
          public void actionPerformed(ActionEvent evt) {
                 // Respond when the user clicks on a button by calling
                 // the appropriate procedure.  Note that the canvas is
                 // registered as a listener in applet's init() method.
             String command = evt.getActionCommand();
             if (command.equals("Deal"))
                doDeal();
             else if (command.equals("New Game"))
                doNewGame();
          } // end actionPerformed()
          void doDeal() {
                   // Called by actionPerformmed() when user clicks "Higher" button.
                   // Check the user's prediction.  Game ends if user guessed
                   // wrong or if the user has made three correct predictions.
             if (gameInProgress == false) {
                   // If the game has ended, it was an error to click "Higher",
                   // So set up an error message and abort processing.
                message = "Click \"New Game\" to start a new game!";
                repaint();
                return;
             hand.addCard( deck.dealCard() );     // Deal a card to the hand.
             int cardCt = hand.getCardCount();
             Card thisCard = hand.getCard( cardCt - 1 );  // Card just dealt.
             Card prevCard = hand.getCard( cardCt - 2 );  // The previous card.
             if ( thisCard.getValue() < prevCard.getValue() ) {
                gameInProgress = false;
                message = "Too bad! You lose.";
             else if ( thisCard.getValue() == prevCard.getValue() ) {
                gameInProgress = false;
                message = "Too bad!  You lose"; // on ties
             else if ( cardCt == 4) {    //CHANGED+++++++++++++++++=
                gameInProgress = false;
               message = "You win! Hurra! ";
             else {
                message = "Got it right!  Try for " + cardCt + " Press  -Deal- ";
             repaint();
          } // end
          void doNewGame() {
                 // Called by the constructor, and called by actionPerformed() if
                 // the use clicks the "New Game" button.  Start a new game.
             if (gameInProgress) {
                     // If the current game is not over, it is an error to try
                     // to start a new game.
                message = "You still have to finish this game! Press   -Deal-";
                repaint();
                return;
             deck = new Deck();   // Create the deck and hand to use for this game.
             hand = new Hand();
             deck.shuffle();
             hand.addCard( deck.dealCard() );  // Deal the first card into the hand.
             message = "Deal your cards";
             gameInProgress = true;
             repaint();
          } // end doNewGame()
          public void paintComponent(Graphics g) {
                // This method draws the message at the bottom of the
                // canvas, and it draws all of the dealt cards spread out
                // across the canvas.  If the game is in progress, an
                // extra card is dealt representing the card to be dealt next.
             super.paintComponent(g);
                  g.setFont(bigFont);
                  g.drawString(message,10,135);
                  g.setFont(smallFont);
             int cardCt = hand.getCardCount();
                  for (int i = 0; i < cardCt; i++)
                        drawCard(g, hand.getCard(i), 10 + i * 90, 10);
             if (gameInProgress)
                drawCard(g, null, 10 + cardCt * 90, 10);
          } // end paintComponent()
          void drawCard(Graphics g, Card card, int x, int y) {
                  // Draws a card as a 80 by 100 rectangle with
                  // upper left corner at (x,y).  The card is drawn
                  // in the graphics context g.  If card is null, then
                  // a face-down card is drawn.  (The cards are
                  // rather primitive.)
             if (card == null) {      // Draw a face-down card
                g.setColor(Color.blue);
                g.fillRect(x,y,80,100);
                g.setColor(Color.white);
                g.drawRect(x+3,y+3,73,93);
                g.drawRect(x+4,y+4,71,91);
             else {
                g.setColor(Color.white);
                g.fillRect(x,y,80,100);
                g.setColor(Color.gray);
                g.drawRect(x,y,79,99);
                g.drawRect(x+1,y+1,77,97);
             if (card.getSuit() == Card.DIAMONDS || card.getSuit() == Card.HEARTS)
                g.setColor(Color.red);
             else
                g.setColor(Color.black);
                g.drawString(card.getValueAsString(), x + 10, y + 30);
                g.drawString("of", x+ 10, y + 50);
                g.drawString(card.getSuitAsString(), x + 10, y + 70);
          } // end drawCard()
       } // end nested class HighLowCanvas
    } // end class HighLowGUI
       An object of class card represents one of the 52 cards in a
       standard deck of playing cards.  Each card has a suit and
       a value.
    public class Card {
        public final static int SPADES = 0,       // Codes for the 4 suits.
                                HEARTS = 1,
                                DIAMONDS = 2,
                                CLUBS = 3;
        public final static int ACE = 1,          // Codes for the non-numeric cards.
                                JACK = 11,        //   Cards 2 through 10 have their
                                QUEEN = 12,       //   numerical values for their codes.
                                KING = 13;
        private final int suit;   // The suit of this card, one of the constants
                                  //    SPADES, HEARTS, DIAMONDS, CLUBS.
        private final int value;  // The value of this card, from 1 to 11.
        public Card(int theValue, int theSuit) {
                // Construct a card with the specified value and suit.
                // Value must be between 1 and 13.  Suit must be between
                // 0 and 3.  If the parameters are outside these ranges,
                // the constructed card object will be invalid.
            value = theValue;
            suit = theSuit;
        public int getSuit() {
                // Return the int that codes for this card's suit.
            return suit;
        public int getValue() {
                // Return the int that codes for this card's value.
            return value;
        public String getSuitAsString() {
                // Return a String representing the card's suit.
                // (If the card's suit is invalid, "??" is returned.)
            switch ( suit ) {
               case SPADES:   return "Spades";
               case HEARTS:   return "Hearts";
               case DIAMONDS: return "Diamonds";
               case CLUBS:    return "Clubs";
               default:       return "??";
        public String getValueAsString() {
                // Return a String representing the card's value.
                // If the card's value is invalid, "??" is returned.
            switch ( value ) {
               case 1:   return "A";
               case 2:   return "2";
               case 3:   return "3";
               case 4:   return "4";
               case 5:   return "5";
               case 6:   return "6";
               case 7:   return "7";
               case 8:   return "8";
               case 9:   return "9";
               case 10:  return "10";
               case 11:  return "J";
               case 12:  return "Q";
               case 13:  return "K";
               default:  return "??";
        public String toString() {
               // Return a String representation of this card, such as
               // "10 of Hearts" or "Queen of Spades".
            //return ""+"
            return getValueAsString() + " of " + getSuitAsString();
    } // end class Card
        An object of type Deck represents an ordinary deck of 52 playing cards.
        The deck can be shuffled, and cards can be dealt from the deck.
    public class Deck {
        private Card[] deck;   // An array of 52 Cards, representing the deck.
        private int cardsUsed; // How many cards have been dealt from the deck.
        public Deck() {       // Create an unshuffled deck of cards.
           deck = new Card[52];
           int cardCt = 0;    // How many cards have been created so far.
           for ( int suit = 0; suit <= 3; suit++ ) {
              for ( int value = 1; value <= 13; value++ ) {
                 deck[cardCt] = new Card(value,suit);
                 cardCt++;
           cardsUsed = 0;
        public void shuffle() {
              // Put all the used cards back into the deck, and shuffle it into
              // a random order.
            for ( int i = 51; i > 0; i-- ) {
                int rand = (int)(Math.random()*(i+1));
                Card temp = deck;
    deck[i] = deck[rand];
    deck[rand] = temp;
    cardsUsed = 0;
    public int cardsLeft() {
    // As cards are dealt from the deck, the number of cards left
    // decreases. This function returns the number of cards that
    // are still left in the deck.
    return 52 - cardsUsed;
    public Card dealCard() {
    // Deals one card from the deck and returns it.
    if (cardsUsed == 52)
    shuffle();
    cardsUsed++;
    return deck[cardsUsed - 1];
    } // end class Deck
    An object of type Hand represents a hand of cards. The maximum number of
    cards in the hand can be specified in the constructor, but by default
    is 5. A utility function is provided for computing the value of the
    hand in the game of Blackjack.
    import java.util.Vector;
    public class Hand {
    private Vector hand; // The cards in the hand.
    public Hand() {
    // Create a Hand object that is initially empty.
    hand = new Vector();
    public void clear() {
    // Discard all the cards from the hand.
    hand.removeAllElements();
    public void addCard(Card c) {
    // Add the card c to the hand. c should be non-null. (If c is
    // null, nothing is added to the hand.)
    if (c != null)
    hand.addElement(c);
    public void removeCard(Card c) {
    // If the specified card is in the hand, it is removed.
    hand.removeElement(c);
    public void removeCard(int position) {
    // If the specified position is a valid position in the hand,
    // then the card in that position is removed.
    if (position >= 0 && position < hand.size())
    hand.removeElementAt(position);
    public int getCardCount() {
    // Return the number of cards in the hand.
    return hand.size();
    public Card getCard(int position) {
    // Get the card from the hand in given position, where positions
    // are numbered starting from 0. If the specified position is
    // not the position number of a card in the hand, then null
    // is returned.
    if (position >= 0 && position < hand.size())
    return (Card)hand.elementAt(position);
    else
    return null;
    public void sortBySuit() {
    // Sorts the cards in the hand so that cards of the same suit are
    // grouped together, and within a suit the cards are sorted by value.
    // Note that aces are considered to have the lowest value, 1.
    Vector newHand = new Vector();
    while (hand.size() > 0) {
    int pos = 0; // Position of minimal card.
    Card c = (Card)hand.elementAt(0); // Minumal card.
    for (int i = 1; i < hand.size(); i++) {
    Card c1 = (Card)hand.elementAt(i);
    if ( c1.getSuit() < c.getSuit() ||
    (c1.getSuit() == c.getSuit() && c1.getValue() < c.getValue()) ) {
    pos = i;
    c = c1;
    hand.removeElementAt(pos);
    newHand.addElement(c);
    hand = newHand;
    public void sortByValue() {
    // Sorts the cards in the hand so that cards of the same value are
    // grouped together. Cards with the same value are sorted by suit.
    // Note that aces are considered to have the lowest value, 1.
    Vector newHand = new Vector();
    while (hand.size() > 0) {
    int pos = 0; // Position of minimal card.
    Card c = (Card)hand.elementAt(0); // Minumal card.
    for (int i = 1; i < hand.size(); i++) {
    Card c1 = (Card)hand.elementAt(i);
    if ( c1.getValue() < c.getValue() ||
    (c1.getValue() == c.getValue() && c1.getSuit() < c.getSuit()) ) {
    pos = i;
    c = c1;
    hand.removeElementAt(pos);
    newHand.addElement(c);
    hand = newHand;

    Please don't crosspost. It cuts down on the effectiveness of responses, leads to people wasting their time answering what others have already answered, makes for difficult discussion, and is generally just annoying and bad form.

  • Class, interface, or enum expected error

    import java.awt.Graphics;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class InventoryFinal
    //main method begins execution of java application
    public static void main(final String args[])
    int i; // varialbe for looping
    double total = 0; // variable for total inventory
    final int dispProd = 0; // variable for actionEvents
    // Instantiate a product object
    final ProductAdd[] nwProduct = new ProductAdd[5];
    // Instantiate objects for the array
    for (i=0; i<5; i++)
    nwProduct[0] = new ProductAdd("CD", 10, 18, 12.00, "Jewel Case");
    nwProduct[1] = new ProductAdd("Blue Ray", 9, 20, 25.00, "HD");
    nwProduct[2] = new ProductAdd("Game", 8, 30, 40.00, "Game Case");
    nwProduct[3] = new ProductAdd("iPod", 7, 40, 50.00, "Box");
    nwProduct[4] = new ProductAdd("DVD", 6, 15, 15.00, "DVD Case");
    for (i=0; i<5; i++)
    total += nwProduct.length; // calculate total inventory cost
    final JButton firstBtn = new JButton("First"); // first button
    final JButton prevBtn = new JButton("Previous"); // previous button
    final JButton nextBtn = new JButton("Next"); // next button
    final JButton lastBtn = new JButton("Last"); // last button
    final JButton AddBtn = new JButton("Add"); // Add button
    final JButton DeleteBtn = new JButton("Delete"); // Delete button
    final JButton ModifyBtn = new JButton("Modify"); // Modify button
    final JButton SaveBtn = new JButton("Save"); // Save button
    final JButton SearchBtn = new JButton("Search"); // Search button
    final JLabel label; // logo
    final JTextArea textArea; // text area for product list
    final JPanel buttonJPanel; // panel to hold buttons
    //JLabel constructor for logo
    Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
    label = new JLabel(logo); // create logo label
    label.setToolTipText("Company Logo"); // create tooltip
    buttonJPanel = new MyJPanel(); // set up panel
    buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
    // add buttons to buttonPanel
    buttonJPanel.add(firstBtn);
    buttonJPanel.add(prevBtn);
    buttonJPanel.add(nextBtn);
    buttonJPanel.add(lastBtn);
    buttonJPanel.add(AddBtn);
    buttonJPanel.add(DeleteBtn);
    buttonJPanel.add(ModifyBtn);
    buttonJPanel.add(SaveBtn);
    buttonJPanel.add(SearchBtn);
    textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
    // add total inventory value to GUI
    textArea.append("/nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
    textArea.setEditable(false); // make text uneditable in main display
    JFrame invFrame = new JFrame(); // create JFrame container
    invFrame.setLayout(new BorderLayout()); // set layout
    invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
    invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
    invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
    invFrame.setTitle("CD & DVD Inventory"); // set JFrame title
    invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
    //invFrame.pack();
    invFrame.setSize(600, 600); // set size of JPanel
    invFrame.setLocationRelativeTo(null); // set screen location
    invFrame.setVisible(true); // display window
    // assign actionListener and actionEvent for each button
    firstBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end firstBtn actionEvent
    }); // end firstBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    prevBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[4]+"\n");
    } // end prevBtn actionEvent
    }); // end prevBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    nextBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[2]+"\n");
    } // end nextBtn actionEvent
    }); // end nextBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    lastBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[3]+"\n");
    } // end lastBtn actionEvent
    }); // end lastBtn actionListener
    textArea.setText(nwProduct[4]+"n");// assign actionListener and actionEvent for each button
    AddBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end AddBtn actionEvent
    }); // end AddBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    DeleteBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end DeleteBtn actionEvent
    }); // end DeleteBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    ModifyBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end ModifyBtn actionEvent
    }); // end ModifyBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    SaveBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end SaveBtn actionEvent
    }); // end SaveBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    SearchBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end SearchBtn actionEvent
    }); // end SearchBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // prevBtn.addActionListener(new ActionListener()
    // public void actionPerformed(ActionEvent ae)
    // dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
    // textArea.setText(nwProduct.display(dispProd)+"\n");
    // } // end prevBtn actionEvent
    // }); // end prevBtn actionListener
    } // end main
    } // end class Inventory4
    class Product
    protected String prodName; // name of product
    protected int itmNumber; // item number
    protected int units; // number of units
    protected double price; // price of each unit
    protected double value; // value of total units
    public Product(String name, int number, int unit, double each) // Constructor for class Product
    prodName = name;
    itmNumber = number;
    units = unit;
    price = each;
    } // end constructor
    public void setProdName(String name) // method to set product name
    prodName = name;
    public String getProdName() // method to get product name
    return prodName;
    public void setItmNumber(int number) // method to set item number
    itmNumber = number;
    public int getItmNumber() // method to get item number
    return itmNumber;
    public void setUnits(int unit) // method to set number of units
    units = unit;
    public int getUnits() // method to get number of units
    return units;
    public void setPrice(double each) // method to set price
    price = each;
    public double getPrice() // method to get price
    return price;
    public double calcValue() // method to set value
    return units * price;
    } // end class Product
    class ProductAdd extends Product
    private String feature; // variable for added feature
    public ProductAdd(String name, int number, int unit, double each, String addFeat)
    // call to superclass Product constructor
    super(name, number, unit, each);
    feature = addFeat;
    }// end constructor
    public void setFeature(String addFeat) // method to set added feature
    feature = addFeat;
    public String getFeature() // method to get added feature
    return feature;
    public double calcValueRstk() // method to set value and add restock fee
    return units * price * 0.10;
    public String toString()
    return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n",
    getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
    } // end class ProductAdd
    class MyJPanel extends JPanel
    //private static Random generator = new Random();
    private ImageIcon picture; //image to be displayed
    // load image
    public MyJPanel()
    picture = new ImageIcon("mypicture.png"); // set icon
    } // end MyJPanel constructor
    // display imageIcon on panel
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    picture.paintIcon( this, g, 0, 0 ); // display icon
    } // end method paintComponent
    // return image dimensions
    //public Dimension getPreferredSize()
    // return new Dimension ( picture.getIconWidth(),
    //picture.getIconHeight() );
    } // end method getPreferredSize
    } // end class MyJPanel
    import java.io.File;
    import java.io.IOException;
    public class FileAccessDemo
    public static void main( String[] args ) throws IOException
    // declare variables
    String formatStr = "%s exists in %s? %b\n\n";
    // processing and output
    File file1 = new File( "studentScores.txt" ); // create a File object
    System.out.printf
    (formatStr, file1.getName(), file1.getAbsolutePath(), file1.exists());
    // processing and output
    File folder1 = new File( "c:/personnel/" ); // create a File object
    folder1.mkdir(); // make a directory
    File file2 = new File( "/personnel/faculty.txt" );
    file2.createNewFile(); // create a new file
    System.out.printf
    ( formatStr, file2.getName(), file2.getAbsolutePath(), file2.exists() );
    // processing and output
    file2.delete(); // delete a file, but not the directory
    System.out.printf
    ( formatStr, file2.getName(), file2.getAbsolutePath(), file2.exists() );
    } // end main
    } // end class
    I need help in resolving this error.
    Thanks

    That code isn't where your error is. Here's the errors I get compiling your code:
    H:\java>javac InventoryFinal.java
    InventoryFinal.java:78: ')' expected
    textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n
                                                 ^
    InventoryFinal.java:78: ';' expected
    textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n
                                                                                                   ^
    InventoryFinal.java:340: class, interface, or enum expected
    import java.io.File;
    ^
    InventoryFinal.java:341: class, interface, or enum expected
    import java.io.IOException;
    ^
    4 errorsThe last two errors are on your import statements, which can't be in the middle of a source file. The first two are on this line:
    textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n");Which certainly isn't a legal line of Java code. If you want to connect multiple Strings you need to use the "+" operator.

Maybe you are looking for