Implementing ActionListener & MouseListener

Hello all!!
I was just wondering, is it possible to implement both an ActionListener and a MouseListener into one class? ex:
public class NAME extends JFrame implements ActionListener implements MouseListener
//etc
I have a program that relies heavily on MouseListener that I want to add a JMenu to, but I need ActionListener to do that... so, is it possible and I only have the wrong code? Or do I have to work around that somehow?
Thank you so much for your help!
Blessings,
Sarah

public class Name extends JFrame implements ActionListener, MouseListener

Similar Messages

  • ActionListener & MouseListener applet

    Hi, i have an applet which determines where the user clicks the mouse within the applet and displays coordinates in the status bar
         public void mouseClicked(MouseEvent e)
                //get coordinates of click
                mousex=e.getX(); mousey=e.getY();
                paint(getGraphics());
                repaint();
           public void paint(Graphics g)
            //Draw location pointer on map
         g.setColor(Color.black);
            g.fillOval(mousex-2,mousey-2,4,4);
            showStatus("You clicked at ("+mousex+ ","+mousey+")");
           }I also have a textfield which allows the user to type in a search term. Then in the actionPerformed() method, a for loop gets the text from the textfield and compares it to an array of keywords; if a match is found then a corresponding message is printed on the screen.
         public void actionPerformed(ActionEvent e)
              if(e.getSource()==text)
                   textStr=e.getActionCommand();   //Possibly use getText?
                   for (int i =0;i<items.length;i++)
                        if (items.equals(textStr))
                        dataString = data[i];break;
                        else
                             dataString = ("Sorry, No information for " + textStr);
    My problem is this: when the mouse click functionality above is enabled, the textfield will not accept any input from the keyboard. If i comment the mouse code out then the textfield works as it should.
    Any suggestions/ideas appreciated.
    Many thanks.
    Joe.

    what do you mean by it is not working?
    what happen when you dont comment out any part of your code andyou click on your applet?
    try to separate the graphics part and the t textfield
    is your applet implementing actionlistener?
    if so change your code
    and add a textfield in your applet and then make the textfield implements actionlistener
    it should work fine

  • How do i create a static function in a class and implement ActionListener?

    i am trying to create a pop up dialog box in a seperate class.
    and i want to make the Function static, so that i only need to access it with the class name.
    But how do i have a ActionListener ?
    everything in a static function is static rite?

    import java.awt.*;
    import java.awt.event.*;
    public class StaticFunction
        Dialog dialog;
        private Panel getUIPanel()
            Button button = new Button("show dialog");
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    if(dialog == null)
                        dialog = OutsideUtility.showDialog("hello world");
                    else if(!dialog.isVisible())
                        dialog.setVisible(true);
                    else if(dialog.isVisible())
                        dialog.dispose();
                        dialog = null;
            Panel panel = new Panel();
            panel.add(button);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        public static void main(String[] args)
            StaticFunction sf = new StaticFunction();
            Frame f = new Frame();
            f.addWindowListener(sf.closer);
            f.add(sf.getUIPanel());
            f.setSize(200,100);
            f.setLocation(200,200);
            f.setVisible(true);
    class OutsideUtility
        public static Dialog showDialog(String msg)
            Button button = new Button("top button");
            button.setActionCommand(msg);
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    Button button = (Button)e.getSource();
                    System.out.println(button.getActionCommand() +
                                       " from anonymous inner listener");
            button.addActionListener(new ButtonListener());
            Button anotherButton = new Button("bottom button");
            anotherButton.setActionCommand("another button");
            anotherButton.addActionListener(localListener);
            Panel north = new Panel();
            north.add(button);
            Panel south = new Panel();
            south.add(anotherButton);
            Dialog dialog = new Dialog(new Frame());
            dialog.addWindowListener(closer);
            dialog.add(north, "North");
            dialog.add(new Label(msg, Label.CENTER));
            dialog.add(south, "South");
            dialog.setSize(200,200);
            dialog.setLocation(425,200);
            dialog.setVisible(true);
            return dialog;
        private static WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                Dialog dialog = (Dialog)e.getSource();
                dialog.dispose();
        private static ActionListener localListener = new ActionListener()
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                System.out.println(button.getActionCommand() +
                                   " from localListener");
        private static class ButtonListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                String ac = button.getActionCommand();
                System.out.println(ac + " from ButtonListener");
    }

  • Implementing ActionListener

    when i put this line in public class guess extends JApplet implements ActionListenerit says guess must be declared abstract...why cant it be public?
    is there a way to implement the ActionListener just later on in the applet?

    and read your damned error messages.
    it said
    guess should be declared abstract; it does not define actionPerformed(java.awt.event.ActionEvent) in guess{
    public class guess implements ActionListener{
    what does that say?
    oh, it does not define actionPerformed(java.awt.event.ActionEvent)
    so define actionPerformed(java.awt.event.ActionEvent)
    like this
    actionPerformed(java.awt.event.ActionEvent event){
        //whatever you wanna do, probably nothing

  • What is wrong wiith:  JFrame that also implements ActionListener

    I got this as a reaction for a question
    Having a JFrame that also implements ActionListener
    is already a code smell, IMOCan someone explain me this.

    If you've got one ActionListener for the frame
    it's fine.This how I make the buttons for each button I make a new KnopHandler
    So this is not good
    This is the way I read in my book a couple of years ago at school.
            importdatafile.setBounds(520,230,195,25);
         importdatafile.addActionListener( new importdatafileKnopHandler() );
         importdata.setBounds(520,260,195,25);
         importdata.addActionListener( new importdataKnopHandler() );
            copy.setBounds(520,310,195,25);
         copy.addActionListener( new copyKnopHandler() );
            insertrow.setBounds(520,340,195,25);
         insertrow.addActionListener( new insertrowKnopHandler() );
             delete.setBounds(520,370,195,25);
         delete.addActionListener( new deleteKnopHandler() );
            senddata.setBounds(520,420,195,25);
         senddata.addActionListener( new senddataKnopHandler() );
         senddatafile.setBounds(520,450,195,25);
         senddatafile.addActionListener( new senddatafileKnopHandler() );
    class printtKnopHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         printt = true;
         GUI();
    class insertrowKnopHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         insertroww = true;
         GUI();
    class senddataKnopHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         sendverbdata = true;
         GUI();
    class senddatafileKnopHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         sendverbfile = true;
         GUI();
         }

  • How I can implement actionlistener

    I want to implement the actionlistener in this program to get an action
    when I press a button I have tried but I get compiler errors
    can someone help me?
    import java.awt .*;
    import javax.swing.*;
    import java.awt.event.ActionEvent.*;
    public class sanna extends JApplet {
    public sanna() {
    Container contentPane= getContentPane();
    JButton ok=new JButton( "return" );
    public void
    JButton enter=new JButton( "search" );
    ok.setBackground(Color.pink);
    ok.setForeground(Color.white);
    JFrame frame=new JFrame("ELHADI ");
    enter.setMaximumSize(new Dimension(100,
    900));
    enter.setForeground(Color.blue);
    contentPane.setBackground( Color.blue);
    for(int i=0;i<10;i++){
    JButton rami=new JButton( "" +i );
    contentPane.add(rami);
    rami.setBackground(Color.blue);}
    contentPane.add(ok);
    JPanel panel=new JPanel(new BorderLayout(500,500) );
    contentPane.setLayout(new FlowLayout( ));
    contentPane.add(panel);
    panel.setBackground( Color.blue );
    panel.add(enter, BorderLayout.PAGE_START);
    panel.add(ok, BorderLayout .PAGE_START);
    panel.setBackground( Color.red );
    Color red=new Color(50,50,50);
    setVisible(true);}
    public static void main (String [] args){
    sanna van=new sanna();
    }}

    Use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    [url http://java.sun.com/docs/books/tutorial/uiswing/events/actionlistener.html]How to Write an Action Listener
    [url http://java.sun.com/docs/books/tutorial/uiswing/components/button.html]How to Use Buttons

  • ActionListener&MouseListener add to Drawing Object in JApplet

    hi,guys
    When I am doing my JApplet, I wanna add the ActionListener and MouseListener to the Drawing Object...
    Like this:
    Graphics2D g11 = (Graphics2D)g;
    g11.setColor(Color.orange);
    g11.fillOval(10,300, 100, 40);
    g11.setColor(Color.darkGray);
    g11.drawString(""+firstpro,30,325); //first protein object
    g11 is the object, and now I wanna add both ActionListener and MouseListener on it.. that means if I click g11 area in my JApplet, it will do certain actions like open another URL page, and send a String from applet to that page also...
    Does is possible to achieve?? If it does, how do I add the source code??
    Hope you guys could kindly help me with some sample code...Thanks a lot!!
    SD

    I don't believe the Graphics derived objects have any support for the Component derived stuff. But you can certainly add these listeners to whichever Component contains your graphics. If you want them to respond only if they are over a drawn part of the component, thats up to you application code as its the only thing that knows where the drawing ends.

  • MyClass extends JPanel implements ActionListener (is that possible?)

    I have tried the above and it doesn't allow me to addActionListener(this) in the constructor, which I usually do with JButtons, so I don't know what to do? I can always do the mouseListener but the ActionListener is more of what I want... Is there a way around that or a suggestion you could offer?

    I have tried the above and it doesn't allow me to
    addActionListener(this) in the constructor, which I
    usually do with JButtons, so I don't know what to do?
    I can always do the mouseListener but the
    ActionListener is more of what I want... Is there a
    way around that or a suggestion you could offer?You're calling addActionListener(this); , right?
    If so, what you're essentially doing is adding the object itself as its own ActionListener!
    I'm not sure if this is illegal.. ??
    And anyway, JPanel does not have the method addActionListener(someActionListener);It looks like this is the main problem.
    is it?
    regards :o)
    lutha

  • Implementing ActionListener in inner class

    Hi
    I'm trying to add an action listener to a button. When i add the new actionlistener i create an anonymous non static inner class at the same time, which has a actionPerfomed(ActionEvent e) method. My checkString() method is in another package, Validate, which i have imported.
    When i try to run the program, i get the following error message:
    GUI/MyGraphics.java [74:1] non-static method checkString(java.lang.String) cannot be referenced from a static context
    boolean textOk = Validator.checkString(userInput);
    ^
    The problem is do with the face that the compiler sees actionPerfomed(ActionEvent e) as a static method/context. How is it static?
    (when i preview my code, it loses all it's indentation. how can i fix this?)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import Interfaces.*;
    import Validate.*;
    public class MyGraphics
        public void startGui()
            JFrame f = new JFrame("Greetings!");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container c = f.getContentPane();
            JLabel lblTop = new JLabel("Who are you? Please enter your                             .       name...");
            c.add(lblTop, BorderLayout.NORTH);
            final JLabel lblResponse = new JLabel();
            c.add(lblResponse, BorderLayout.SOUTH);
            final JLabel lblResponse2 = new JLabel();
            c.add(lblResponse2, BorderLayout.EAST);
            final TextField tfOne = new TextField("My name is...", 50);
            c.add(tfOne, BorderLayout.CENTER);
            JPanel jp = new JPanel();
            JButton Bok = new JButton("Ok");
            jp.add(Bok);
            JButton Bbye = new JButton("Bye!");
            jp.add(Bbye);
            c.add(jp, BorderLayout.SOUTH);
            f.pack();
            f.show();  
            Bok.addActionListener(new ActionListener(){    
            public void actionPerformed(ActionEvent e)
                try
                    String userInput = tfOne.getText();
                    boolean textOk = Validator.checkString(userInput);
                        if(textOk == true)
                            lblResponse.setText("You Have Success!");
                        else
                            lblResponse.setText("Sorry, No Success.");
                catch (Exception a)
                    lblResponse.setText("ERROR! You must enter a valid   value");
    }

    thank you, that is exactly what i needed.
    also, i don't know how to keep my code indentation. i type it in the text field with proper indents but when i preview it, it loses all formatting. how can i prevent this happening?

  • Implements ActionListener , Runnable

    hi......i want to ask about this :
    public void run() {
                 while (runner != null && pindahrun) {
                      //repaint();
                      try {
                         Thread.sleep( 50 );
                     } catch ( InterruptedException e ) {
                         // do nothing
                     ubahkolomcr(Long.parseLong(tcre.getText())+1);
                     labs[pindahkotak].setText(""+(Long.parseLong(labs[pindahkotak].getText())-1));
                     if(Long.parseLong(labs[pindahkotak].getText())==0) {
                          pindahkotak = -1;
                          pindahrun = false;
             }when "run" is running,why i cannot click any button at my application.but when "run" is finished,i can click it.
    what should i do,so when "run" is running,i can click the button ?
    anybody can help me ?
    thanks.

    this is my code :
    CLASS1:
    public static void main(String[] args){
         final JFrame appp = new JFrame("test");
         appp.setSize(800,300);
         final class2 m = new class2();
         m.init();
         m.start();
         appp.add(m,BorderLayout.CENTER);
         appp.setVisible(true);
         appp.setLocationRelativeTo(null);
    CLASS2 :
    //init just to add button,so i dont post it again.
    Thread runner = null;
    public void start() {
           if ( runner == null ) {
               runner = new Thread( this );
               runner.start();
    public void stop() {
            if ( runner != null && runner.isAlive() )
                runner.stop();
             runner = null;
    public void run() {
           while (pindahrun) {
               labs[pindahkotak].setText(""+i);
    public void paint(){
         if(pindahrun) this.run();
    public void actionPerformed(ActionEvent e) {
         Object com = e.getSource();
         if(com.equals(test1)) {
              pindahrun = true;
              repaint();
         if(com.equals(skip)) {
                  if(pindahrun){
                       pindahrun = false;
    }

  • Calling an implemented method from an external class.

    Hey guys...
    I'm writing a package to be put into a program I'm writing for a project (for Uni), but I also want to use the package in other programs.
    Basically, the package will return a JScrollPane that can be put into any JFrame or JPanel or whatever.
    It draws boxes on the JScrollPane in different colours and locations depending on what information is passed to it (kind of like iCal or Microsoft Outlook Calendar), and is to be used for a Resource Allocation Program that requires drag and drop of boxes for moving bookings around etc.
    http://www.pixel2.com.au/ethos/class_diagram.png
    This is a copy of the class diagram for the relevant classes. ViewFrame is the class that instantiates the JScrollPane (AllocationTable). It implements the AllocationInterface to implement methods such as moveAllocation() newAllocation() etc.
    BookingPanel is the content pane for the JScrollPane. AllocatedBox is the individual bookings, or boxes that are painted onto the BookingPanel.
    BookingPanel implements ActionListener, MouseListener and MouseMotionListener, which enables drag and drop functionality.
    What I want to do, is when mouseReleased() is called by dropping a box, call the method moveAllocation() in ViewFrame to make the changes to the database to move the booking around.
    I don't know how to access that from BookingPanel as the name of ViewFrame will change obviously for different programs.
    If you could help me out, that would be great!
    If you need anything else explained, please let me know.
    Thanks,
    Ryan.

    LeRyan wrote:
    Hey guys...
    I'm writing a package to be put into a program I'm writing for a project (for Uni), but I also want to use the package in other programs.
    Basically, the package will return a JScrollPane that can be put into any JFrame or JPanel or whatever.I think you have some terminology issues that might stand in your way of getting help or understanding the issues. A Package is a grouping of classes, so a package doesn't return anything...
    It draws boxes on the JScrollPane in different colours and locations depending on what information is passed to it (kind of like iCal or Microsoft Outlook Calendar), and is to be used for a Resource Allocation Program that requires drag and drop of boxes for moving bookings around etc.So from your description of the function of this thing, I think you mean a class - some sort of JComponent?
    >
    http://www.pixel2.com.au/ethos/class_diagram.png
    This is a copy of the class diagram for the relevant classes. ViewFrame is the class that instantiates the JScrollPane (AllocationTable). It implements the AllocationInterface to implement methods such as moveAllocation() newAllocation() etc.
    BookingPanel is the content pane for the JScrollPane. AllocatedBox is the individual bookings, or boxes that are painted onto the BookingPanel.
    BookingPanel implements ActionListener, MouseListener and MouseMotionListener, which enables drag and drop functionality.
    What I want to do, is when mouseReleased() is called by dropping a box, call the method moveAllocation() in ViewFrame to make the changes to the database to move the booking around.
    I don't know how to access that from BookingPanel as the name of ViewFrame will change obviously for different programs.
    If I follow, and I am not sure that I do - you want a reference to the ViewFrame in the BookingPanel. So either on construction of the BookingPanel via a parameter in the constructor, or as a separate step via a setter, place a reference to the ViewFrame in BookingPanel. Then when you call mouseReleased you can call moveAllocation through that reference.
    If you could help me out, that would be great!
    If you need anything else explained, please let me know.
    Thanks,
    Ryan.

  • Huge problem with implements

    Okay so about an hour ago this worked, but now it isn't can anyone tell me what I'm doing wrong? the problem is in the +,+ area.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestFrame extends JFrame implements ActionListener +,+ MouseListener {
         public TestFrame() {
              super("Java Scatter Graph");
              setSize(800, 800);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              FlowLayout flo = new FlowLayout(FlowLayout.RIGHT, 10, 10);
              setLayout(flo);
                   JButton go = new JButton ("Go");
                   JButton pause = new JButton ("Pause");
                   JButton stop = new JButton ("Stop");
                        add(go);
                        add(stop);
                        add(pause);
                        setVisible(true);
              public static void main(String[] args) {
                   TestFrame sal = new TestFrame();
    }

    about an hour ago in the command prompt it worked and it brought up the window, but now in the fourth line between the ActionListener and the MouseListener there is that little carrot thingy and no matter what I do it doesn't fix the problem. It is really frusterating because it worked about 60 minutes ago.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestFrame extends JFrame implements ActionListener +,+ MouseListener {
         public TestFrame() {
              super("Java Scatter Graph");
              setSize(800, 800);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              FlowLayout flo = new FlowLayout(FlowLayout.RIGHT, 10, 10);
              setLayout(flo);
                   JButton go = new JButton ("Go");
                   JButton pause = new JButton ("Pause");
                   JButton stop = new JButton ("Stop");
                        add(go);
                        add(stop);
                        add(pause);
                        setVisible(true);
              public static void main(String[] args) {
                   TestFrame sal = new TestFrame();
    }

  • Following code is not working

    hi all
    following is code which compile well but didnt show any output, could any genious help me out of this problem.
    i will be veryyyyyyyyyyyyyyyyy thankful to all
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GoMoku1 extends JFrame{
    JButton newGameButton; // Button for starting a new game.
    JButton resignButton; // Button that a player can use to end the
    // game by resigning.
    JLabel message; // Label for displaying messages to the user.
    public void GoMoku1() {
    Container content = getContentPane(); // Content pane of applet.
    content.setLayout(null); // I will do the layout myself.
    content.setBackground(new Color(0,150,0)); // Dark green background.
    Board board = new Board(); // Note: The constructor for the
    // board also creates the buttons
    // and label.
    content.add(board);
    content.add(newGameButton);
    content.add(resignButton);
    content.add(message);
    /* Set the position and size of each component by calling
    its setBounds() method. */
    board.setBounds(16,16,220,220);
    newGameButton.setBounds(310, 60, 120, 30);
    resignButton.setBounds(310, 120, 120, 30);
    message.setBounds(0, 350, 350, 30);
    public static void main(String[] args)
    GoMoku1 gm=new GoMoku1();
    // ----------------------- Nested class -----------------------------------
    class Board extends JPanel implements ActionListener, MouseListener {
    int[][] board; // The data for the board is kept here. The values
    // in this array are chosen from the following constants.
    static final int EMPTY = 0, // Represents an empty square.
    WHITE = 1, // A white piece.
    BLACK = 2; // A black piece.
    boolean gameInProgress; // Is a game currently in progress?
    int currentPlayer; // Whose turn is it now? The possible values
    // are WHITE and BLACK. (This is valid only while
    // a game is in progress.)
    int win_r1, win_c1, win_r2, win_c2; // When a player wins by getting five or more
    // pieces in a row, the squares at the
    // ends of the row are (win_r1,win_c1)
    // and (win_r2,win_c2). A red line is
    // drawn between these squares. When there
    // are no five pieces in a row, the value of
    // win_r1 is -1. The values are set in the
    // count() method. The value of win_r1 is
    // tested in the paintComponent() method.
    public Board() {
    // Constructor. Create the buttons and label. Listen for mouse
    // clicks and for clicks on the buttons. Create the board and
    // start the first game.
    setBackground(Color.lightGray);
    addMouseListener(this);
    resignButton = new JButton("Resign");
    resignButton.addActionListener(this);
    newGameButton = new JButton("New Game");
    newGameButton.addActionListener(this);
    message = new JLabel("",JLabel.CENTER);
    message.setFont(new Font("Serif", Font.BOLD, 14));
    message.setForeground(Color.green);
    board = new int[ 15][ 15];
    doNewGame();
    public void actionPerformed(ActionEvent evt) {
    // Respond to user's click on one of the two buttons.
    Object src = evt.getSource();
    if (src == newGameButton)
    doNewGame();
    else if (src == resignButton)
    doResign();
    void doNewGame() {
    // Begin a new game.
    if (gameInProgress == true) {
    // This should not be possible, but it doesn't
    // hurt to check.
    message.setText("Finish the current game first!");
    return;
    for (int row = 0; row < 15; row++) // Fill the board with EMPTYs
    for (int col = 0; col < 15; col++)
    board[row][col] = EMPTY;
    currentPlayer = BLACK; // BLACK moves first.
    message.setText("BLACK: Make your move.");
    gameInProgress = true;
    newGameButton.setEnabled(false);
    resignButton.setEnabled(true);
    win_r1 = -1; // This value indicates that no red line is to be drawn.
    repaint();
    void doResign() {
    // Current player resigns. Game ends. Opponent wins.
    if (gameInProgress == false) {
    // This should not be possible.
    message.setText("There is no game in progress!");
    return;
    if (currentPlayer == WHITE)
    message.setText("WHITE resigns. BLACK wins.");
    else
    message.setText("BLACK resigns. WHITE wins.");
    newGameButton.setEnabled(true);
    resignButton.setEnabled(false);
    gameInProgress = false;
    void gameOver(String str) {
    // The game ends. The parameter, str, is displayed as a message.
    message.setText(str);
    newGameButton.setEnabled(true);
    resignButton.setEnabled(false);
    gameInProgress = false;
    void doClickSquare(int row, int col) {
    // This is called by mousePressed() when a player clicks on the
    // square in the specified row and col. It has already been checked
    // that a game is, in fact, in progress.
    /* Check that the user clicked an empty square. If not, show an
    error message and exit. */
    if ( board[row][col] != EMPTY ) {
    if (currentPlayer == BLACK)
    message.setText("BLACK: Please click an empty square.");
    else
    message.setText("WHITE: Please click an empty square.");
    return;
    /* Make the move. Check if the board is full or if the move
    is a winning move. If so, the game ends. If not, then it's
    the other user's turn. */
    board[row][col] = currentPlayer; // Make the move.
    repaint();
    if (winner(row,col)) { // First, check for a winner.
    if (currentPlayer == WHITE)
    gameOver("WHITE wins the game!");
    else
    gameOver("BLACK wins the game!");
    return;
    boolean emptySpace = false; // Check if the board is full.
    for (int i = 0; i < 15; i++)
    for (int j = 0; j < 15; j++)
    if (board[j] == EMPTY)
    emptySpace = true;
    if (emptySpace == false) {
    gameOver("The game ends in a draw.");
    return;
    /* Continue the game. It's the other player's turn. */
    if (currentPlayer == BLACK) {
    currentPlayer = WHITE;
    message.setText("WHITE: Make your move.");
    else {
    currentPlayer = BLACK;
    message.setText("BLACK: Make your move.");
    } // end doClickSquare()
    private boolean winner(int row, int col) {
    // This is called just after a piece has been played on the
    // square in the specified row and column. It determines
    // whether that was a winning move by counting the number
    // of squares in a line in each of the four possible
    // directions from (row,col). If there are 5 squares (or more)
    // in a row in any direction, then the game is won.
    if (count( board[row][col], row, col, 1, 0 ) >= 5)
    return true;
    if (count( board[row][col], row, col, 0, 1 ) >= 5)
    return true;
    if (count( board[row][col], row, col, 1, -1 ) >= 5)
    return true;
    if (count( board[row][col], row, col, 1, 1 ) >= 5)
    return true;
    /* When we get to this point, we know that the game is not
    won. The value of win_r1, which was changed in the count()
    method, has to be reset to -1, to avoid drawing a red line
    on the board. */
    win_r1 = -1;
    return false;
    } // end winner()
    private int count(int player, int row, int col, int dirX, int dirY) {
    // Counts the number of the specified player's pieces starting at
    // square (row,col) and extending along the direction specified by
    // (dirX,dirY). It is assumed that the player has a piece at
    // (row,col). This method looks at the squares (row + dirX, col+dirY),
    // (row + 2*dirX, col + 2*dirY), ... until it hits a square that is
    // off the board or is not occupied by one of the players pieces.
    // It counts the squares that are occupied by the player's pieces.
    // Furthermore, it sets (win_r1,win_c1) to mark last position where
    // it saw one of the player's pieces. Then, it looks in the
    // opposite direction, at squares (row - dirX, col-dirY),
    // (row - 2*dirX, col - 2*dirY), ... and does the same thing.
    // Except, this time it sets (win_r2,win_c2) to mark the last piece.
    // Note: The values of dirX and dirY must be 0, 1, or -1. At least
    // one of them must be non-zero.
    int ct = 1; // Number of pieces in a row belonging to the player.
    int r, c; // A row and column to be examined
    r = row + dirX; // Look at square in specified direction.
    c = col + dirY;
    while ( r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] == player ) {
    // Square is on the board and contains one of the players's pieces.
    ct++;
    r += dirX; // Go on to next square in this direction.
    c += dirY;
    win_r1 = r - dirX; // The next-to-last square looked at.
    win_c1 = c - dirY; // (The LAST one looked at was off the board or
    // did not contain one of the player's pieces.
    r = row - dirX; // Look in the opposite direction.
    c = col - dirY;
    while ( r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] == player ) {
    // Square is on the board and contains one of the players's pieces.
    ct++;
    r -= dirX; // Go on to next square in this direction.
    c -= dirY;
    win_r2 = r + dirX;
    win_c2 = c + dirY;
    // At this point, (win_r1,win_c1) and (win_r2,win_c2) mark the endpoints
    // of the line of pieces belonging to the player.
    return ct;
    } // end count()
    public void paintComponent(Graphics g) {
    super.paintComponent(g); // Fill with background color, lightGray
    /* Draw a two-pixel black border around the edges of the canvas,
    and draw grid lines in darkGray. */
    g.setColor(Color.darkGray);
    for (int i = 1; i < 15; i++) {
    g.drawLine(1 + 15*i, 0, 1 + 15*i, getSize().height);
    g.drawLine(0, 1 + 15*i, getSize().width, 1 + 15*i);
    g.setColor(Color.black);
    g.drawRect(0,0,getSize().width-1,getSize().height-1);
    g.drawRect(1,1,getSize().width-3,getSize().height-3);
    /* Draw the pieces that are on the board. */
    for (int row = 0; row < 15; row++)
    for (int col = 0; col < 15; col++)
    if (board[row][col] != EMPTY)
    drawPiece(g, board[row][col], row, col);
    /* If the game has been won, then win_r1 >= 0. Draw a line to mark
    the five winning pieces. */
    if (win_r1 >= 0)
    drawWinLine(g);
    } // end paintComponent()
    private void drawPiece(Graphics g, int piece, int row, int col) {
    // Draw a piece in the square at (row,col). The color is specified
    // by the piece parameter, which should be either BLACK or WHITE.
    if (piece == WHITE)
    g.setColor(Color.white);
    else
    g.setColor(Color.black);
    g.fillOval(3 + 15*col, 3 + 15*row, 10, 10);
    private void drawWinLine(Graphics g) {
    // Draw a 2-pixel wide red line from the middle of the square at
    // (win_r1,win_c1) to the middle of the square at (win_r2,win_c2).
    // This routine is called to mark the 5 pieces that won the game.
    // The values of the variables are set in the count() method.
    g.setColor(Color.red);
    g.drawLine( 8 + 15*win_c1, 8 + 15*win_r1, 8 + 15*win_c2, 8 + 15*win_r2 );
    if (win_r1 == win_r2)
    g.drawLine( 8 + 15*win_c1, 7 + 15*win_r1, 8 + 15*win_c2, 7 + 15*win_r2 );
    else
    g.drawLine( 7 + 15*win_c1, 8 + 15*win_r1, 7 + 15*win_c2, 8 + 15*win_r2 );
    public Dimension getPreferredSize() {
    // Specify desired size for this component. Note:
    // the size MUST be 172 by 172.
    return new Dimension(220, 220);
    public Dimension getMinimumSize() {
    return new Dimension(220, 220);
    public Dimension getMaximumSize() {
    return new Dimension(220, 220);
    public void mousePressed(MouseEvent evt) {
    // Respond to a user click on the board. If no game is
    // in progress, show an error message. Otherwise, find
    // the row and column that the user clicked and call
    // doClickSquare() to handle it.
    if (gameInProgress == false)
    message.setText("Click \"New Game\" to start a new game.");
    else {
    int col = (evt.getX() - 2) / 15;
    int row = (evt.getY() - 2) / 15;
    if (col >= 0 && col < 15 && row >= 0 && row < 15)
    doClickSquare(row,col);
    public void mouseReleased(MouseEvent evt) { }
    public void mouseClicked(MouseEvent evt) { }
    public void mouseEntered(MouseEvent evt) { }
    public void mouseExited(MouseEvent evt) { }
    } // end nested class Board
    } // end class GoMoku

    This'll do it.
    regards,
    Owen
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GoMoku1 extends JFrame
        JButton newGameButton; // Button for starting a new game.
        JButton resignButton; // Button that a player can use to end the
                               // game by resigning.
        JLabel  message;      // Label for displaying messages to the user.
        public GoMoku1 ( )
            super("GoMoku1");
            Container content = getContentPane(); // Content pane of applet.
            content.setLayout(null); // I will do the layout myself.
            content.setBackground(new Color(0, 150, 0)); // Dark green background.
            Board board = new Board(); // Note: The constructor for the
            // board also creates the buttons
            // and label.
            content.add(board);
            content.add(newGameButton);
            content.add(resignButton);
            content.add(message);
            /* Set the position and size of each component by calling
             its setBounds() method. */
            board.setBounds(16, 16, 220, 220);
            newGameButton.setBounds(310, 60, 120, 30);
            resignButton.setBounds(310, 120, 120, 30);
            message.setBounds(0, 350, 350, 30);
        public static void main(String[] args)
            GoMoku1 gm = new GoMoku1();
            gm.setSize ( 640, 480 );
            gm.setVisible(true);
            gm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // ----------------------- Nested class -----------------------------------
        class Board extends JPanel implements ActionListener, MouseListener
            int[][] board; // The data for the board is kept here. The values
                           // in this array are chosen from the following constants.
            static final int EMPTY = 0, // Represents an empty square.
                                   WHITE = 1, // A white piece.
                                   BLACK = 2; // A black piece.
            boolean          gameInProgress; // Is a game currently in progress?
            int              currentPlayer;  // Whose turn is it now? The possible values
                                              // are WHITE and BLACK. (This is valid only while
                                              // a game is in progress.)
            int              win_r1, win_c1, win_r2, win_c2; // When a player wins by getting five or more
                                                             // pieces in a row, the squares at the
                                                             // ends of the row are (win_r1,win_c1)
                                                             // and (win_r2,win_c2). A red line is
                                                             // drawn between these squares. When there
                                                             // are no five pieces in a row, the value of
                                                             // win_r1 is -1. The values are set in the
                                                             // count() method. The value of win_r1 is
                                                             // tested in the paintComponent() method.
            public Board ( )
                // Constructor. Create the buttons and label. Listen for mouse
                // clicks and for clicks on the buttons. Create the board and
                // start the first game.
                setBackground(Color.lightGray);
                addMouseListener(this);
                resignButton = new JButton("Resign");
                resignButton.addActionListener(this);
                newGameButton = new JButton("New Game");
                newGameButton.addActionListener(this);
                message = new JLabel("", JLabel.CENTER);
                message.setFont(new Font("Serif", Font.BOLD, 14));
                message.setForeground(Color.green);
                board = new int[15][15];
                doNewGame();
            public void actionPerformed(ActionEvent evt)
                // Respond to user's click on one of the two buttons.
                Object src = evt.getSource();
                if (src == newGameButton)
                    doNewGame();
                else if (src == resignButton)
                    doResign();
            void doNewGame()
                // Begin a new game.
                if (gameInProgress == true)
                    // This should not be possible, but it doesn't
                    // hurt to check.
                    message.setText("Finish the current game first!");
                    return;
                for (int row = 0; row < 15; row++)
                    // Fill the board with EMPTYs
                    for (int col = 0; col < 15; col++)
                        board[row][col] = EMPTY;
                currentPlayer = BLACK; // BLACK moves first.
                message.setText("BLACK: Make your move.");
                gameInProgress = true;
                newGameButton.setEnabled(false);
                resignButton.setEnabled(true);
                win_r1 = -1; // This value indicates that no red line is to be drawn.
                repaint();
            void doResign()
                // Current player resigns. Game ends. Opponent wins.
                if (gameInProgress == false)
                    // This should not be possible.
                    message.setText("There is no game in progress!");
                    return;
                if (currentPlayer == WHITE)
                    message.setText("WHITE resigns. BLACK wins.");
                else
                    message.setText("BLACK resigns. WHITE wins.");
                newGameButton.setEnabled(true);
                resignButton.setEnabled(false);
                gameInProgress = false;
            void gameOver(String str)
                // The game ends. The parameter, str, is displayed as a message.
                message.setText(str);
                newGameButton.setEnabled(true);
                resignButton.setEnabled(false);
                gameInProgress = false;
            void doClickSquare(int row, int col)
                // This is called by mousePressed() when a player clicks on the
                // square in the specified row and col. It has already been checked
                // that a game is, in fact, in progress.
                /* Check that the user clicked an empty square. If not, show an
                 error message and exit. */
                if (board[row][col] != EMPTY)
                    if (currentPlayer == BLACK)
                        message.setText("BLACK: Please click an empty square.");
                    else
                        message.setText("WHITE: Please click an empty square.");
                    return;
                /* Make the move. Check if the board is full or if the move
                 is a winning move. If so, the game ends. If not, then it's
                 the other user's turn. */
                board[row][col] = currentPlayer; // Make the move.
                repaint();
                if (winner(row, col))
                { // First, check for a winner.
                    if (currentPlayer == WHITE)
                        gameOver("WHITE wins the game!");
                    else
                        gameOver("BLACK wins the game!");
                    return;
                boolean emptySpace = false; // Check if the board is full.
                for (int i = 0; i < 15; i++)
                    for (int j = 0; j < 15; j++)
                        if (board[i][j] == EMPTY)
                            emptySpace = true;
                if (emptySpace == false)
                    gameOver("The game ends in a draw.");
                    return;
                /* Continue the game. It's the other player's turn. */
                if (currentPlayer == BLACK)
                    currentPlayer = WHITE;
                    message.setText("WHITE: Make your move.");
                else
                    currentPlayer = BLACK;
                    message.setText("BLACK: Make your move.");
            } // end doClickSquare()
            private boolean winner(int row, int col)
                // This is called just after a piece has been played on the
                // square in the specified row and column. It determines
                // whether that was a winning move by counting the number
                // of squares in a line in each of the four possible
                // directions from (row,col). If there are 5 squares (or more)
                // in a row in any direction, then the game is won.
                if (count(board[row][col], row, col, 1, 0) >= 5)
                    return true;
                if (count(board[row][col], row, col, 0, 1) >= 5)
                    return true;
                if (count(board[row][col], row, col, 1, -1) >= 5)
                    return true;
                if (count(board[row][col], row, col, 1, 1) >= 5)
                    return true;
                /* When we get to this point, we know that the game is not
                 won. The value of win_r1, which was changed in the count()
                 method, has to be reset to -1, to avoid drawing a red line
                 on the board. */
                win_r1 = -1;
                return false;
            } // end winner()
            private int count(int player, int row, int col, int dirX, int dirY)
                // Counts the number of the specified player's pieces starting at
                // square (row,col) and extending along the direction specified by
                // (dirX,dirY). It is assumed that the player has a piece at
                // (row,col). This method looks at the squares (row + dirX, col+dirY),
                // (row + 2*dirX, col + 2*dirY), ... until it hits a square that is
                // off the board or is not occupied by one of the players pieces.
                // It counts the squares that are occupied by the player's pieces.
                // Furthermore, it sets (win_r1,win_c1) to mark last position where
                // it saw one of the player's pieces. Then, it looks in the
                // opposite direction, at squares (row - dirX, col-dirY),
                // (row - 2*dirX, col - 2*dirY), ... and does the same thing.
                // Except, this time it sets (win_r2,win_c2) to mark the last piece.
                // Note: The values of dirX and dirY must be 0, 1, or -1. At least
                // one of them must be non-zero.
                int ct = 1; // Number of pieces in a row belonging to the player.
                int r, c; // A row and column to be examined
                r = row + dirX; // Look at square in specified direction.
                c = col + dirY;
                while (r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] == player)
                    // Square is on the board and contains one of the players's pieces.
                    ct++;
                    r += dirX; // Go on to next square in this direction.
                    c += dirY;
                win_r1 = r - dirX; // The next-to-last square looked at.
                win_c1 = c - dirY; // (The LAST one looked at was off the board or
                // did not contain one of the player's pieces.
                r = row - dirX; // Look in the opposite direction.
                c = col - dirY;
                while (r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] == player)
                    // Square is on the board and contains one of the players's pieces.
                    ct++;
                    r -= dirX; // Go on to next square in this direction.
                    c -= dirY;
                win_r2 = r + dirX;
                win_c2 = c + dirY;
                // At this point, (win_r1,win_c1) and (win_r2,win_c2) mark the endpoints
                // of the line of pieces belonging to the player.
                return ct;
            } // end count()
            public void paintComponent(Graphics g)
                super.paintComponent(g); // Fill with background color, lightGray
                /* Draw a two-pixel black border around the edges of the canvas,
                 and draw grid lines in darkGray. */
                g.setColor(Color.darkGray);
                for (int i = 1; i < 15; i++)
                    g.drawLine(1 + 15 * i, 0, 1 + 15 * i, getSize().height);
                    g.drawLine(0, 1 + 15 * i, getSize().width, 1 + 15 * i);
                g.setColor(Color.black);
                g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
                g.drawRect(1, 1, getSize().width - 3, getSize().height - 3);
                /* Draw the pieces that are on the board. */
                for (int row = 0; row < 15; row++)
                    for (int col = 0; col < 15; col++)
                        if (board[row][col] != EMPTY)
                            drawPiece(g, board[row][col], row, col);
                /* If the game has been won, then win_r1 >= 0. Draw a line to mark
                 the five winning pieces. */
                if (win_r1 >= 0)
                    drawWinLine(g);
            } // end paintComponent()
            private void drawPiece(Graphics g, int piece, int row, int col)
                // Draw a piece in the square at (row,col). The color is specified
                // by the piece parameter, which should be either BLACK or WHITE.
                if (piece == WHITE)
                    g.setColor(Color.white);
                else
                    g.setColor(Color.black);
                g.fillOval(3 + 15 * col, 3 + 15 * row, 10, 10);
            private void drawWinLine(Graphics g)
                // Draw a 2-pixel wide red line from the middle of the square at
                // (win_r1,win_c1) to the middle of the square at (win_r2,win_c2).
                // This routine is called to mark the 5 pieces that won the game.
                // The values of the variables are set in the count() method.
                g.setColor(Color.red);
                g.drawLine(8 + 15 * win_c1, 8 + 15 * win_r1, 8 + 15 * win_c2, 8 + 15 * win_r2);
                if (win_r1 == win_r2)
                    g.drawLine(8 + 15 * win_c1, 7 + 15 * win_r1, 8 + 15 * win_c2, 7 + 15 * win_r2);
                else
                    g.drawLine(7 + 15 * win_c1, 8 + 15 * win_r1, 7 + 15 * win_c2, 8 + 15 * win_r2);
            public Dimension getPreferredSize()
                // Specify desired size for this component. Note:
                // the size MUST be 172 by 172.
                return new Dimension(220, 220);
            public Dimension getMinimumSize()
                return new Dimension(220, 220);
            public Dimension getMaximumSize()
                return new Dimension(220, 220);
            public void mousePressed(MouseEvent evt)
                // Respond to a user click on the board. If no game is
                // in progress, show an error message. Otherwise, find
                // the row and column that the user clicked and call
                // doClickSquare() to handle it.
                if (gameInProgress == false)
                    message.setText("Click \"New Game\" to start a new game.");
                else
                    int col = (evt.getX() - 2) / 15;
                    int row = (evt.getY() - 2) / 15;
                    if (col >= 0 && col < 15 && row >= 0 && row < 15)
                        doClickSquare(row, col);
            public void mouseReleased(MouseEvent evt)
            public void mouseClicked(MouseEvent evt)
            public void mouseEntered(MouseEvent evt)
            public void mouseExited(MouseEvent evt)
        } // end nested class Board
    } // end class GoMoku

  • Need help to draw recangle on video

    Hi guys ,
    Below I have pasted my code . In this code I have defined frame and in that frame stored video run. The other class has defined rectangle in cnvas . My problem is that I want rectangle to be drawn on video player and I havnt been successful.
    So its my reequest to please help me out.
    Thanks a ton in advance........
    public class Map extends JFrame
    * MAIN PROGRAM / STATIC METHODS
    public static void main(String args[])
    Map mdi = new Map();
    static void Fatal(String s)
    MessageBox mb = new MessageBox("JMF Error", s);
    * VARIABLES
    JMFrame jmframe = null;
    JDesktopPane desktop;
    FileDialog fd = null;
    CheckboxMenuItem cbAutoLoop = null;
    Player player = null;
    Player newPlayer = null;
    //JPanel glass = null;
    SelectionArea drawingPanel;
    String filename;
    // code//
    //ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
    // boolean stop=false;
    * METHODS
    public Map()
    super("Java Media Player");
    drawingPanel = new SelectionArea(this);
    // Add the desktop pane
    setLayout( new BorderLayout() );
    desktop = new JDesktopPane();
    desktop.setDoubleBuffered(true);
    add("Center", desktop);
    setMenuBar(createMenuBar());
    setSize(640, 480);
    setVisible(true);
    //add(drawingPanel);
    //drawingPanel.setVisible(true);
    try
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    catch (Exception e)
    System.err.println("Could not initialize java.awt Metal lnf");
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent we)
    System.exit(0);
    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
    private MenuBar createMenuBar()
    ActionListener al = new ActionListener()
    public void actionPerformed(ActionEvent ae)
    String command = ae.getActionCommand();
    if (command.equals("Open"))
    if (fd == null)
    fd = new FileDialog(Map.this, "Open File",
    FileDialog.LOAD);
    fd.setDirectory("/movies");
    fd.show();
    if (fd.getFile() != null)
    String filename = fd.getDirectory() + fd.getFile();
    openFile("file:" + filename);
    else if (command.equals("Exit"))
    dispose();
    System.exit(0);
    MenuItem item;
    MenuBar mb = new MenuBar();
    // File Menu
    Menu mnFile = new Menu("File");
    mnFile.add(item = new MenuItem("Open"));
    item.addActionListener(al);
    mnFile.add(item = new MenuItem("Exit"));
    item.addActionListener(al);
    // Options Menu
    Menu mnOptions = new Menu("Options");
    cbAutoLoop = new CheckboxMenuItem("Auto replay");
    cbAutoLoop.setState(true);
    mnOptions.add(cbAutoLoop);
    mb.add(mnFile);
    mb.add(mnOptions);
    return mb;
    * Open a media file.
    public void openFile(String filename)
    String mediaFile = filename;
    Player player = null;
    // URL for our media file
    URL url = null;
    try
    // Create an url from the file name and the url to the
    // document containing this applet.
    if ((url = new URL(mediaFile)) == null)
    Fatal("Can't build URL for " + mediaFile);
    return;
    // Create an instance of a player for this media
    try
    player = Manager.createPlayer(url);
    catch (NoPlayerException e)
    Fatal("Error: " + e);
    catch (MalformedURLException e)
    Fatal("Error:" + e);
    catch (IOException e)
    Fatal("Error:" + e);
    if (player != null)
    this.filename = filename;
    JMFrame jmframe = new JMFrame(player, filename);
    desktop.add(jmframe);
    if (player.getVisualComponent() != null)
    getContentPane().add(player.getVisualComponent());
    player.start();
    jmframe.add(drawingPanel);
    drawingPanel.setVisible(true);
    /*validate();
    public void paint(Graphics g)
    drawingPanel.repaint();
    public void update(Graphics g)
    paint(g);
    drawingPanel.repaint();
    class SelectionArea extends Canvas implements ActionListener, MouseListener, MouseMotionListener
    Rectangle currentRect;
    Map controller;
    //for double buffering
    Image image;
    Graphics offscreen;
    public SelectionArea(Map controller)
    super();
    this.controller = controller;
    addMouseListener(this);
    addMouseMotionListener(this);
    public void actionPerformed(ActionEvent ae)
    repaintoffscreen();
    public void repaintoffscreen()
    image = createImage(this.getWidth(), this.getHeight());
    offscreen = image.getGraphics();
    Dimension d = size();
    if(currentRect != null)
    //Rectangle box = new Rectangle();
    //box.getDrawable(currentRect, d);
    Rectangle box = getDrawableRect(currentRect, d);
    //Draw the box outline.
    offscreen.drawRect(box.x, box.y, box.width - 1, box.height - 1);
    repaint();
    public void mouseEntered(MouseEvent me) {}
    public void mouseExited(MouseEvent me){ }
    public void mouseClicked(MouseEvent me){}
    public void mouseMoved(MouseEvent me){}
    public void mousePressed(MouseEvent me)
    currentRect = new Rectangle(me.getX(), me.getY(), 0, 0);
    repaintoffscreen();
    public void mouseDragged(MouseEvent me)
    System.out.println("here in dragged()");
    currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
    repaintoffscreen();
    repaint();
    public void mouseReleased(MouseEvent me)
    currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
    repaintoffscreen();
    repaint();
    public void update(Graphics g)
    paint(g);
    public void paint(Graphics g)
    g.drawImage(image, 0, 0, this);
    Rectangle getDrawableRect(Rectangle originalRect, Dimension drawingArea)
    int x = originalRect.x;
    int y = originalRect.y;
    int width = originalRect.width;
    int height = originalRect.height;
    //Make sure rectangle width and height are positive.
    if (width < 0)
    width = 0 - width;
    x = x - width + 1;
    if (x < 0)
    width += x;
    x = 0;
    if (height < 0)
    height = 0 - height;
    y = y - height + 1;
    if (y < 0)
    height += y;
    y = 0;
    //The rectangle shouldn't extend past the drawing area.
    if ((x + width) > drawingArea.width)
    width = drawingArea.width - x;
    if ((y + height) > drawingArea.height)
    height = drawingArea.height - y;
    return new Rectangle(x, y, width, height);
    }

    Chances of someone reading a gazillion lines of unformatted code: < 1%
    Paste your code (from the source), highlight it and click the CODE button to retain formatting and make it readable.

  • PLEASE HELP ME FOR MY PROJECT

    Hello.
    I have my project to be done by Monday.
    I typed some code, but have no idea what to do anymore. No clue...
    The following is the project overview etc.
    Overview
    In a single source file named App.java, define an Employee class to encapsulate employee data and an App class defining an applet to maintain a collection of Employee objects.
    Employee Class
    Define a small, non-public class named Employee that encapsulates private instance variables for name (String) and pay rate (double). The class needs a single constructor to instantiate an Employee object with values received for both instance variables. It also needs minimal set() and get() methods (such as setName(), getPayRate(), etc.) that allow a class client to store and retrieve the value of each instance variable. Do not be concerned with editing the data within this class. It is used only to support the testing of your applet.
    Code this class inside your App.java source file but after the definition of the App class. Be sure to omit the specification of public in the class header (because Java only allows one public class per source file).
    App class
    This public class will define the processing of your applet. Its required features are as follows:
    Input Components:
    Name (a TextField). For entering or displaying an employee's name.
    Pay rate (a TextField). For entering or displaying an employee's pay rate. When used for input, the value must be edited (see the processing notes below). If the value is invalid, display an appropriate error message.
    First (a button). When clicked, triggers the display of the name and pay rate of the first employee in the collection. If the collection is empty, display an appropriate message.
    Next (a button). When clicked, triggers the display of the name and pay rate of the next employee in the collection. If there are no more objects in the collection, display an appropriate message.
    Find (a button). When clicked, triggers the display of the name and pay rate of the employee whose name currently appears in the name text field. If the requested employee doesn't exist, display an appropriate error message.
    Add (a button). When clicked, triggers the construction of an Employee object having the currently displayed name and pay rate and the addition of the object to the collection. Display appropriate error messages if input data is missing or incorrect or if the employee already exists within the collection.
    Delete (a button). When clicked, triggers the deletion of the Employee object having the currently displayed name from the collection. If the specified employee doesn't exist, display an appropriate error message.
    Output components:
    Number of employees (a Label). For displaying how many Employee objects are currently within the collection. This must be changed as employees are added or deleted from the collection.
    Message area (a TextArea). For displaying messages.
    Processing notes:
    The applet must get the value of an HTML parameter named "maxRate". Convert the associated value string to a double and use it to edit a pay rate entered by the user. It represents the maximum allowable pay rate for an employee. If an attempt is made to enter a larger pay rate, display an appropriate error message.
    Use GridBagLayout for the applet's components. The arrangement of components is up to you.
    Use a SortedMap implemented as a TreeMap for the collection. It is to be maintained in ascending order based upon employee name.
    When the user moves the mouse to touch one of the buttons, its color or font should change. When the mouse exits the button, its color or font should return to normal.
    The following is the code I have so far
    <CODE>
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class App extends Applet implements ActionListener, MouseListener,
    MouseMotionListener{
    // Instance variables for the employees' name and pay rate.
    private String name;
    private double payRate;
    // Instance variables for referencing the Employee name heading and its text field.
    private Label nameLabel;
    private TextField nameField;
    // Instance variables for referencing the pay rate heading and its text field.
    private Label payRateLabel;
    private TextField payRateField;
    // Instance variables for referencing the number of employees' heading and
    // its text field.
    private Label empNumLabel;
    private TextField empNumField;
    // Instance variables for referencing the "First", "Next", "Find", "Add", and
    // "Delete" button.
    private Button firstBtn;
    private Button nextBtn;
    private Button findBtn;
    private Button addBtn;
    private Button deleteBtn;
    // Instance variables for referencing the message area.
    private TextArea msg;
    public static void main(String[] args){
    SortedMap m = new TreeMap();
    // This method defines initial (one-time) applet processing.
    public void init(){
    // Set the size and background/foreground color for the applet window.
    setSize(250, 350);
    setBackground(Color.lightGray);
    setForeground(Color.green);
    // Choose GridBagLayout and create a GridBagConstraints object for use in
    // laying out components to be added to hte container.
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    // Initialize constraints to stretch small components to fill their entire
    // display area, give all rows equal height when distributing extra vertical
    // space, and give all columns equal width when distributing extra horizontal
    // space.
    c.fill=GridBagConstraints.BOTH;
    c.anchor = GridBagConstrainst.CENTER;
    c.weightx = 1;
    c.weighty = 1;
    // Build Employee Name label and add it to the top-left cell in the layout.
    nameLabel = new Label ("Employee Name");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 1;
    c.gridheight = 1;
    add (nameLabel, c);
    // Build Employee Name text field and add it to x=1, y=0 in the layout.
    nameField = new TextField (30);
    c.gridx = 1;
    c.gridy = 0;
    c.gridwidth = 1;
    // or c.gridwidth = GridBagConstraints.REMAINDER; //Last on row.
    c.gridheight = 1;
    add (nameField, c);
    // Build Pay Rate label and add it to the second row, first column in the layout.
    payRateLabel = new Label ("Pay Rate");
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.gridheight = 1;
    add (payRateLabel, c);
    // Build Pay Rate text field and add it to x=1, y=1 in the layout.
    payRateField = new TextField (8);
    c.gridx = 1;
    c.gridy = 1;
    c.gridwidth = 1;
    // or c.gridwidth = GridBagConstraints.REMAINDER; //Last on row.
    c.gridheight = 1;
    add (payRateField, c);
    // Build number of employee label and add it to x=1, y=2 in the layout.
    empNumLabel = new Label ("Number of Employees");
    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    c.gridheight = 1;
    add(empNumLabel, c);
    // Build number of employee text field and add it to x=2, y=2 in the layout.
    empNumField = new TextField (5);
    c.gridx = 2;
    c.gridy = 2;
    c.gridwidth = 1;
    c.gridheight = 1;
    add(empNumField, c);
    // Create the "ADD" button and add it to the x=1, y=3 in the layout.
    addBtn = new Button ("Add");
    addBtn.setBackground(Color.red);
    addBtn.setForeground(Color.black);
    addBtn.addActionListener(
    new ActionListener() {
    public void actionPerformed (ActionEvent e){
    c.gridx = 1;
    c.gridy = 3;
    c.gridwidth = 1;
    c.gridheight = 1;
    add(addBtn, c);
    // Create the "DELETE" button and add it to the x=2, y=3 in the layout.
    deleteBtn = new Button ("Delete");
    deleteBtn.setBackground(Color.red);
    deleteBtn.setForeground(Color.black);
    deleteBtn.addActionListener(
    new ActionListener() {
    public void actionPerformed (ActionEvent e){
    c.gridx = 2;
    c.gridy = 3;
    c.gridwidth = 1;
    c.gridheight = 1;
    add(deleteBtn, c);
    // Create the "FIRST" button and add it to the x=0, y=4 in the layout.
    firstBtn = new Button ("First");
    firstBtn.setBackground(Color.red);
    firstBtn.setForeground(Color.black);
    firstBtn.addActionListener(
    new ActionListener() {
    public void actionPerformed (ActionEvent e){
    c.gridx = 0;
    c.gridy = 4;
    c.gridwidth = 1;
    c.gridheight = 1;
    add(firstBtn, c);
    // Create the "NEXT" button and add it to the x=1, y=4 in the layout.
    nextBtn = new Button ("Next");
    nextBtn.setBackground(Color.red);
    nextBtn.setForeground(Color.black);
    nextBtn.addActionListener(
    new ActionListener() {
    public void actionPerformed (ActionEvent e){
    c.gridx = 1;
    c.gridy = 4;
    c.gridwidth = 1;
    c.gridheight = 1;
    add(nextBtn, c);
    // Create the "FIND" button and add it to the x=2, y=4 in the layout.
    findBtn = new Button ("Find");
    findBtn.setBackground(Color.red);
    findBtn.setForeground(Color.black);
    findBtn.addActionListener(
    new ActionListener() {
    public void actionPerformed (ActionEvent e){
    c.gridx = 2;
    c.gridy = 4;
    c.gridwidth = 1;
    c.gridheight = 1;
    add(findBtn, c);
    // Create message are and add it to x=0, y=5 in the layout.
    msg = new TextArea (5, 20);
    c.gridx = 0;
    c.gridy = 5;
    c.gridwidth = GridBagConstraints.REMAINDER; // Last on row
    c.gridheight = 1;
    add(msg, c);
    //???????????????????????????????????????????????/////////////////////////???????????????????????????????????????????????///////////////////////public void setName (String newName){
    name = newName;
    public void setPayRate (double newPayRate){
    payRate = newPayRate;
    public void getName () {
    return name;
    public void getPayRate() {
    return payRate;
    //Change color of Button
    public void mouseEntered (MouseEvent e){
    Color oldBackground = addBtn.getBackground();
    addBtn.setBackground(addBtn.getForeground());
    addBtn.setForeground(oldBackground);
    public void mouseExited (MouseEvent e){
    Color oldBackground = addBtn.getBackground();
    addBtn.setBackground(addBtn.getForeground());
    addBtn.setForeground(oldBackground);
    </CODE>
    I don't know where to put Employee class.
    I don't know what to do anymore...
    I'm soooooooooooooo stuck and just want to cry...
    Please give me any suggestion/help so that I could move on.
    Thank you so much in advance

    Step 1 (analying your specs).
    In a single source file named App.java, define an Employee class to encapsulate employee data and an App class defining an applet to maintain a collection of Employee objects.
    You are given lots of usefule information.
    Name of the primary (source) class to create App
    Primary class (source) will include an employee class.
    The need to maintain a collection (list) of employee classes.
    first thing i do is
    public class App {
        Vector myEmps = new Vector();// will hold the employee objects;
        Employee emp;      // single instance of an employee object
        App() {
           // this is how we add employee objects to the list
           // in this case the list is a vector.
           myEmps.add(new Employee("sean",1,80000.50));
           myEmps.add(new Employee("davey",1,70000.25));
           myEmps.add(new Employee("harry",1,90000.15));
    class Employee {
    // define employee data as variables
       String name;
       int ID;
       double payRate;
          Employee(String n, int ID, double pr) {
            this.name = n;
            this.ID = ID;
            this.payRate = pr;
         public void setName(String n) {  // can set/change emps name
            name = n;
         public void setPayRate(double pr) {  // can set/change payRate
              payRate = pr;
    }this is just a start

Maybe you are looking for

  • I am trying to install XP Home Edition over Windows 7

    Hello,  I have been all over trying to resolve the problem detailed below and hope you can help me. I have a HP Pavilion Elite -  HPE 180T - OS Win 7 64 bit.  System Info: 9 GB Physical memory - 5 memory Modules - Video Card1.8GB  NVIDIA GeForct GTX

  • Help please. My mac book pro did a java update and now will not boot  oot.

    As it says above. Since doing a java update automatically and then shutting down on me.. my mac book will not boot properly. I can get it to boot in safe mode eventually, usually after 5 to 10 mins of waiting, but will not boot into mormal mode. How

  • Boot Camp Partition and OS X Cloning Apps?

    I've tried a search of previous posts and can't get a bulletproof answer. Here goes: Using XP SP3 in a Boot Camp partition on my iMac running Snow Leopard. Only one complaint (the metal keyboard Option key issue for boot up -- really lame). The Windo

  • Basic transition between two pictures (MCs)

    I'm trying to implement a typical gallery fade transition between two pictures when a thumbnail is clicked, but the tweens aren't showing. The individual pic information is loaded from an XML file, not the library. The correct picture is displayed, b

  • Deployment MANIFEST.MF CLASSPATH

    I am create (deploy into) a jar file using JDeveloper 11.1.2.1. My app has dependencies on other libraries (AXIS2). I can create dependencies using manage libraries, and can compile my project. In the deployment profile I created a file group contain