Using alpha in jpanel compoments

hi all,
I am overhiden jpanel and yours components using alpha and happens which components are drawing too in area left superior, and I dont know, why this happens, I wish post code here , but is to long... I do alpha in images, and no problems with that, but in compoments I dont know how make this... thanks
      class painel extends JPanel{
          public void paintComponent(Graphics g) {
              System.out.println("pintando "+alpha);
            ((Graphics2D) g).setComposite(
                    AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                                               alpha));
            g.setColor(getBackground());
           // g.fillRect(0,0,getWidth(),getHeight());
             g.fillRect(0,0,getWidth(),getHeight());
}

I try setOpaque(true), but fail...
import java.awt.AlphaComposite;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.*;
public class FadingExemple extends JFrame {
    public FadingExemple(){
    public static void main(String[] args) throws Exception {
       JFrame f = new JFrame();
       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       FadingOut glassOut = new FadingOut();
       FadingIn glassIn = new FadingIn();
     JPanel contentPane = new JPanel();
       //contentPane.setLayout(new java.awt.GridLayout(10,10));
       contentPane.setLayout(new java.awt.FlowLayout());
       //for(int row = 0; row < 10; row++)
         //  for(int column = 0; column < 10; column++) {
              contentPane.add(new JButton("Fading"));
              contentPane.add(new JButton("323232"));
              contentPane.add(new JButton("2347676767"));
       f.setContentPane(contentPane);
       f.pack();
       f.setSize(400,400);
       f.setVisible(true);
       try{Thread.sleep(500);}
       catch(InterruptedException e) {e.printStackTrace();}
       f.setGlassPane(glassOut);
       glassOut.setVisible(true);
       //glassOut.beginFade();
glassOut.beginFade(0.70f);
       // usando glassOut e apos glassIn -> glassIn faz aparecer
       // usando somente glassIn -> glassIn faz desaparecer rapido
       try{Thread.sleep(900);}
       catch(InterruptedException e) {e.printStackTrace();}
       f.setGlassPane(glassIn);
       glassIn.setVisible(true);
       glassIn.beginFade();
    public static class FadingIn extends JPanel implements ActionListener
              private float opacity = 1f;
              private Timer fadeTimer;
                 public void beginFade() {
            fadeTimer = new javax.swing.Timer(75,this);
            fadeTimer.setInitialDelay(0);
            fadeTimer.start();
        public void actionPerformed(ActionEvent e) {
               opacity -= .01;
               System.out.println(opacity);
            if(opacity < 0) {
                opacity = 0;
                fadeTimer.stop();
                fadeTimer = null;
            repaint();
           public void paintComponent(Graphics g) {
        ((Graphics2D) g).setComposite(
                    AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                                               opacity));
            g.setColor(getBackground());
            g.fillRect(0,0,getWidth(),getHeight());
    public static class FadingOut extends JPanel
            implements ActionListener
        private float opacity = 0f;
        private Timer fadeTimer;
        public void beginFade() {
            fadeTimer = new javax.swing.Timer(75,this);
            fadeTimer.setInitialDelay(0);
            fadeTimer.start();
        public void beginFade(float opacity){
            this.opacity = opacity;
        public void actionPerformed(ActionEvent e) {
            opacity += .03;
            System.out.println(opacity);
            if(opacity > .5) {
                opacity = 0.5f;
                fadeTimer.stop();
                fadeTimer = null;
            repaint();
        public void paintComponent(Graphics g) {
            ((Graphics2D) g).setComposite(
                    AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                                               opacity));
            g.setColor(getBackground());
            g.fillRect(0,0,getWidth(),getHeight());
}

Similar Messages

  • Can we use setinsets in JPanel?

    can we use setinsets in JPanel?

    Instead of posting twice in the wrong forum, how about posting once in the correct section next time?

  • Can we use setInsets into JPanel?

    can we use setInsets into JPanel?
    Advance wishes

    yes.So? If LayoutManagers handle insets and JPanels can have LayoutManagers, you will have Inset handling in JPanels.

  • Inserting a Gui program using JFrames and JPanel

    I'm trying to insert a chat program into a game that I've created! The chat program is using JFrames and JPanels. I want to insert this into a GridLayout and Panel. How can I go about doing this?

    whatever is in the frame's contentPane now, you add to a separate JPanel.
    you also add your chat stuff to the separate panel
    the separate panel is added to the frame as the content pane

  • Using alpha-numeric characters as plotchart itemrenderers

    I understand, a developer can import a gif or jpg image to use as a custom itemrenderer in a plotchart.  I would like to be a litte more simple and use alpha-numeric characters as the itemrenderer.  For example, a plot chart describing some data for Argentina and Brazil would contain a bunch of A's and B's scattered about the plotchart.  Is there an easy way to do this without resorted to creating gifs and jpegs for each character I'd need to use.

    wondering under Mac OSX is there a similar feature such as in a windows environment to do the Alt + 0169 which should equal the Copyright symbol.
    Essentially no. On a Mac you use either the Character Palette or a keyboard shortcut like Option/Alt + g (which gives ©).
    There is however a special software keyboard layout called Uncode Hex Input which lets you input Alt + the Unicode hex codepoint to produce characters. With that layout active, Alt + 00A9 gives you ©.

  • Copying member("aTextMemb").image into a rect in an image that uses alpha

    Hi all. I'm currently developping a strategy game with Director, and one of the things I've run into is that i want to update the number of units I have in a panel (on initial game setup) via 1) updating a text member that holds the number of units left to setup and copyPixeling the image onto the panel. This I've acheived except that since my text member image doesnt have alpha originally and the panel is semitransparent, a white (no matter the bckgrnd color I set for the text member) bounding box appears in the final result. I guess the way to go is duplicating the text member image and make it a 1 bit mask image then using the apropiate imaging lingo command (dont remember if it's copyPixels or another at this point). Imaging lingo is very interesting for me since normally I built all my aplications using the score directly (15 years exp with Director). This is my first game where I mostly rely on parent scripting and in some situations imaging lingo.
    This is currently the handler that does the job. It: 1) stores the image of the text member "panelCount" 2) defines the destinatiion rectangle where it will be copied in the panel bitmap and 3) copies it (but as I said the correct alpha is missing).
    on updateUnitsDisplay me
      member("panelCount").text= string(pPanelUnitCount)
      -- we retrieve the image of the text member that stores how many units left in the panel
      _textImage= member("panelCount").image 
      bottomMargin= 20 -- distance from the bottom of the panel that we want the text to be
      _left= (sprite(me.spriteNum).width- _textImage.width)/2
      _top= sprite(me.spriteNum).height- bottomMargin- (_textImage.height/2)
      _right= _left+ _textImage.width
      _bottom= _top+ _textImage.height
      destRect= rect(_left, _top, _right, _bottom)
      pPanelMember.image.copyPixels(_textImage, destRect, _textImage.rect) 
    end updateUnitsDisplay
    Your proposals and thoughts are welcome (specially good ones )
    EDIT: I've said above that my textImage wouldnt have alpha originally. Well, i think that was wrong according to what I've found in he scripting dictionary under the image() section "When you create a new image object, the background color defaults to white (color(255,255,255)), and the alpha channel is completely opaque (color(0,0,0))."
    On the other hand, the paramList in the copyPixels command should do it I think (a matte can be defined, also and ink mode for the copied pixels can be used although my first experiments have not worked yet).

    I think I got it. The paramList in the copyPixels command has been enough to get rid of the white box around the text (using #ink: 36 which is bckgrnd transparent in it), the problem was that I was using the same white for foreground and background colors in the text member (been some time not using director and misplaced the false white I used to use in these cases in the color selector). Bottom line, dont use exact same color values for back and fore colors of the text member. I've observed also that using the alpha of the image (useAlpha= true) makes it well antialiased while not using the alpha does produces a bad image of the text (btw, the font of the text is an inserted text media element of course). I keep investigating

  • When using Alpha to outline photos in an ebook does it stay outlined across other platforms or programs

    I am creating an ebook in Keynote with animation, and some movies. Then I plan on publishing it with iAuthor. Then I want to publish it with other book sellers, i.e. Amazon and others. What are the concerns with everything working in the other platforms and what do I need to do? Also, I'm concerned about using the Alpha programs to outline photos. It does not seem to work after Alpha to save them into iphoto for reuse. What happens to those photos when going to another device, program. Do they stay outlined? Any help you can offer would be appreciated. Thanks

    Tom -
    In Keystone I have some art that apprear in the image and text and they stay there in playing after importing them into quicktime movie and placing them into iAuthor. When I preview them on the iPad they appear and then dissapear. The page goes back to the beginning after the movie is complete without the image. The page is to stay with the image while the reader finishes the page and then goes to the next. How can I get the  page to stat intact. All ideas appreciated.
    Thanks Jack

  • Use JWindow, JInternalFrame, JPanel, or JDialog

    Hello,
    My main window application extends a JFrame. When a component of the JFrame is mouse clicked,I want to open a popup window on top of this frame.
    The opened window is used to receive input from the user; with these properties: title bar, resizeable, can close with the "X" on the right side of the title bar, no minimizable or maximizable buttons on the title bar.
    1. I am very unsure whether I should use: a JWindow, JInternalFrame, JPanel, JDialog, JPopupMenu (probably not since I don't need a menu) to create the popup window. I think I should use JWindow, but am not sure.
    2. Also, I am unsure whether I can use JWindow and JInternalFrame with JFrame as the main app window.
    Thank you for your advice.

    If you want a popup window on top of this frame, you can either choose JFrame, JDialog or JWindow. They all have the own characteristics.
    JFrame: Usually application will use it as the base. Because It has a title bar with minimizable, maximizable and exit button.
    JDialog: Usually work as a option / peference / about dialog (Ex. Just click the IE about to see). Because it has a smaller title bar with only maximizable and exit button and the model setting. If model is to TRUE, that means all the other area of the window will be disable except the opened dialog own.
    JWindow: Usually use as a splash to display logo or welcome message.
    JInternalFrame: It display inside a desktop panel of JFrame. Just like the multi-documents function inside the MS Words.

  • How do I get MacBook Pro to use Alpha Network wifi usb adapter?

    Using OS X.  Alpha Network usb wifi adapter using Ralink wireless utility.  Network utility says it is connected as 802.11 n WLAN.  But my browsers (Safari and Firefox) do not use the adapter to connect to the internet.  How do I turn off the internal wifi card and get the OS to recognize the usb adapter?

    you have to have the right drivers for your usb data stick.....check the website of the manufacturer for drivers.
    to disable your wifi, click on the wifi icon and select, turn wifi off.
    good luck..

  • Unable to paint (using paint() in JPanel) inside mouse listeners

    This is hard to explain but I'll do my best :)
    I've created a little game and at some point I needed to make images "move" on the JPanel (through paint()), on a checkers-based game board.
    The game works like so:
    it has a mouse listener for clicks and movement, and the main game process is THINK(), REPAINT(), which is repeated until the user wins (the above is inside a while).
    The mouse actions were added to the constructor so they are always active, THINK changes the enemy's locations, and REPAINT simply calls "paint()" again.
    The picture is either an enemy or the player, and it can only "rest" on squares.
    (e.g. point's x and y must be divided in 50).
    While doing that, I wanted to make the movement more sleek and clean,
    instead of them simply jumping from one square to the other with a blink of the eye.
    So, I've created MOVEACTOR, that "moves" an enemy or a player from its current point (actor.getPoint()) to the requested future square (futurePoint).
    //actor = enemy or player, has getPoint() that returnes the current point on the board where he rests on.
    //futurePoint = the new point where the enemy or player should be after the animation.
    //please ignore obvious stuff that has nothing to do with what I asked -- those will be deleted in the future, for they are only temporary checking extra lines and stuff.
    //also feel free to ignore the "jumpX" things. Those are just to change images, to imitate physical "jumping" animation.
    protected void moveActor(Actor actor, Point futurePoint)
              Point presentPoint = actor.getPoint();
              int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
              int addToX, addToY;
              if (futurePoint.getX() > x) addToX = 1;
              else addToX = -1;
              if (futurePoint.getY() > y) addToY = 1;
              else addToY = -1;
              Point middlePoint = new Point(x,y);
              int imageCounter = 0;
              while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
                   imageCounter++;
                   x+=addToX;
                   y+=addToY;
                   middlePoint.setLocation(x,y);
                   actor.setPoint(middlePoint);
                   /*if (imageCounter<=10) actor.setStatus("jump1");
                   else if (imageCounter<=40) actor.setStatus("jump2");
                   else if (imageCounter<=50) actor.setStatus("jump3");*/
                   repaint();
                   try {animator.sleep(1);} catch (InterruptedException e) {}
              //actor.setStatus("idle");
         }I use the above on several occasions:
    [1] When an enemy moves. Summary:
                             if (playerIsToVillainsRight) xToAdd = 50;
                             else if (playerIsToVillainsLeft) xToAdd = -50;
                             else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                             if (playerIsBelowVillain) yToAdd = 50;
                             else if (playerIsAboveVillain) yToAdd = -50;
                             else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                             Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                             moveActor(actors[currentVillain], futurePoint);[2] When the player moves. Summary (this is inside the mouseClicked listener):
    //mouseLocation = MouseWEvent.getPoint();
    //stl, str, etc = rectangles that represents future location of the player on the board.
              if (waitingForPlayer) {
                   if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                        moveActor(actors[0], stl.getLocation());
                        waitingForPlayer = false;
                   if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                        moveActor(actors[0], str.getLocation());
                        waitingForPlayer = false;
                   if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                        moveActor(actors[0], sbl.getLocation());
                        waitingForPlayer = false;                                   
                   if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                        moveActor(actors[0], sbr.getLocation());
                        waitingForPlayer = false;
    SO ... WHAT IS THE QUESTION?!?
    What I see when I run the game:
    the animation of the enemy (first code) works, but the animation of the player (second code, inside the mouse listeners) -- doesn't!
    The purpose of the moveActor is to move the enemy or player pixel by pixel, until its in the future point,
    instead of skipping the pixels between the squares and going straight for the future location.
    So what comes out is, that the enemy is moving pixel by pixel, and the player simply jumps there!
    I doublechecked and if I use moveActor with the player OUTSIDE the mouse listener, it works (i think).
    Any ideas what is the source of this problem?
    Hope I made myself clear enough :D
    Thanks,
    Eshed.

    I don't know if thats what happens, nor how to fix the thread problems. The mosue actions are "threaded" by default, no? And the moving thing happens after the mouse was clicked, and if the enemy's moving the user can still move his mouse and get responses, like "enemy didn't move yet" and stuff.
    Here's the complete GamePanel.java:
    //drawings
    import javax.swing.ImageIcon;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    //events
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    //tools
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.MediaTracker;
    import java.awt.Dimension;
    //panels, buttons, etc
    import javax.swing.JPanel;
    /** The Game Panel.
    *The panel's size is 500x500, and each square is squaresized 50.
    *This is where the game actually "exists". Here its being updated, drawn, etc.*/
    public class GamePanel extends JPanel implements Runnable
         private static final int PWIDTH = 500;                              //Width of the panel.
         private static final int PHEIGHT = 500;                              //Height of the panel.
         private static final int SQUARESIZE = 50;                         //Size of each square in the panel.
         private boolean working = false;                                   //Game keeps going until this is FALSE.
         private volatile Thread animator;                                   //The animation thread.
         private ImageIcon stand,fall;                                        //Images for the background - ground and water.
         private static ImageHandler ih;                                        //An image handler for image loading.
         private int numOfImages = 0;                                        //Number of total images (max image qunatity).
         private Actor[] actors;                                                  //The actors: [0] is the player, rest are enemies.
         private Point mouseLocation;                                        //Saves the current mouse location for checking where the mouse is
         protected Rectangle stl, str, sbl, sbr;                              //squares around the player, for mouse stuff.
         protected Rectangle v1, v2, v3, v4, v5;                              //squares around each villain, for mouse stuff.
         protected Rectangle wholeBoard = new Rectangle(0,0,PWIDTH,PHEIGHT);
         protected boolean waitingForPlayer = true;
         private int currentVillain = 1;
         private boolean inSight = false;
         // in methods other than the listeners.
         /** Waits for the Window (or whatever this panel loads in) to settle in before doing anything.*/
         public void addNotify()
              super.addNotify();                                                                           //When the super finishes...
              go();                                                                                                         //..go, go, go!
         /** Starts the game.*/
         private void go()
              if (animator==null || !working)     {                                        //if the game isn't in process,
                   animator = new Thread(this);                                        //make the animator as the main process,
                   animator.start();                                                                      //and start it (because of the runnable it launches "run()".
         /**Constructor of the Game Panel.*/
         public GamePanel()
              numOfImages = 14;                                                                      //Total image num.
              ih = new ImageHandler(this,numOfImages);               //Setting a new image handler for the images.
              ih.addImage("player_idle", "images/p_idle.png");          //Adding images.
              ih.addImage("villain_idle", "images/v_idle.png");
              ih.addImage("stand", "images/stand.gif");
              ih.addImage("fallpng", "images/fall.png");
              ih.addImage("fall", "images/fall.gif");
              ih.addImage("ghost", "images/ghost.gif");
              ih.addImage("villain_angry", "images/v_angry.png");
              ih.addImage("player_angry", "images/p_angry.png");
              ih.addImage("player_jump1", "images/p_j1.gif");
              ih.addImage("player_jump2", "images/p_j2.gif");
              ih.addImage("player_jump3", "images/p_j3.gif");
              ih.addImage("villain_jump1", "images/v_j1.gif");
              ih.addImage("villain_jump2", "images/v_j2.gif");
              ih.addImage("villain_jump3", "images/v_j3.gif");
              setPreferredSize(new Dimension(PWIDTH,PHEIGHT));     //Setting size of the panel.
              setFocusable(true);                                                                                //This and the next makes the window "active" and focused.
              requestFocus();
              /** Mouse hovering settings.*/
              addMouseMotionListener( new MouseMotionAdapter()
                   /** When the mouse is moving, do these stuff.*/
                   public void mouseMoved(MouseEvent e1)
                         *  |  stl  |       | str   |          stl = squareTopLeft
                         *  |_______|_______|_______|       str = squareTopRight
                        *   |       |current|       |         current = player's location
                        *   |_______|_______|_______|       sbl = squareBottomLeft
                        *   |  sbl  |       |  sbr  |       sbr = squareBottomRight
                        *   |_______|_______|_______|
                        mouseLocation = e1.getPoint();
                        Dimension defaultSquareDimension = new Dimension(50,50);
                        //current-player-location points
                        Point topLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY());
                        Point topRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY());
                        Point bottomLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY()+50);
                        Point bottomRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY()+50);
                        //four-squares-around-the-player points
                        //T = top, B = bottom, R = right, L = left
                        Point ptl = new Point((int)topLeft.getX()-50,(int)topLeft.getY()-50);
                        Point ptr = new Point((int)topRight.getX(),(int)topRight.getY()-50);
                        Point pbl = new Point((int)bottomLeft.getX()-50,(int)bottomLeft.getY());
                        Point pbr = new Point((int)bottomRight.getX(),(int)bottomRight.getY());
                        //ghosts
                        stl = new Rectangle (ptl, defaultSquareDimension);
                        str = new Rectangle (ptr, defaultSquareDimension);
                        sbl = new Rectangle (pbl, defaultSquareDimension);
                        sbr = new Rectangle (pbr, defaultSquareDimension);
                        Rectangle player = new Rectangle(topLeft, defaultSquareDimension);     //rectangle of player
                        if (stl.contains(mouseLocation) && !hoveringVillain(stl))
                             actors[8] = new Actor("ghost", ptl);
                             else actors[8] = null;
                        if (str.contains(mouseLocation) && !hoveringVillain(str))
                             actors[9] = new Actor("ghost", ptr);
                             else actors[9] = null;
                        if (sbl.contains(mouseLocation) && !hoveringVillain(sbl))
                             actors[10] = new Actor("ghost", pbl);
                             else actors[10] = null;
                        if (sbr.contains(mouseLocation) && !hoveringVillain(sbr))
                             actors[11] = new Actor("ghost", pbr);
                             else actors[11] = null;
                   private boolean hoveringVillain(Rectangle r)
                        boolean onVillain = false;
                        for (int i=1; i<=5 && !onVillain; i++) onVillain = actors.getRect().equals(r);
                        return onVillain;
              /** Mouse-click settings.
              Note: only usable after moving the mouse. /
              addMouseListener (new MouseAdapter()
                   /** When the mouse button is clicked */
                   public void mouseClicked (MouseEvent me)
                        mouseClickedAction(me);
         private boolean hoveringVillain(Rectangle r)
              boolean onVillain = false;
              for (int i=1; i<=5 && !onVillain; i++) onVillain = actors[i].getRect().equals(r);
              return onVillain;
         public void mouseClickedAction(MouseEvent me)
              System.out.println("Point: "+me.getX()+","+me.getY());
              if (waitingForPlayer) {
                   //causes error if the mouse wasn't moved uptil now. try it.
                   mouseLocation = me.getPoint();
                   if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                        moveActor(actors[0], stl.getLocation());
                        waitingForPlayer = false;
                   if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                        moveActor(actors[0], str.getLocation());
                        waitingForPlayer = false;
                   if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                        moveActor(actors[0], sbl.getLocation());
                        waitingForPlayer = false;                                   
                   if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                        moveActor(actors[0], sbr.getLocation());
                        waitingForPlayer = false;
              } else MiscTools.shout("Wait for the computer to take action!");
              if (actors[0].getPoint().getY() == 0){
                   for (int i=1; i<=5; i++){
                             actors[i].setStatus("angry");
                   //repaint();
                   MiscTools.shout("Game Over! You Won!");
         /** First thing the Game Panel does.
         Initiating the variables, and then looping: updating, painting and sleeping./
         public void run() {
    Thread thisThread = Thread.currentThread();                                                  //Enables the restart action (two threads needed).
    init();                                                                                                                                            //Initialize the variables.
    while (animator == thisThread && working){                                                  //While the current thead is the game's and it's "on",
                   think();                                                                                                                             //Update the variables,
                   repaint();                                                                                                                             //Paint the stuff on the panel,
                   try {Thread.sleep(5);} catch (InterruptedException ex) {}                    //And take a wee nap.
         /** Initializing the variables.*/
         private void init()
              currentVillain = 1;
              working = true;                                                                                //Make the game ready for running.
              inSight = false;
              actors = new Actor[12];                                                                      //Six actors: player and 5*villains.
              actors[0] = new Actor("player", 200, 450);                                             //The first actor is the player.
              int yPoint = 50;                                                                           //The Y location of the villains (first row).
              /* ACTORS ON TOP, RIGHT, LEFT
              actors[1] = new Actor ("villain", 0, 350);
              actors[2] = new Actor ("villain", 0, 150);
              actors[3] = new Actor ("villain", 50, 0);
              actors[4] = new Actor ("villain", 250, 0);
              actors[5] = new Actor ("villain", 450, 0);
              actors[6] = new Actor ("villain", 450, 200);
              actors[7] = new Actor ("villain", 450, 400);
              /* ACTORS ON TOP*/
              for (int i=1; i<actors.length-4; i++){                                                  //As long as it doesnt go above the array...
                   actors[i] = new Actor ("villain", yPoint, 0);                                   //init the villains
                   actors[i].setStatus("idle");
                   yPoint+=100;                                                                           //and advance in the Y axis.
         /** Updating variables.*/
         private void think()
              if (!waitingForPlayer){
                   //initialize
                   int playerX = (int)actors[0].getPoint().getX();
                   int playerY = (int)actors[0].getPoint().getY();
                   boolean moved = false;
                   wholeBoard = new Rectangle(0,0,500,500);     //needed to check whether an actor is inside the board
                   //for (int in = 0; in<=5; in++) actors[in].setStatus("idle"); //"formatting" the actor's mood
                   if (playerY <= 1000) inSight = true;     //first eye contact between the player and villains.
                   int closestVillainLevel = 0;
                   int[] vills = closestVillain();
                   int moveCounter = 0;
                   if (inSight) {
                        while (!moved){               //while none of the villains made a move
                        moveCounter++;
                        if (moveCounter == 5) moved = true;
                        else{
                             currentVillain = vills[closestVillainLevel];
                             int villainX = (int)actors[currentVillain].getPoint().getX();
                             int villainY = (int)actors[currentVillain].getPoint().getY();
                             //clearing stuff up before calculating things
                             boolean playerIsBelowVillain = playerY > villainY;
                             boolean playerIsAboveVillain = playerY < villainY;
                             boolean playerIsOnSameRowAsVillain = playerY == villainY;
                             boolean playerIsToVillainsRight = playerX > villainX;
                             boolean playerIsToVillainsLeft = playerX < villainX;
                             boolean playerIsOnSameColumnAsVillain = playerX == villainX;
                             //System.out.println("\n-- villain number "+currentVillain+" --\n");
                             int xToAdd = 0, yToAdd = 0;
                             if (playerIsToVillainsRight) xToAdd = 50;
                             else if (playerIsToVillainsLeft) xToAdd = -50;
                             else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                             if (playerIsBelowVillain) yToAdd = 50;
                             else if (playerIsAboveVillain) yToAdd = -50;
                             else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                             Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                             if (legalPoint(futurePoint)){
                                  moveActor(actors[currentVillain], futurePoint);
                                  moved = true;
                                  //System.out.println("\nVillain "+currentVillain+" is now at "+actors[currentVillain].getPoint());
                             else closestVillainLevel=circleFive(closestVillainLevel);
                        } //end of else
                        } //end of while
                        //currentVillain = circleFive(currentVillain); //obsolete
                   } //end of ifInSight
                   waitingForPlayer = true;
         private boolean legalPoint(Point fp)
              return (wholeBoard.contains(fp) && !onPeople(fp) && legalSquare(fp));
         private boolean legalSquare(Point p)
              if ( (p.getX()==0 || p.getX()%100==0) && (p.getY()/50)%2!=0 ) return true;
              if ( (p.getX()/50)%2!=0 && (p.getY()==0 || p.getY()%100==0) ) return true;
              return false;
         //return the closest villain to the player, by its level of distance.
         public int[] closestVillain()
              //System.out.println("Trying to find the closest villain...");
              double[] gaps = new double[5];     //the distances array
              //System.out.println("The villains' distances are: ");
              for (int i=0; i<5; i++){
                   gaps[i] = distanceFromPlayer(actors[i+1].getPoint());     //filling the distances array
                   //System.out.print(gaps[i]+", ");
              int[] toReturn = new int[5];
              double smallestGapFound;
              double[] arrangedGaps = smallToLarge(gaps);
              for (int level=0; level<5; level++){
                   smallestGapFound = arrangedGaps[level];
                   for (int i=1; i<=5; i++){
                        if (smallestGapFound == distanceFromPlayer(actors[i].getPoint())){
                             toReturn[level] = i;
              return toReturn;
         private double[] smallToLarge(double[] nums)
              //System.out.println("\nArranging array... \n");
              double[] newArray = new double[5];
              int neweye = 0;
              double theSmallestOfTheArray;
              for (int i=0; i<nums.length; i++){
                   theSmallestOfTheArray = smallest(nums);
                   //System.out.println("\t\t>> Checking whether location "+i+" ("+nums[i]+") is equal to "+theSmallestOfTheArray);
                   if (nums[i] == theSmallestOfTheArray && nums[i]!=0.0){
                        //System.out.println("\t\t>> Adding "+nums[i]+" to the array...");
                        newArray[neweye] = nums[i];
                        //System.out.println("\t\t>> Erasing "+nums[i]+" from old array...\n");
                        nums[i] = 0.0;
                        neweye++;
                        i=-1;
              /*System.out.print("\nDONE: ");
              for (int i=0; i<newArray.length; i++)
                   System.out.print("["+newArray[i]+"] ");
              System.out.println();*/
              return newArray;
         private double smallest (double[] nums)
                   //System.out.print("\tThe smallest double: ");
                   double small = 0.0;
                   int j=0;
                   while (j<nums.length){               //checking for a starting "small" that is not a "0.0"
                        if (nums[j]!=0.0){
                             small = nums[j];
                             j = nums.length;
                        } else j++;
                   for (int i=1; i<nums.length; i++){
                        if (small>nums[i] && nums[i]!=0.0){
                             small = nums[i];
                   //System.out.println(small+".");
                   return small;
         private double distanceFromPlayer(Point vp)
              Point pp = actors[0].getPoint(); //pp=plaer's point, vp=villain's point
              double x = Math.abs(vp.getX() - pp.getX());
              double y = Math.abs(vp.getY() - pp.getY());
              return Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
         private int circleFive(int num)
                   if (num>=5) return 0;
                   else return num+1;
         private boolean onPeople(Point p)
              for (int jj=0; jj<=5; jj++)
                   if (jj!=currentVillain && p.equals(actors[jj].getPoint()))
                        return true;
              return false;
         /** Painting the game onto the Game Panel.*/
         public void paintComponent(Graphics g)
              Graphics2D graphics = (Graphics2D)g;                                                            //Reset the graphics to have more features.
              //draw bg
              graphics.setColor(Color.white);                                                                                //"format" the panel.
              graphics.fillRect(0,0,500,500);
         char squareType = 'f';                                                                                                    //First square's type (stand or fall).
         for (int height=0; height<PHEIGHT; height=height+SQUARESIZE){     //Painting the matrix bg.
                   for (int width=0; width<PWIDTH; width=width+SQUARESIZE){
                        if (squareType=='f') {                                                                                               //If a "fall" is to be drawn,
                             ih.paint(graphics, "fallpng", new Dimension(width,height));          //Draw a non-animated image to bypass white stuff.
                             ih.paint(graphics, "fall", new Dimension(width,height));               //Draw the water animation.
                             squareType = 's';                                                                                                    //Make the next square a "stand".
                        } else if (squareType=='s'){                                                                                //If a "stand" is to be drawn,
                             ih.paint(graphics, "stand", new Dimension(width,height));          //Draw the ground image,
                             squareType = 'f';                                                                                                    //and make the next square a "fall".
                   if (squareType=='f') squareType = 's';                                                                 //After finishing a row, switch again so
                   else squareType = 'f';                                                                                                    // the next line will start with the same type (checkers).
              for (int i=actors.length-1; i>=0; i--){                                                                           //Draw the actors on the board.
                   if (actors[i]!=null)
                        ih.paint(graphics, actors[i].currentImage(), actors[i].getPoint());
         /** Restart the game.
         Or, in other words, stop, initialize and start (again) the animator thread and variables./
         public void restart()
              System.out.println("\n\n\nRESTARTING GAME\n\n\n");
              animator = null;                                                                                                                   //Emptying the thread.
              init();                                                                                                                                                 //Initializing.
              animator = new Thread(this);                                                                                     //Re-filling the thread with this panel's process.
              animator.start();                                                                                                                   //launch "run()".
         protected void moveActor(Actor actor, Point futurePoint)
              Point presentPoint = actor.getPoint();
              int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
              int addToX, addToY;
              if (futurePoint.getX() > x) addToX = 1;
              else addToX = -1;
              if (futurePoint.getY() > y) addToY = 1;
              else addToY = -1;
              Point middlePoint = new Point(x,y);
              int imageCounter = 0;
              while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
                   imageCounter++;
                   x+=addToX;
                   y+=addToY;
                   middlePoint.setLocation(x,y);
                   actor.setPoint(middlePoint);
                   /*if (imageCounter<=10) actor.setStatus("jump1");
                   else if (imageCounter<=40) actor.setStatus("jump2");
                   else if (imageCounter<=50) actor.setStatus("jump3");*/
                   repaint();
                   try {animator.sleep(1);} catch (InterruptedException e) {}
              //actor.setStatus("idle");

  • Want to use JDeskTopPane in JPanel

    Hi
    I want to use JDeskTopPane in a JPanel. The reason is that I want to use some JInternalFrames within a particular panel of my application.
    I am using an applet so obviously I could use this.setContentPane() when loading the APPLET, however I need some kind of setContentPane() method on my JPanel which I am using.
    Not sure if you can do that to a JPanel.
    cheers,
    Oliver

    This section from the Swing tutorial shows you how to use a JDeskTopPane and JInternalFrame:
    http://java.sun.com/docs/books/tutorial/uiswing/components/internalframe.html

  • How to: Cut Selection to 0 pixels by 0 pixels using alpha channel

    Hello,
    I am trying to understand an action I found online. The action can be used to age a photograph. In this action
    there is a part that cuts a selection 0 pixels by 0 pixels using an alpha channel.
    For the past few days I have tried to duplicate that part of the action. And needless to say: I failed beyond words!
    All I want is to cut away the so called marching ants, not the part inside or outside of the selection, marching ants
    only.
    The original action can be downloaded here:
    http://mutato-nomine.deviantart.com/art/Vintage-Photo-10893481
    Thank you for taking a look.
    Kind regards,
    TackoDing
    (Pardon my English, I'm Dutch)
    Here's an image to give you a rough idea of the final result:

    Silkrooster,
    I only wish to cut the marching ants of the selected portion.
    Unfortenately when I use CTRL+X or EDIT>CUT the whole portion gets cut,
    not just the marching ants (cut selection to 0pixels by 0pixels).

  • (Another) problem with custom painting using JApplet and JPanel

    Hi all,
    I posted regarding this sort of issue yesterday (http://forums.sun.com/message.jspa?messageID=10883107). I fixed the issue I was having, but have run into another issue. I've tried solving this myself to no avail.
    Basically I'm working on creating the GUI for my JApplet and it has a few different JPanels which I will be painting to, hence I'm using custom painting. My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    public class TetrisClone extends JApplet {
         public void init() {
              setSize( 450, 500 );
              Container content = getContentPane();
              content.add( new mainGUI(), BorderLayout.CENTER );
              content.add( new rightGUI() , BorderLayout.LINE_END );
    class mainGUI extends JPanel {
         // Main bit where blocks fall
         public mainGUI() {
              setBackground( new Color(68,75,142) );
              setPreferredSize( new Dimension( 325, 500 ) );
              validate();
         public Dimension getPreferredSize() {
              return new Dimension( 450, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              // As a test. This shows up fine.
              g.setColor( Color.black );
              g.fillRect(10,10,100,100);
              g.setColor( Color.white );
              g.drawString("Main",45,55);
    class rightGUI extends JPanel {
         BufferedImage img = null;
         int currentLevel = 0;
         int currentScore = 0;
         int currentLines = 0;
         public rightGUI() {
              // The right panel. Has quite a few bits. Starts here..
              FlowLayout flow = new FlowLayout();
              flow.setVgap( 20 );
              setLayout( flow );
              setPreferredSize( new Dimension( 125, 500 ) );
              setBackground( new Color(27,34,97) );
              setBorder( BorderFactory.createMatteBorder(0,2,0,0,Color.black) );
              // Next block bit
              JPanel rightNext = new JPanel();
              rightNext.setPreferredSize( new Dimension( 100, 100 ) );
              //rightNext.setBackground( new Color(130,136,189) );
              rightNext.setOpaque( false );
              rightNext.setBorder( BorderFactory.createEtchedBorder(EtchedBorder.LOWERED) );
              Font rightFont = new Font( "Courier", Font.BOLD, 18 );
              // The player's playing details
              JLabel rightLevel = new JLabel("Level: " + currentLevel, JLabel.LEFT );
              rightLevel.setFont( rightFont );
              rightLevel.setForeground( Color.white );
              JLabel rightScore = new JLabel("Score: " + currentScore, JLabel.LEFT );
              rightScore.setFont( rightFont );
              rightScore.setForeground( Color.white );
              JLabel rightLines = new JLabel("Lines: " + currentLines, JLabel.LEFT );
              rightLines.setFont( rightFont );
              rightLines.setForeground( Color.white );
              JPanel margin = new JPanel();
              margin.setPreferredSize( new Dimension( 100, 50 ) );
              margin.setBackground( new Color(27,34,97) );
              JButton rightPause = new JButton("Pause");
              try {
                  img = ImageIO.read(new File("MadeBy.gif"));
              catch (IOException e) { }
              add( rightNext );
              add( rightLevel );
              add( rightScore );
              add( rightLines );
              add( margin );
              add( rightPause );
              validate();
         public Dimension getPreferredSize() {
                   return new Dimension( 125, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              g.setColor( Color.black );
              g.drawString( "blah", 425, 475 ); // Doesn't show up
              g.drawImage( img, 400, 400, null ); // Nor this!
              System.out.println( "This bit gets called fine" );
    }Any help would be greatly appreciated. I've read loads of swing and custom painting tutorials and code samples but am still running into problems.
    Thanks,
    Tristan Perry

    Many thanks for reminding me about the error catching - I've added a System.out.println() call now. Anywhoo, the catch block never gets run; the image get call works fine.
    My problem was/is:
    "My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:"
    I guess I should have expanded on that. Basically whatever I try to output in the public void paintComponent( Graphics g ) method of the rightGUI class doesn't get output.
    So this doesn't output anything:
    g.drawString( "blah", 425, 475 ); // Doesn't show up
    g.drawImage( img, 400, 400, null ); // Nor this!
    I've checked and experimented with setOpaque(false), however this doesn't seem to be caused by any over-lapping JPanels or anything.
    Let me know if I can expand on this :)
    Many thanks,
    Tristan Perry
    Edited by: TristanPerry on Dec 10, 2009 8:40 AM

  • Using alpha effect

    Im trying to fade text in using the alpha effect tool from
    one key frame to another. I have set up the first frame with a
    movie clip containing text set at 0% and set up a second frame
    further down the timeline with the alpha effect set at 100%. I then
    added the tween effect to create the fading in of the text. When i
    move the timeline along on the stage the effect works perfectly.
    However, when i publish and test the movie as an swf the effect
    doesnt work. I am left with the text just popping on to the screen
    as opposed to fading on. Any ideas whats going on?
    Thankyou. :)

    This is asked and answered almost daily.
    http://keyframer.com/forum/viewtopic.php?t=479
    Chris Georgenes
    Animator
    http://www.mudbubble.com
    http://www.keyframer.com
    Adobe Community Expert
    *\^^/*
    (OO)
    <---->
    suggy44 wrote:
    > Im trying to fade text in using the alpha effect tool
    from one key frame to
    > another. I have set up the first frame with a movie clip
    containing text set at
    > 0% and set up a second frame further down the timeline
    with the alpha effect
    > set at 100%. I then added the tween effect to create the
    fading in of the text.
    > When i move the timeline along on the stage the effect
    works perfectly.
    > However, when i publish and test the movie as an swf the
    effect doesnt work. I
    > am left with the text just popping on to the screen as
    opposed to fading on.
    > Any ideas whats going on?
    >
    > Thankyou. :)
    >

  • How can i use an inner Jpanel in another JPanel

    Hi, i need to put an inner panel in a container panel.I have been trying for hours but I couldn't make it work. Please waiting for help...
    public class Gui extends JFrame{
         public Gui() {
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setEnabled(true);
              setSize(500, 500);
              JPanel mainPanel=new JPanel();
              int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
              int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
              JScrollPane jsp=new JScrollPane(mainPanel,v,h);
              this.add(mainPanel);
              setContentPane(jsp);
                    //this part doesn't works
              JPanel innerPanel=new JPanel();
              innerPanel.setSize(50, 50);
              innerPanel.setLocation(100, 100);
              innerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
              innerPanel.setBackground(Color.red);
                   //this part doesn't works
         public static void main(String[] args) {
              Gui gui= new Gui();
              gui.setVisible(true);
    }

    I'm sorry it's my bad that i have forgotten to add the innerPanel to mainPannel (But of course i tried it in the original code :) ). Now i made the changes you suggested but there are still problems.
    I can see the innerPanel now, but the size and the position of the innerPanel doesn't works.
    public Gui() {
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setEnabled(true);
              setSize(500, 500);
              JPanel mainPanel=new JPanel();
              int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
              int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
              JScrollPane jsp=new JScrollPane(mainPanel,v,h);
              getContentPane().add(jsp);
              JPanel innerPanel=new JPanel();
              innerPanel.setSize(500, 500);
              innerPanel.setLocation(400, 400);
              innerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
              innerPanel.setBackground(Color.red);
                    mainPanel.add(innerPanel);
                    //also i tried
                    //getContentPane().add(innerPanel);
                    //or
                    //jsp.add(innerPanel);        
    ...

Maybe you are looking for

  • Using sunperf in shared libraries

    Hi, I would like to support sunperf in one software project which uses cblas. The code using cblas is a dynamically loadable library (python module). My problem is that using -xlic_lib=sunperf does not work when building shared libraries. More concre

  • How to list column names and data types for a given table using SQL

    I remember that it is possible to use a select statement to list the column names and data types of databaase tables but forgot how its done. Please help.

  • Iphoto thumbnails disappear with each reboot

    My iPhoto thumbnails disappear any time I reboot or log out of iPhoto. I use the rebuild command and get them back, but they don't  stay. Is this a problem with iPhoto or the address where the thumbnails are stored?

  • Clip Book

    Every time i open a webpage, a HP Smart Web Printing Clip Book  window opens up as a left column.  How can I get rid of this? It is so annoying. George Kassis

  • Search Algorithms in Oracle

    What are the search algorithms that Oracle supports?