Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (482)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (550)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Creating custom Button Class  (Read 1761 times)
0 Members and 1 Guest are viewing this topic.
Offline Serethos

Junior Member




Java games rock!


« Posted 2004-02-06 19:24:19 »

i want to implement a custom button class for my applet. main idea is, that the button is able to provide my kind of animation-strips, so that there's some animation, not only on/off graphics.

up to now did not use any component or awt classes ( i want to avoid the method-overkill and have ome training).

so the basic is only a class, which draws themselfe on a graphics context, has some animationstrips and registers to a mouse listener.
but if the button doesnt extend component, i can not use mouseEntered().

after long text now my question:

only solution i see is to test in every button which is active on screen in its mouseMoved() if the cursor has moved into the bounding box of the button.
is this the way, mouseEntered works ? is there a better way `?
Offline Jeff

JGO Coder




Got any cats?


« Reply #1 - Posted 2004-02-06 19:45:27 »

if you want to use AWT events you need to use AWT components. Its about  that simple.  You will need to at least subclass Component and might as well subclass JButton for convenience.

If you are not using AWT at all (for instance when doing active rednering) you can use JInput to poll the mouse once around the game loop.  JInput returns raw mouse deltas so you will need to animate your own cursor and track its location yourself.

Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Offline sma

Junior Member





« Reply #2 - Posted 2004-02-13 10:00:53 »

Quote
i want to implement a custom button class for my applet. main idea is, that the button is able to provide my kind of animation-strips, so that there's some animation, not only on/off graphics.


Using the Java Plug-in, you've Swing and Swing can display any Image on a JButton, even animated gifs.  That would make your problem go away.

But if you want to make things more difficult for yourself, you need to create your own barebone mini UI from scratch.  You applet is an AWT component (the only one left if you don't want to use AWT or Swing) and you need to add your mouse listener here and overwrite its paint() method.

You've to create your own objects representing buttons and synthetize your own events. See below for a code sketch:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
class UIButton  {
  Applet parent;
  Rectangle bounds;
  boolean over;
  boolean pressed;
  void paint(Graphics g) {
    // paint stuff inside bounds, depending over and pressed state
 }
  void setOver(boolean b) {
    if (over == b) return;
    over = b; repaint();
  }
  // same for pressed
 // also add getters
 void repaint() {
    repaint(bounds);
  }
  void repaint(Rectangle r) {
    if (parent != null) parent.repaint(r.x, r.y, r.width, r.height);
  }
  void boolean contains(int x, int y) {
    return bounds.contains(x, y);
  }
  void onMouseEnter() { setOver(true); }
  void onMouseExit() { setOver(false); }
  void onMousePressed() { setPressed(true); }
  void onMouseReleased() { setPressed(false); }
  void onMouseClicked() {}
}
class YourApplet extends Applet {
  List<UIButton> buttons; //notice, I'm using JDK 1.5 style generics
 void init() {
    addMouseListener(new MouseAdapter() {
      // delegate calls to methods shown below
   });
    // do the same for mouseMoveListener
 }
  void addButton(UIButton b) {
    buttons.add(b);
    b.parent = this;
    b.repaint();
  }
  void removeButton(UIButton b) {
     b.repaint();
     b.parent = null;
     buttons.remove(b);
  }
  UIButton buttonAt(int x, int y) {
    for (UIButton b : buttons) // again 1.5 style, it's so much shorter
     if (b.contains(x, y)) return b;
    return null;
  }
  void paint(Graphics g) {
    for (UIButton b : buttons) b.paint(g);
  }
  UIButton over, pressed;
  private void onMouseMove(int x, int y)  {
    UIButton b = buttonAt(x, y);
    if (b != over) {
      if (over != null) over.onMouseExit();
      over = b;
      if (over != null) over.onMouseEnter();
    }
  }
  private void onMousePressed(int x, int y) {
    if (over != null) {
      pressed = over;
      pressed.onMousePressed(x, y);
    }
  }
  private void onMouseReleased(int x, int y) {
    if (pressed != null) pressed.onMousePressed(x, y);
    if (pressed == over) pressed.onMouseClicked();
    pressed = false;
  }
}

This code implements generic buttons you can subclass and use similar to you'd use AWT buttons (there's no listener concept though).  To add animations, I could imagine this.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
class UIAnimatedButton extends UIButton {
  int phase;
  Image phasesImage;
  synchronized void tick() {
   phase = (phase + 1) % MAX_PHASE; repaint();
  }
  void paint(Graphics g) {
     // draw some part of the image
   g.drawImage(phasesImage, bounds.x, bounds.y, ..., phase*WIDTH, 0, (phase+1)*WIDTH, HEIGHT, ..);
  }
}
class YourApplet extends Applet {
  Thread animator = new Thread() {
    public void run() {
      while (!interrupted()) {
        sleep(1000);
        for (UIButton b : buttons) b.tick();
      }
    }
  void start() { animator.start(); }
  void stop() { animator.interrupt(); }
}

.: Truth Until Paradox!
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Kommi

Junior Member




All opinions will be lined up and shot!


« Reply #3 - Posted 2004-02-13 13:57:27 »

Hey Jeff what API is JInput in? I cant find it on sun's site.

Kommi
Offline swpalmer

JGO Coder




Where's the Kaboom?


« Reply #4 - Posted 2004-02-13 15:35:51 »

JInput is open of the Java Gaming "Core" APIs, it's open source..  look at jinput.dev.java.net

Offline mattocks

Senior Newbie




Java games rock!


« Reply #5 - Posted 2004-02-14 05:31:34 »

Here's a custom animated JButton class:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
// Animated JButton

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

public class HotButton extends JButton
{
      // Global class vars
     private final String imageNames[];      // names (URLs) of button's images
     private javax.swing.Timer t = null;      // animation control timer
     private int n = 0;                              // index of current image displayed

      // Constructor
     public HotButton(final String imageNames[], int speed)
      {
            super();
            setContentAreaFilled(false);
            setBorderPainted(false);
            setFocusPainted(false);
//            setSize( (new ImageIcon(imageNames[0])).getIconWidth(), (new ImageIcon(imageNames[0])).getIconHeight() );
           this.imageNames = imageNames;

            ActionListener timedAction = new ActionListener()
            {
                  public void actionPerformed(ActionEvent e)
                  {
                        setIcon( new ImageIcon(imageNames[n]) );
                        n = (n + 1) % imageNames.length;
                  }
            };

            t = new javax.swing.Timer(speed, timedAction);
            t.setInitialDelay(0);                        // Start up immediately
//            t.setCoalesce(true);                        // Prevent event flooding
//            t.start();                                          // Autostart
     } // end HotButton constructor

      // Can be invoked by any thread (since timer is thread-safe).
     public synchronized void start()
      {
            if ( !t.isRunning() )
            {
                  t.start();                  // Start animation!
           }
      }

      // Can be invoked by any thread (since timer is thread-safe).
     public synchronized void stop()
      {
            if ( t.isRunning() )
            {
                  t.stop();                  // Stop animation.
           }
      }

} // end class HotButton


and here's a demo which uses it:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class AnimatedButtonDemo extends JFrame
{
      // Global class vars
     int speed = 100;      // button refresh rate in ms
     String[] imageNames = {"images/duck0.jpg", "images/duck1.jpg", "images/duck2.jpg", "images/duck3.jpg"};
      HotButton button;
      boolean startstop = false;      // animation toggle flag

      // Constructor
     public AnimatedButtonDemo()
      {
            super("Animated Button Demo");

            button = new HotButton(imageNames, speed);
            button.addActionListener
            (
                  new ActionListener()
                  {
                        public void actionPerformed(ActionEvent e)
                        {
                              if (startstop)
                              {
                                    startstop = false;
                                    button.start();
                                    System.out.println("<< button started >>");
                              }
                              else
                              {
                                    button.stop();
                                    startstop = true;
                                    System.out.println("|| button stopped ||");
                              }
                        }
                  }
            );
            button.start();      // Autostart

            Container c = getContentPane();
            c.setLayout(null);                              // We'll do the layout ourselves
           button.setBounds(150,100, 93,90);
            c.add(button);

      } // end constructor

      public static void main(String[] args)
      {
            JFrame f = new AnimatedButtonDemo();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(400,300);
            f.setVisible(true);
      }
}


Have fun!
Craig
Offline Serethos

Junior Member




Java games rock!


« Reply #6 - Posted 2004-02-14 08:00:42 »

nice, at first thx for the helping answers. but one question for the end:

in your game projects, do you use custom classes or mods of the swing-components ?
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CopyableCougar4 (13 views)
2014-08-22 19:31:30

atombrot (28 views)
2014-08-19 09:29:53

Tekkerue (25 views)
2014-08-16 06:45:27

Tekkerue (23 views)
2014-08-16 06:22:17

Tekkerue (15 views)
2014-08-16 06:20:21

Tekkerue (22 views)
2014-08-16 06:12:11

Rayexar (61 views)
2014-08-11 02:49:23

BurntPizza (39 views)
2014-08-09 21:09:32

BurntPizza (31 views)
2014-08-08 02:01:56

Norakomi (37 views)
2014-08-06 19:49:38
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!