Rotate a JLabel

Hello again!
I am trying to rotate an image on a JLabel and I feel I am almost there! However the size does not seem to adjust so when I put it on my label it is far too small. The code I am using is below:
  protected ImageIcon poleImage = new ImageIcon("ai/Images/pole.jpg");
  protected Image img = Toolkit.getDefaultToolkit().getImage("ai/Images/pole.jpg");
public JLabel rotatePole(JLabel lbl)
   Image image;
   ImageIcon icon;
   image = img;
   icon = poleImage;
   int h = image.getHeight(lbl);
   int w = image.getWidth(lbl);
   rad = rad + toRad(30);
   BufferedImage bim = new BufferedImage(h, w, BufferedImage.TYPE_INT_RGB);
   Graphics2D g2d = (Graphics2D)(bim.createGraphics());
   g2d.translate(h, 0);
   g2d.rotate(rad);
   g2d.drawImage(image, 0, 0, w, h, lbl);
   icon = new ImageIcon(bim);
   lbl.setIcon(icon);
   image = bim;
   return(lbl);
public double toRad(double deg)
     double radians;
     radians = deg * 0.0174532925;
     return(radians);
}//end toRad()I am defining rad to be zero in the constructor and it sould be increasing by 30 degrees each time I hit the left arrow key. Also the returned lbl goes to the JLabel I use in my JPanel ( poleLbl = pole.rotatePole(poleLbl); )
What I am seeing is my full size image is replaced by a tiny square. Any help would be appreciated.
Thanks

OK. From the code provided by 74philip and the recommended link from camickr I put this together. I get no error messages of any kind.
I am calling the routine via:
private void processRKey()
  int offsetR;
  int newXcart;
  int newXpole;
//The line below is where I am calling the rotation methods
  poleLbl = pole.getLabel();
  poleLblSz = poleLbl.getPreferredSize();
//I threw this  in to try to re-establish the pole binding but alas no luck
// buildbindings();
  offsetR = 20;
  newXcart = cart.getXPos()+ offsetR;
  newXpole = pole.getXPos() + offsetR;
  positionLbls(newXcart, cart.getYPos(), newXpole, pole.getYPos());
  cart.setXPos(newXcart);
  pole.setXPos(newXpole);
  System.out.println("R: " + cart.getXPos() + " " + cart.getYPos());
}//end processRKey() What is happening is that my pole no longer moves in any direction nor does it rotate. My cart is still key-bound and does move left and right in response to arrow key strikes. What follows is my rotation routine.
public void Rotation()
   ClassLoader cl = Pole.class.getClassLoader();
   try
      bi = ImageIO.read(cl.getResourceAsStream(path));
      image = bi;
   catch(IOException ioE)
      JOptionPane.showMessageDialog(null, "Bufferd Image Load Failure\n");
   //getValue();
private BufferedImage getImage(double theta)
     double cos = Math.abs(Math.cos(theta));
     double sin = Math.abs(Math.sin(theta));
     double width  = image.getWidth();
     double height = image.getHeight();
     int w = (int)(width * cos + height * sin);
     int h = (int)(width * sin + height * cos);
     BufferedImage out = new BufferedImage(w, h, image.getType());
     Graphics2D g2 = out.createGraphics();
     g2.setPaint(UIManager.getColor("Panel.background"));
     g2.fillRect(0,0,w,h);
     double x = w/2;
     double y = h/2;
     AffineTransform at = AffineTransform.getRotateInstance(theta, x, y);
     x = (w - width)/2;
     y = (h - height)/2;
     at.translate(x, y);
     g2.drawRenderedImage(image, at);
     g2.dispose();
     return out;
public JLabel getLabel()
     Rotation();
     rad = rad + toRad(30);
     BufferedImage bi = getImage(rad);
     image = bi;
     //tempLbl.setIcon(new ImageIcon(bi));
     ImageIcon icon = new ImageIcon(image);
     tempLbl = new JLabel(icon);
     tempLbl.setHorizontalAlignment(JLabel.CENTER);
     return tempLbl;
/*private void getValue()
   rad = rad + toRad(30);
   BufferedImage bi = getImage(rad);
   tempLbl.setIcon(new ImageIcon(bi));
public double toRad(double deg)
     double radians;
     radians = deg * 0.0174532925;
     return(radians);
}//end toRad()I think it is just something obvious that I am too inexperienced to recognize.
Thanks for the help earlier, by the way!

Similar Messages

  • Rotate JLabel containing a imgicon

    I want to rotate a jlabel when its clicked. The label is containing a imgicon.
    I have tried to do like
    http://www.codeguru.com/java/articles/199.shtml
    but the label dont rotate, just the image (i think).
    The image image is a vertical filled rectangle, but when i try to click it, it becomes a square...
    The code for adding the ship to the contentpane
    ImageIcon img = new ImageIcon("bigship.gif");
    JLabel jLship =      new JLabel( "ship", img, SwingConstants.LEFT );
    jLship.setName("ship");
    jLship.setBounds(
         ship.getPosition().x * (jlPOpoGame.getWidth() / 11) + 5,
         ship.getPosition().y * (jlPOpoGame.getHeight() / 11) + 5,
         img.getIconWidth(),
         img.getIconHeight());
    getJPOwnGame().add(jLship ,new Integer(1), 0);And the code for changing the label inside a mouselistener.
    selected.setUI(new VerticalLabelUI(true));And the code for the UI:
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    class VerticalLabelUI extends BasicLabelUI
         static {
              labelUI = new VerticalLabelUI(false);
         protected boolean clockwise;
         VerticalLabelUI( boolean clockwise )
              super();
              this.clockwise = clockwise;
        public Dimension getPreferredSize(JComponent c)
             Dimension dim = super.getPreferredSize(c);
             return new Dimension( dim.height, dim.width );
        private static Rectangle paintIconR = new Rectangle();
        private static Rectangle paintTextR = new Rectangle();
        private static Rectangle paintViewR = new Rectangle();
        private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
         public void paint(Graphics g, JComponent c)
            JLabel label = (JLabel)c;
            String text = label.getText();
            Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();
            if ((icon == null) && (text == null)) {
                return;
            FontMetrics fm = g.getFontMetrics();
            paintViewInsets = c.getInsets(paintViewInsets);
            paintViewR.x = paintViewInsets.left;
            paintViewR.y = paintViewInsets.top;
             // Use inverted height & width
            paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
            paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
            paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
            paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
            String clippedText =
                layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);
             Graphics2D g2 = (Graphics2D) g;
             AffineTransform tr = g2.getTransform();
             if( clockwise )
                  g2.rotate( Math.PI / 2 );
                  g2.translate( 0, - c.getWidth() );
             else
                  g2.rotate( - Math.PI / 2 );
                  g2.translate( - c.getHeight(), 0 );
             if (icon != null) {
                icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
            if (text != null) {
                int textX = paintTextR.x;
                int textY = paintTextR.y + fm.getAscent();
                if (label.isEnabled()) {
                    paintEnabledText(label, g, clippedText, textX, textY);
                else {
                    paintDisabledText(label, g, clippedText, textX, textY);
             g2.setTransform( tr );
    }Why dont the JLabel rotate?

    I found the error, but one new occured... :(
    I rotate the label with
    selected.setBounds(e.getX(), e.getY(), selected.getHeight(), selected.getWidth());But the rotation works fine only one time, then it gets wrong! Look at
    http://mrserver.pointclark.net/tmp/rotate.jpg
    to how it looks.
    Picture 1: Start position.
    Picture 2: First click, rotate around where i clicked, OK.
    Picture 3: Second click, the image gets cropped! The label is rotated thoug, i can select it and drag it if i click where the image should be.
    Picture 4: Third click. The image is back to horizontal, looks ok!
    And then it switched between 3 and 4 when i continue to click!
    Can somebody help me?

  • When my thread starts running, at that time keylistener is not working.

    when my thread starts running, at that time keylistener is not working.
    plz reply me.

    //FrameShow.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.util.logging.Level;
    import java.awt.event.*;
    import java.util.*;
    public class FrameShow extends JFrame implements ActionListener,KeyListener
         boolean paused=false;
         JButton stop;
         JButton start;
         JButton exit;
         public IncludePanel CenterPanel;
         public FrameShow()
    CenterPanel= new IncludePanel();
              Functions fn=new Functions();
              int height=fn.getScreenHeight();
              int width=fn.getScreenWidth();
              setTitle("Game Assignment--Santanu Tripathy--MCA");
              setSize(width,height);
              setResizable(false);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              show();
              initComponents();
              DefaultColorSet();
              this.addKeyListener(this);
         this.setFocusable(true);
         public void initComponents()
              Container contentpane=getContentPane();
              //Creating Panel For Different Side
              JPanel EastPanel= new JPanel();
              JPanel WestPanel= new JPanel();
              JPanel NorthPanel= new JPanel();
              JPanel SouthPanel= new JPanel();
              //CenterPanel = new IncludePanel();
              //IncludePanel CenterPanel= new IncludePanel();
              EastPanel.setPreferredSize(new Dimension(100,10));
              WestPanel.setPreferredSize(new Dimension(100,10));
              NorthPanel.setPreferredSize(new Dimension(10,100));
              SouthPanel.setPreferredSize(new Dimension(10,100));
              //CenterPanel.setPreferredSize(new Dimension(200,200));
              //Adding Color to the Panels
              NorthPanel.setBackground(Color.green);
              SouthPanel.setBackground(Color.orange);
              CenterPanel.setBackground(Color.black);
              //Creating Border For Different Side
              Border EastBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border WestBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border NorthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border SouthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border CenterBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              //Creating Components For East Panel
              JLabel left= new JLabel("LEFT");
              JLabel right= new JLabel("RIGHT");
              JLabel rotate= new JLabel("ROTATE");
              left.setForeground(Color.blue);
              right.setForeground(Color.blue);
              rotate.setForeground(Color.blue);
              //Creating Components For West Panel
              ButtonGroup group = new ButtonGroup();
              JRadioButton rb1 = new JRadioButton("Pink",false);
              JRadioButton rb2 = new JRadioButton("Cyan",false);
              JRadioButton rb3 = new JRadioButton("Orange",false);
              JRadioButton _default = new JRadioButton("Black",true);
              rb1.setForeground(Color.pink);
              rb2.setForeground(Color.cyan);
              rb3.setForeground(Color.orange);
              _default.setForeground(Color.black);
              //Creating Components For North Panel
              JLabel name= new JLabel("Santanu Tripathy");
              name.setForeground(Color.blue);
              name.setFont(new Font("Serif",Font.BOLD,30));
              //Creating Components For South Panel
              start = new JButton();
              stop = new JButton();
              exit = new JButton();
              start.setToolTipText("Click this button to start the game");
              start.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              start.setText("START");
              start.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              start.setMaximumSize(new java.awt.Dimension(90, 35));
              start.setMinimumSize(new java.awt.Dimension(90, 35));
              start.setPreferredSize(new java.awt.Dimension(95, 35));
              if(paused)
                   stop.setToolTipText("Click this button to pause the game");
              else
                   stop.setToolTipText("Click this button to resume the game");
              stop.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              stop.setText("PAUSE");
              stop.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              stop.setMaximumSize(new java.awt.Dimension(90, 35));
              stop.setMinimumSize(new java.awt.Dimension(90, 35));
              stop.setPreferredSize(new java.awt.Dimension(95, 35));
              exit.setToolTipText("Click this button to exit from the game");
              exit.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              exit.setText("EXIT");
              exit.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              exit.setMaximumSize(new java.awt.Dimension(90, 35));
              exit.setMinimumSize(new java.awt.Dimension(90, 35));
              exit.setPreferredSize(new java.awt.Dimension(95, 35));
              //Adding some extra things to the Panels
              group.add(rb1);
              group.add(rb2);
              group.add(rb3);
              group.add(_default);
              //Adding Component into the Panels
              EastPanel.add(left);
              EastPanel.add(right);
              EastPanel.add(rotate);
              WestPanel.add(rb1);
              WestPanel.add(rb2);
              WestPanel.add(rb3);
              WestPanel.add(_default);
              NorthPanel.add(name);
              SouthPanel.add(start);
              SouthPanel.add(stop);
              SouthPanel.add(exit);
              //Adding Border Into the Panels
              EastPanel.setBorder(EastBr);
              WestPanel.setBorder(WestBr);
              NorthPanel.setBorder(NorthBr);
              SouthPanel.setBorder(SouthBr);
              CenterPanel.setBorder(CenterBr);
              //Adding Panels into the Container
              EastPanel.setLayout(new GridLayout(0,1));
              contentpane.add(EastPanel,BorderLayout.EAST);
              WestPanel.setLayout(new GridLayout(0,1));
              contentpane.add(WestPanel,BorderLayout.WEST);
              contentpane.add(NorthPanel,BorderLayout.NORTH);
              contentpane.add(SouthPanel,BorderLayout.SOUTH);
              contentpane.add(CenterPanel,BorderLayout.CENTER);
              //Adding Action Listeners
              rb1.addActionListener(this);
              rb2.addActionListener(this);
              rb3.addActionListener(this);
              _default.addActionListener(this);
              exit.addActionListener(this);
              start.addActionListener(this);
    try
              start.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        start.setEnabled(false);
    CenterPanel.drawCircle();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
    try
              stop.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        paused=!paused;
                        if(paused)
                             start.setToolTipText("Click this button to resume the game");
                             stop.setText("RESUME");
                        else
                             start.setToolTipText("Click this button to pause the game");
                             stop.setText("PAUSE");
    CenterPanel.pause();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
         public void DefaultColorSet()
              getContentPane().setBackground(Color.white);
         public void actionPerformed(ActionEvent AE)
              String str=(String)AE.getActionCommand();
              if(str.equalsIgnoreCase("pink"))
                   CenterPanel.setBackground(Color.pink);
              if(str.equalsIgnoreCase("cyan"))
                   CenterPanel.setBackground(Color.cyan);
              if(str.equalsIgnoreCase("orange"))
                   CenterPanel.setBackground(Color.orange);
              if(str.equalsIgnoreCase("black"))
                   CenterPanel.setBackground(Color.black);
              if(str.equalsIgnoreCase("exit"))
                   System.exit(0);
         public void keyTyped(KeyEvent kevt)
    //repaint();
    public void keyPressed(KeyEvent e)
              System.out.println("here key pressed");
              //CenterPanel.dec();
         public void keyReleased(KeyEvent ke) {}
    }//End of FrameShow.ja
    //IncludePanel.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.Graphics.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.util.*;
    import java.util.logging.Level;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class IncludePanel extends JPanel implements Runnable
    int x=0,y=0;
    int color_1=0;
    int color_2=1;
    int start=0;
    Thread th;
    Image red,blue,green,yellow;
    java.util.List image;
    static boolean PAUSE=false;
         public IncludePanel()
         red= Toolkit.getDefaultToolkit().getImage("red.png");
         blue= Toolkit.getDefaultToolkit().getImage("blue.png");
         green= Toolkit.getDefaultToolkit().getImage("green.png");
         yellow= Toolkit.getDefaultToolkit().getImage("yellow.png");
    public void paintComponent(Graphics g)
              super.paintComponent(g);
              draw(g);
    public void dec()
         System.out.println("in dec method");
         x=x+30;
    public void draw(Graphics g)
              g.setColor(Color.red);
              int xx=0,yy=0;
              for (int row=0;row<=12;row++)
                   g.drawLine(xx,yy,180,yy);
                   yy=yy+30;
              xx=0;
              yy=0;
              for (int col=0;col<=6;col++)
                   g.drawLine(xx,yy,xx,360);
                   xx=xx+30;
              if(color_1==0)
                   g.drawImage(red, x, y, this);
              else if(color_1==1)
                   g.drawImage(blue,x, y, this);
              else if(color_1==2)
                   g.drawImage(green,x,y, this);
              else if(color_1==3)
                   g.drawImage(yellow,x,y, this);
    x=x+30;
              if(color_2==0)
                   g.drawImage(red, x, y, this);
              else if(color_2==1)
                   g.drawImage(blue,x,y, this);
              else if(color_2==2)
                   g.drawImage(green,x,y, this);
              else if(color_2==3)
                   g.drawImage(yellow,x,y, this);
    x=0;
    public void drawCircle( )
         th=new Thread(this);
         th.start();
         public void pause()
              if(PAUSE)
                   th.resume();
                   PAUSE=false;
                   return;
              if(!PAUSE)
              PAUSE=true;
         public synchronized void run()
              Random rand = new Random();
              Thread ani=Thread.currentThread();
              while(ani==th)
                   if(PAUSE)
                        th.suspend();
                   if(y==330)
                        color_1 = Math.abs(rand.nextInt())%4;
                        color_2 = Math.abs(rand.nextInt())%4;
                        if(color_1==color_2)
                             color_2=(color_2+1)%4;
                        y=0;
                   else
                        y=y+30;
                   repaint();
                   try
                        Thread.sleep(700);
                   catch(Exception e)
         }//End of run
    i sent two entire program

  • JLabel rotation

    hi friends..I'm new to this forums and in need of help..
    i have a jpanel with jlabel added.
    i want to move the location of the jlabel in the panel in an angular manner from a fixed pivot point...from 0 to 90 degrees.
    i have tried using jlabel.setlocation method but its setting the location to some abrupt locations..some problem with my trignometric logic..kindly help!..code 'll be highly appriciated..:)
    thank you!

    private void jLayeredPane2MouseDragged(java.awt.event.MouseEvent evt) {                                          
            // TODO add your handling code here:
            if(clb1.getX()<evt.getX() && (clb1.getX()+clb1.getWidth()>evt.getX()))
                if(clb1.getY()<evt.getY() && (clb1.getY()+clb1.getHeight()>evt.getY()))
                    int x=evt.getX();
                    //shifting the origin to left bottom
                    int y=labelHeight-evt.getY();
                      float theta=Math.atan2(y,x);
                      clb1.setlocation(labelwidth*Math.cos(theta),labelwidth*Math.sin(theta));
                }heres the part of my code..clb1 is my jlabel with a circle imageicon..i want to move this label at 0 to 90 angle
    its moving at abrupt locations..:(

  • How can i rotate a PNG photo and keep the transparent background?

    current i use this method to rotate a photo, but the transparent background is lost.
    what can I do ?
    public CreateRotationPhoto(String photofile,String filetype,int rotation_value,String desfile){
                 File fileIn = new File(photofile);
               if (!fileIn.exists()) {
                   System.out.println(" file not exists!");
                   return;
               try {
                       InputStream input = new FileInputStream(fileIn);
                       JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(input);
                       BufferedImage imageSrc = decoder.decodeAsBufferedImage();
                       int width = imageSrc.getWidth();
                       int height = imageSrc.getHeight();
                       BufferedImage src = ImageIO.read(input);
                       int width = src.getWidth(); //????? 
                            int height = src.getHeight(); //????? 
                       Image img = src.getScaledInstance(width, height,
                               Image.SCALE_FAST);
                       BufferedImage bi;
                       int fill_width=0;
                       int fill_height=0;
                       if (rotation_value==1||rotation_value==3){
                            bi = new BufferedImage(height, width,BufferedImage.TYPE_INT_RGB);
                            fill_width=height;
                            fill_height=width;
                       else{
                            bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
                            fill_height=height;
                            fill_width=width;
                            //BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                       input.close();
                       System.out.println(photofile);
                       File fileOut = new File(desfile);
                       //File fileOut = new File("c:/Host1.PNG");
                       OutputStream output = new FileOutputStream(fileOut);
                       JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
                       JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
                       param.setQuality(0.90f, false);
                       encoder.setJPEGEncodeParam(param);
                       Graphics2D biContext =bi.createGraphics();
                      biContext.setColor(Color.white);
                       biContext.fillRect(0,0,fill_width,fill_height);
                       int frame_width,frame_height;
                     if (rotation_value==1||rotation_value==3){
                            frame_width=height;
                            frame_height=width;
                       }else{
                            frame_width=width;
                            frame_height=height;
                       int x=0,y=0;
                       if (rotation_value==2){
                            x=frame_width;
                            y=frame_height;
                       if (rotation_value==0){
                             x=frame_width;
                             y=frame_height;
                       if (rotation_value==1){
                                x=frame_height;
                                 y=frame_height;
                       if (rotation_value==3){
                                    x=frame_width;
                                 y=frame_width;
                       double rotate=0;
                       if (rotation_value==0){
                             rotate=Math.PI *2;
                       if (rotation_value==1){
                            rotate=Math.PI / 2;
                       if (rotation_value==2){
                            rotate=Math.PI;
                       if (rotation_value==3){
                            rotate=Math.PI*1.5;
                       int x=0,y=0;
                       if (rotation_value==2){
                            x=width;
                            y=height;
                       if (rotation_value==1){
                                x=height;
                                 y=height;
                       if (rotation_value==3){
                                    x=width;
                                 y=width;
                       double rotate=0;
                       if (rotation_value==1){
                            rotate=Math.PI / 2;
                       if (rotation_value==2){
                            rotate=Math.PI;
                       if (rotation_value==3){
                            rotate=Math.PI*1.5;
                       System.out.println(Integer.toString(x)+"|x|"+Integer.toString(y)+"|y|"+Double.toString(rotate));
                       biContext.rotate(rotate, x / 2, y / 2);
                       biContext.drawImage(src, 0, 0, null);
                       biContext.dispose();
                       System.out.println("123123123123");
                       try{
                               ImageIO.write(bi, filetype, output);
                               //ImageIO.write(bi, filetype, "c:/Host.PNG");
                               output.close();
                          }catch (IOException e) {
                              System.err.println(e);
                      // encoder.encode(bi);
                       //output.close();
                } catch (Exception e) {
                         e.printStackTrace();
          }

    Using this BufferedImage.TYPE_INT_RGB for the type will eliminate any transparency in
    your image. Try BufferedImage.TYPE_INT_ARGB.
    Image file: Bird.gif
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Rotate implements ChangeListener
        BufferedImage image;
        JLabel label;
        JSlider slider;
        public Rotate(BufferedImage orig)
            // make transparent background
            Color toErase = new Color(248, 248, 248, 255);
            image = eraseColor(convertImage(orig), toErase);
        public void stateChanged(ChangeEvent e)
            int value = slider.getValue();
            double theta = Math.toRadians(value);
            BufferedImage rotated = getImage(theta);
            label.setIcon(new ImageIcon(rotated));
        private BufferedImage getImage(double theta)
            double cos = Math.cos(theta);
            double sin = Math.sin(theta);
            int w = image.getWidth();
            int h = image.getHeight();
            int width  = (int)(Math.abs(w * cos) + Math.abs(h * sin));
            int height = (int)(Math.abs(w * sin) + Math.abs(h * cos));
            BufferedImage bi = new BufferedImage(width, height, image.getType());
            Graphics2D g2 = bi.createGraphics();
            g2.setPaint(new Color(0,0,0,0));
            g2.fillRect(0,0,width,height);
            AffineTransform at = AffineTransform.getRotateInstance(theta, width/2, height/2);
            double x = (width - w)/2;
            double y = (height - h)/2;
            at.translate(x, y);
            g2.drawRenderedImage(image, at);
            g2.dispose();
            return bi;
        private BufferedImage convertImage(BufferedImage in)
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            BufferedImage out = gc.createCompatibleImage(in.getWidth(), in.getHeight(),
                                                         Transparency.TRANSLUCENT);
            Graphics2D g2 = out.createGraphics();
            g2.drawImage(in, 0, 0, null);
            g2.dispose();
            return out;
        private BufferedImage eraseColor(BufferedImage source, Color color)
            int w = source.getWidth();
            int h = source.getHeight();
            int type = BufferedImage.TYPE_INT_ARGB;
            BufferedImage out = new BufferedImage(w, h, type);
            Graphics2D g2 = out.createGraphics();
            g2.setPaint(new Color(0,0,0,0));
            g2.fillRect(0,0,w,h);
            int target = color.getRGB();
            for(int j = 0; j < w*h; j++)
                int x = j % w;
                int y = j / w;
                if(source.getRGB(x, y) == target)
                    source.setRGB(x, y, 0);
            g2.drawImage(source, 0, 0, null);
            g2.dispose();
            return out;
        private JLabel getLabel()
            label = new JLabel(new ImageIcon(image));
            return label;
        private JSlider getSlider()
            slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
            slider.addChangeListener(this);
            return slider;
        public static void main(String[] args) throws IOException
            String path = "images/Bird.gif";
            ClassLoader cl = Rotate.class.getClassLoader();
            InputStream is = cl.getResourceAsStream(path);
            Rotate rotate = new Rotate(ImageIO.read(is));
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().setBackground(Color.pink);
            f.getContentPane().add(rotate.getLabel());
            f.getContentPane().add(rotate.getSlider(), "South");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Which is better for drawing JPGs on JLabel: ImageIcon or directly?

    I'm currently using this everywhere.
    BufferedImage bi;
    Jlabel jLabel;
    ImageIcon img = new ImageIcon( bi );
    jLabel.setIcon(imgIcon);but now I've discovered I can write images directly to the component from paintComponent( Graphics g )
    (from a subclass of JLabel)
    public void paintComponent( Graphics g ) {
      super.paintComponent( g );
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );Is this more efficient or better form? Should I update my code everywhere?
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this:
    public void mouseEntered(MouseEvent e) {
      Graphics g = this.getGraphics();
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );
    }what's wrong?

    Is this more efficient or better form?
    No.
    Should I update my code everywhere?
    It depends on what you want to do. If you want to show an image then ImageIcon is an easy way. Override paintComponent when you want to do something other than simply display the image, eg, write text on top of the image or alter the image with things like rotation and scaling.
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this
    Don't put painting code inside event code. Painting/drawing code belongs in an appropriate painting method. Use member variables in the enclosing class for state, manipulate these from your event code and set up your painting method to be able to accurately render this state at any time.
    stephensk8s is correct about the mouseEntered method. It works for components. So using a simple JLabel with ImageIcon is a carefree way to achieve rollover affects.
    Creating this kind of thing for custom graphics and images takes a little more effort. It all depends on what you are trying to do.
    Is there a good place to go to get a better understanding of this, or just ask on this forum?
    Ask when you need help.
    Resources that may be helpful to get started:
    Lesson: Writing Event Listeners
    Lesson: Performing Custom Painting
    How to Use Icons
    Lesson: Working with Images
    Core Java Technologies Tech Tips.

  • Problem in rotating and moving image at the same time

    the problem is that im making a car game(2D) in which u have upper view of car.
    i have make the car rotate bt problem is that i canot move it forward or backward correctly
    .wen i move it forward or backward i goes wrong...
    nd another problem is that i cannot both rotate and move the car at same time
    example if i press both up nd right arrow keys i doesnt move nd rotate..
    nd also plz tell me the accelerate nd reverse method so i can speedup my car like other car games
    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.applet.*;
    import java.net.URL;
    public class RaceGame extends JComponent
    static int x=560;
    static int y=410;
    static int currentAngle=0;
    static double hspeed,vspeed;
    static int carspeed=1;
    Image car;
    //int angle=car.getAngle();
    Image getImage(String filename)
    URL url = getClass().getResource(filename);
    ImageIcon icon = new ImageIcon(url);
    return icon.getImage();
    //Rectangle2D.Float rect=new Rectangle2D.Float(x,y,30,30);
    //Rectangle rect=new Rectangle(x,y,30,30);
    public RaceGame()
    car=getImage("car1.jpeg");
    public void CreateBase()
    JFrame frame=new JFrame("Dare2Race");
    frame.setBounds(70,30,650,500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c=frame.getContentPane();
    c.add(new RaceGame());
    frame.addKeyListener(new adapter());
    c.setBackground(Color.BLACK);
    //JLabel finish=new JLabel("FINISH");
    //c.add(finish);
    public void rotate()
    currentAngle+=1;
    if(currentAngle>=360)
    currentAngle=0;
    repaint();
    public void paint(Graphics g)
    super.paint(g);
    Graphics2D g2d=(Graphics2D)g;
    AffineTransform origXform=g2d.getTransform();
    AffineTransform newXform=(AffineTransform)(origXform.clone());
    newXform.rotate(Math.toRadians(currentAngle),x,y);
    g2d.setTransform(newXform);
    g2d.drawImage(car,x,y,this);
    g2d.setTransform(origXform);
    g.setColor(Color.WHITE);
    g.drawLine(640,380,420,380);
    g.drawLine(640,460,320,460);
    g.drawLine(420,380,420,300);
    g.drawLine(320,460,320,380);
    g.drawLine(420,300,125,300);
    g.drawLine(320,380,230,380);
    g.drawLine(230,380,230,460);
    g.drawLine(230,460,2,460);
    g.drawLine(125,300,125,370);
    g.drawLine(125,370,105,370);
    g.drawLine(2,460,2,180);
    g.drawLine(105,370,105,300);
    g.drawLine(2,180,450,180);
    g.drawLine(105,300,105,250);
    g.drawLine(105,250,550,250);
    g.drawLine(550,250,550,20);
    g.drawLine(550,20,275,20);
    g.drawLine(450,180,450,100);
    g.drawLine(450,100,360,100);
    g.drawLine(360,100,360,160);
    g.drawLine(360,160,10,160);
    g.drawLine(10,160,10,30);
    g.drawLine(275,20,275,90);
    g.drawLine(275,90,110,90);
    g.drawLine(110,90,110,30);
    repaint();
    class adapter extends KeyAdapter
    public void keyPressed(KeyEvent e)
    switch(e.getKeyCode())
    case KeyEvent.VK_LEFT:
    currentAngle--;
    repaint();
    break;
    case KeyEvent.VK_RIGHT:
    currentAngle++;
    repaint();
    break;
    case KeyEvent.VK_UP:
    carspeed++;
    hspeed=((double)carspeed)*Math.cos(currentAngle);
    vspeed=((double)carspeed)*Math.sin(currentAngle);
    x = x - (int) hspeed;
    y = y - (int) vspeed;
    repaint();
    break;
    case KeyEvent.VK_DOWN:
    carspeed--;
    hspeed=((double)carspeed)*Math.cos(currentAngle);
    vspeed=((double)carspeed)*Math.sin(currentAngle);
    x = x + (int)hspeed;
    y = y + (int)vspeed;
    repaint();
    break;
    public static void main(String[]args)
    RaceGame race=new RaceGame();
    race.CreateBase();
    //race.setDoubleBuffered(true);
    }

    the problem is that im making a car game(2D) in which u have upper view of car.
    i have make the car rotate bt problem is that i canot move it forward or backward correctly
    .wen i move it forward or backward i goes wrong...
    nd another problem is that i cannot both rotate and move the car at same time
    example if i press both up nd right arrow keys i doesnt move nd rotate..
    nd also plz tell me the accelerate nd reverse method so i can speedup my car like other car games
    plz help me
    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.applet.*;
    import java.net.URL;
    public class RaceGame extends JComponent
    static int x=560;
    static int  y=410;
    static int currentAngle=0;
    static double hspeed,vspeed;
    static  int carspeed=1;
    Image car;
    //int angle=car.getAngle();
    Image getImage(String filename)
    URL url = getClass().getResource(filename);
    ImageIcon  icon = new ImageIcon(url);   
    return icon.getImage();
    //Rectangle2D.Float rect=new Rectangle2D.Float(x,y,30,30);
    //Rectangle rect=new Rectangle(x,y,30,30);
    public RaceGame()
    car=getImage("car1.jpeg");
    public void CreateBase()
    JFrame frame=new JFrame("Dare2Race");
    frame.setBounds(70,30,650,500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c=frame.getContentPane();
    c.add(new RaceGame());
    frame.addKeyListener(new adapter());
    c.setBackground(Color.BLACK);
    //JLabel finish=new JLabel("FINISH");
    //c.add(finish);
    public void rotate()
    currentAngle+=1;
    if(currentAngle>=360)
    currentAngle=0;
    repaint();
    public void paint(Graphics g)
    super.paint(g);
    Graphics2D g2d=(Graphics2D)g;
    AffineTransform origXform=g2d.getTransform();
    AffineTransform newXform=(AffineTransform)(origXform.clone());
    newXform.rotate(Math.toRadians(currentAngle),x,y);
    g2d.setTransform(newXform);
    g2d.drawImage(car,x,y,this);
    g2d.setTransform(origXform);
    g.setColor(Color.WHITE);
    g.drawLine(640,380,420,380);
    g.drawLine(640,460,320,460);
    g.drawLine(420,380,420,300);
    g.drawLine(320,460,320,380);
    g.drawLine(420,300,125,300);
    g.drawLine(320,380,230,380);
    g.drawLine(230,380,230,460);
    g.drawLine(230,460,2,460);
    g.drawLine(125,300,125,370);
    g.drawLine(125,370,105,370);
    g.drawLine(2,460,2,180);
    g.drawLine(105,370,105,300);
    g.drawLine(2,180,450,180);
    g.drawLine(105,300,105,250);
    g.drawLine(105,250,550,250);
    g.drawLine(550,250,550,20);
    g.drawLine(550,20,275,20);
    g.drawLine(450,180,450,100);
    g.drawLine(450,100,360,100);
    g.drawLine(360,100,360,160);
    g.drawLine(360,160,10,160);
    g.drawLine(10,160,10,30);
    g.drawLine(275,20,275,90);
    g.drawLine(275,90,110,90);
    g.drawLine(110,90,110,30);
    repaint();
    class adapter extends KeyAdapter
    public void keyPressed(KeyEvent e)
      switch(e.getKeyCode())
        case KeyEvent.VK_LEFT:
        currentAngle--;
        repaint();
        break;
        case KeyEvent.VK_RIGHT:
        currentAngle++;
        repaint();
        break;
        case KeyEvent.VK_UP:
        carspeed++;
        hspeed=((double)carspeed)*Math.cos(currentAngle);
        vspeed=((double)carspeed)*Math.sin(currentAngle);
        x = x - (int) hspeed;
        y = y - (int) vspeed;
        repaint();
        break;
        case KeyEvent.VK_DOWN:
        carspeed--;
        hspeed=((double)carspeed)*Math.cos(currentAngle);
        vspeed=((double)carspeed)*Math.sin(currentAngle);
        x = x + (int)hspeed;
        y = y + (int)vspeed;
        repaint();
        break;
    public static void main(String[]args)
    RaceGame race=new RaceGame();
    race.CreateBase();
    //race.setDoubleBuffered(true);
    }and there is no compile time error in this code
    the only error that occurs when u write java RaceGame is because of the car image which compiler doesnt found and throughs exception if u place any image in ur bin folder adn name it car.jpg it wont generate error

  • Rotate Operator leaves black color around destination image

    Hi Everyone,
    I am creating a JPeg image which has two layers. First one is the background image layer. Second one is the photo which i want to put on the center on the back ground image. I am using overlay operator for this purpose.I have already done this thing.. BUT when i try to rotate the photo then a black color appears (in the area where part of un-rotated image was). I want the background image to be there instead of that black colour..
    I have searched a lot but did not find the solution.. Please help.
    Thanks & Best Regards,
    Masood Ahmad

    Hi,
    It works perfect.. i am doing the same thing using rotate operator in JAI... why that is not working... I am pasting both Rotate programs here.. One is in Java2D and 2nd in JAI.. Java2D is working but JAI rotate is leaving black area after rotation.
    Please tell where i am wrong in JAI or is it bug in JAI?
    Program in JAI
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.awt.*;
    import java.awt.color.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.awt.image.renderable.*;
    import java.util.*;
    import javax.media.jai.*;
    import javax.media.jai.operator.*;
    import javax.media.jai.widget.*;
    import com.sun.media.jai.codec.*;
    public class RotateTestJAI extends JPanel
    PlanarImage src1 = null;
    PlanarImage src2 = null;
    ImageDisplay ic1 = null;
    public static void main(String any[]) throws Exception{
    JFrame frame = new JFrame();
    frame.add(new RotateTestJAI(any[0],any[1]));
    frame.setSize(800,600);     
    frame.setVisible(true);     
    public RotateTestJAI(String im1, String im2) throws Exception{
    super(true);
    setLayout(new BorderLayout());
         try
                   //scale first image
                   FileSeekableStream stream = new FileSeekableStream(im1);
                   RenderedOp imscaled = JAI.create("stream",stream);
                   Interpolation interp = Interpolation.getInstance(Interpolation.INTERP_BILINEAR);
                   System.out.println("height : "+imscaled.getHeight()+" Width : "+imscaled.getWidth());
                   ParameterBlock params = new ParameterBlock();
                   params.addSource(imscaled);
                   params.add((float)1388/imscaled.getWidth());
                   params.add((float)1641/imscaled.getHeight());
                   params.add(0.00F);
                   params.add(0.00F);
                   params.add(interp);
                   src1 = JAI.create("scale", params );
                   //scale second image
                   stream = new FileSeekableStream(im2);
                   imscaled = JAI.create("stream",stream);
                   interp = Interpolation.getInstance(Interpolation.INTERP_BILINEAR);
                   params = new ParameterBlock();
                   params.addSource(imscaled);
                   params.add((float)400/imscaled.getWidth());
                   params.add((float)300/imscaled.getHeight());
                   params.add(0.00F);
                   params.add(0.00F);
                   params.add(interp);
                   src2 = JAI.create("scale", params );
                   float x = (float)(src1.getHeight()/2)-src2.getHeight();
                   float y = (float)(src1.getWidth()/2)-src2.getWidth();
                   int value = 10;
                   float angle = (float)(value * (Math.PI/180.0F));
                   //Rotate second image          
                   params = new ParameterBlock();
                   params.addSource(src2); // The source image
                   params.add(x); // The x origin
                   params.add(y); // The y origin
                   params.add(angle); // The rotation angle
                   params.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR)); // The interpolation
                   // Create the rotate operation
                   src2 = JAI.create("Rotate", params, null);
                   //translate 2nd image to bring it in center               
                   params = new ParameterBlock();
                   params.addSource(src2); // The source image
                   params.add((float)Math.max(x, 0)); // The x translation
                   params.add((float)Math.max(y, 0)); // The y translation
                   params.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR)); // The interpolation
                   // Create the translate operation
                   src2 = JAI.create("translate", params, null);
                   //overlay second image on first image
                   params = new ParameterBlock();     
                   params.addSource(src1);
                   params.addSource(src2);     
              RenderedOp tmp = JAI.create("overlay", params);
                   //put the image on display     
                   ic1=new ImageDisplay(tmp);
              this.add(ic1,BorderLayout.CENTER);
         catch ( MalformedURLException e)
              return;
    Program in Java2D:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class RotationTest implements ActionListener
    BufferedImage bg;
    BufferedImage fg;
    JLabel label;
    double theta;
    double thetaInc;
    public RotationTest(BufferedImage bg, BufferedImage fg)
    this.bg = bg;
    this.fg = fg;
    theta = 0.0;
    thetaInc = Math.PI/6;
    public void actionPerformed(ActionEvent e)
    theta += thetaInc;
    label.setIcon(new ImageIcon(getImage()));
    private BufferedImage getImage()
    int w = bg.getWidth();
    int h = bg.getHeight();
    BufferedImage out = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = out.createGraphics();
    g2.drawRenderedImage(bg, null);
    double width = fg.getWidth();
    double height = fg.getHeight();
    double x = (w - width)/2;
    double y = (h - height)/2;
    AffineTransform at = AffineTransform.getTranslateInstance(x, y);
    at.rotate(theta, width/2, height/2);
    g2.drawRenderedImage(fg, at);
    g2.dispose();
    return out;
    private JLabel getLabel()
    ImageIcon icon = new ImageIcon(getImage());
    label = new JLabel(icon);
    label.setHorizontalAlignment(JLabel.CENTER);
    return label;
    private JPanel getUIPanel()
    JButton rotate = new JButton("rotate");
    rotate.addActionListener(this);
    JPanel panel = new JPanel();
    panel.add(rotate);
    return panel;
    public static void main(String[] args) throws IOException
    ClassLoader cl = RotationTest.class.getClassLoader();
    String path = "images/cougar.jpg";
    BufferedImage one = ImageIO.read(cl.getResourceAsStream(path));
    path = "images/Bird.gif";
    BufferedImage two = ImageIO.read(cl.getResourceAsStream(path));
    RotationTest test = new RotationTest(one, two);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(test.getLabel());
    f.getContentPane().add(test.getUIPanel(), "South");
    f.setSize(400,400);
    f.setLocation(200,200);
    f.setVisible(true);
    }

  • Borderlayout east west rotate

    I'm a beginner, and i would like to ask if there is a way to rotate the view of a hand with cards.
    I want a hand on the north, on the south, on the west (i want to show this vertical) and the east (vertical too)
    Who can help me with this?
    this is my code so far.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    * This is the BlackjackGUI window. The user can play a game of blackjack
    * through this window. The BlackjackGUI creates the players and starts the game.
    * @author Tony Sintes
    public class BlackjackGUI extends JFrame {
    public static void main( String [] args ) {
    JFrame frame = new BlackjackGUI();
    frame.getContentPane().setBackground( FOREST_GREEN );
    frame.setSize( 1024, 860 );
    frame.show();
    private BlackjackDealer dealer;
    private GUIPlayer human;
    private JPanel players = new JPanel( new BorderLayout() );
    private static final Color FOREST_GREEN = new Color( 35, 142, 35 );
    public BlackjackGUI() {
    setUp();
    WindowAdapter wa = new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    System.exit( 0 );
    addWindowListener( wa );
    // needs to be protected if subclassed
    private PlayerView getPlayerView( Player p ) {
    PlayerView v = new PlayerView( p );
    v.setBackground( FOREST_GREEN );
    return v;
    // needs to be protected if subclassed
    private void setUp() {
    BlackjackDealer dealer = getDealer();
    PlayerView v1 = getPlayerView( dealer );
    GUIPlayer human = getHuman();
    PlayerView v2 = getPlayerView( human );
    Player safe = getSafePlayer();
    PlayerView v3 = getPlayerView(safe);
    Player onehit = getOneHitPlayer();
    PlayerView v4 = getPlayerView(onehit);
    PlayerView [] views = { v1, v2, v3, v4 };
    // addPlayers( views );
    dealer.addPlayer( human);
    dealer.addPlayer(safe);
    dealer.addPlayer(onehit);
    addOptionView( human, dealer );
    getContentPane().add(players);
    players.setBackground( FOREST_GREEN );
    players.add(v1, BorderLayout.NORTH);
    players.add(v2, BorderLayout.EAST);
    players.add(v3, BorderLayout.WEST);
    players.add(v4, BorderLayout.SOUTH);
    // needs to be protected if subclassed
    // private void addPlayers( PlayerView [] p ) {
    // players.setBackground( FOREST_GREEN );
    // for( int i = 0; i < p.length; i ++ ) {
    // players.add( p );
    // getContentPane().add( players, BorderLayout.CENTER );
    private void addOptionView( GUIPlayer human, BlackjackDealer dealer ) {
    OptionView ov = new OptionView( human, dealer );
    ov.setBackground( FOREST_GREEN );
    getContentPane().add( ov, BorderLayout.SOUTH );
    private BlackjackDealer getDealer() {
    if( dealer == null ) {
    Hand dealer_hand = new Hand();
    Deckpile cards = getCards();
    dealer = new BlackjackDealer( "Dealer", dealer_hand, cards );
    return dealer;
    private GUIPlayer getHuman() {
    if( human == null ) {
    Hand human_hand = new Hand();
    Bank bank = new Bank( 1000 );
    human = new GUIPlayer( "Human", human_hand, bank );
    return human;
    private Player getSafePlayer() {
    // lever zoveel als nodig
    Hand safe_hand = new Hand();
    Bank safe_bank = new Bank (1000);
    return new SafePlayer("Safe", safe_hand, safe_bank);
    private Player getOneHitPlayer() {
    // lever zoveel als nodig
    Hand onehit_hand = new Hand();
    Bank onehit_bank = new Bank (1000);
    return new OneHitPlayer("OneHit", onehit_hand, onehit_bank);
    private Deckpile getCards() {
    Deckpile cards = new Deckpile();
    for( int i = 0; i < 4; i ++ ) {
    cards.shuffle();
    Deck deck = new VDeck();
    deck.addToStack( cards );
    cards.shuffle();
    return cards;
    }

    This requires the font playing cards which you can find on this page.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class HandRotation
        Cards cards;
        JPanel table;
        JPanel hand1, hand2, hand3, hand4;
        JPanel[] hands;
        JLabel[] ids;
        int handIndex;   // index into hands for hand in north section
        public HandRotation()
            cards = new Cards();
            table = new JPanel();
            initTable();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(getUIPanel(), "North");
            f.getContentPane().add(new JScrollPane(table));
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private JPanel getUIPanel()
            final JButton
                deal   = new JButton("deal"),
                rotate = new JButton("rotate"),
                clear  = new JButton("clear"),
                show   = new JButton("show deck");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JButton button = (JButton)e.getSource();
                    if(button == deal)
                        dealHand();
                    if(button == rotate)
                        rotateView();
                    if(button == clear)
                        clear();
                    if(button == show)
                        cards.showDeck();
            deal.addActionListener(l);
            rotate.addActionListener(l);
            clear.addActionListener(l);
            show.addActionListener(l);
            JPanel panel = new JPanel();
            panel.add(deal);
            panel.add(rotate);
            panel.add(clear);
            panel.add(show);
            return panel;
        private void initTable()
            // clockwise starting at north position
            hand1 = new JPanel(new GridLayout(1,0));
            hand2 = new JPanel(new GridLayout(0,1));
            hand3 = new JPanel(new GridLayout(1,0));
            hand4 = new JPanel(new GridLayout(0,1));
            hands = new JPanel[] { hand1, hand2, hand3, hand4 };
            handIndex = 0;
            JPanel idPanel = initIDPanel();
            table.setLayout(new BorderLayout());
            // add clockwise
            table.add(hand1, "North");
            table.add(hand2, "East");
            table.add(hand3, "South");
            table.add(hand4, "West");
            table.add(idPanel);
            cards.shuffle();
        private JPanel initIDPanel()
            JPanel panel = new JPanel(new BorderLayout());
            String[] quadrants = { "North", "East", "South", "West" };
            String[] idNames = { "hand 1", "hand 2", "hand 3", "hand 4" };
            ids = new JLabel[idNames.length];
            for(int j = 0; j < ids.length; j++)
                ids[j] = new JLabel(idNames[j]);
                ids[j].setHorizontalAlignment(JLabel.CENTER);
                panel.add(ids[j], quadrants[j]);
                hands[j].setName(idNames[j]);
            return panel;
        private void dealHand()
            for(int j = 0; j < hands.length; j++)
                hands[j].add(cards.deal());
            table.revalidate();
            table.repaint();
        private void rotateView()
            // shift each hand anti-clockwise one position
            //     hands all appear to rotate anti-clockwise with each call
            // remove each hand from table and change the rows/cols in its
            //     GridLayout from (0,1) to (1,0), or from (1,0) to (0,1)
            //     before adding the hand to the next anti-clockwise position
            for(int j = 0; j < hands.length; j++)
                table.remove(hands[j]);
                GridLayout layout = (GridLayout)hands[j].getLayout();
                int rows = layout.getRows();
                int cols = layout.getColumns();
                // to avoid IllegalArgumentException:
                //         "rows and cols cannot both be zero"
                if(rows == 0)
                    layout.setRows(cols);
                    layout.setColumns(rows);
                else
                    layout.setColumns(rows);
                    layout.setRows(cols);
            // next (clockwise) hand goes into north section
            handIndex++;
            if(handIndex > hands.length - 1)
                handIndex = 0;
            // add hands back into new positions in table
            //    and update the ids with names of new hands
            String[] directions = { "North", "East", "South", "West" };
            for(int j = 0; j < hands.length; j++)
                int index = (handIndex + j) % hands.length;
                table.add(hands[index], directions[j]);
                ids[j].setText(hands[index].getName());
            table.revalidate();
            table.repaint();
        private void clear()
            for(int j = 0; j < hands.length; j++)
                hands[j].removeAll();
            table.repaint();
            cards.shuffle();
        public static void main(String[] args)
            new HandRotation();
    class Cards
        List deck;
        Font font;
        int lastCardIndex;
        public Cards()
            font = new Font("playing cards", Font.PLAIN, 72);
            createDeck();
            lastCardIndex = 0;
        public Card deal()
            if(lastCardIndex > deck.size() - 1)
                shuffle();
            return (Card)deck.get(lastCardIndex++);
        public void shuffle()
            Collections.shuffle(deck);
            lastCardIndex = 0;
        public void showDeck()
            JPanel panel = new JPanel(new GridLayout(0,13));
            Font f = font.deriveFont(36f);
            Card card;
            JLabel label;
            for(int j = 0; j < deck.size(); j++)
                card = (Card)deck.get(j);
                label = new JLabel(card.getText());
                label.setForeground(card.getForeground());
                label.setFont(f);
                panel.add(label);
            JOptionPane.showMessageDialog(null, panel);
        private void createDeck()
            deck = new ArrayList();
            String s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            String next;
            Color
                color = Color.black,
                red = new Color(204,0,0);
            for(int j = 0; j < 52; j++)
                if(j == s.length() - 1)
                    next = s.substring(j);
                else
                    next = s.substring(j, j + 1);
                if(j == 26)
                    color = red;
                deck.add(new Card(next, color));
        public class Card extends JLabel
            public Card(String s, Color color)
                super(s);
                setFont(font);
                setForeground(color);
                setHorizontalAlignment(JLabel.CENTER);
    }

  • Flashing & Rotate image problem!

    1) how can i make an image flashing ( appear & disappear ) in JLabel?.
    2)how can i make it rotate?.
    plz need help!

    both questions easily answered by searching the forums - numerous examples

  • Rotate a bob image

    hi,
    I need to rotate a blob image and place it on a JLabel. can anyone help me to do that. it is really urgent
    thx in advance

    Don't multi post! One thread is enough! Locked. I'll delete this later.

  • Load a redrawn image into a JLabel and save it into a BufferedImage?

    Hello, I'm doing a small application to rotate an image, it works, but I'd like to show it into a JLabel that I added, and also store the converted image into a BufferedImage to save it into a database, this is what I have so far:
    public void getImage() {
    try{
    db_connection connect = new db_connection();
    Connection conn = connect.getConnection();
    Statement stmt = conn.createStatement();
    sql = "SELECT image " +
    "FROM image_upload " +
    "WHERE image_id = 1";
    rset = stmt.executeQuery(sql);
    if(rset.next()){
    img1 = rset.getBinaryStream(1);
    buffImage = ImageIO.read(img1);
    rset.close();
    } catch(Exception e){
    System.out.println(e);
    public void paint(Graphics g){
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;
    ImageIcon imgIcon = new ImageIcon(buffImage);
    AffineTransform tx = AffineTransform.getRotateInstance(rotacion, imgIcon.getIconWidth()/2, imgIcon.getIconHeight()/2);
    g2.drawImage(imgIcon.getImage(), tx, this);
    jLabel1.setIcon(imgIcon);
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    setRotacion(getRotacion() + 1.5707963249999999);
    repaint();
    I get the image from a db, then using the paint() method I rotate the image, it works, but the new image is outside of the JLabel and I don't know how to assign the new one into the JLabel (like overwritting the original) and also how to store the new image into a BufferedImage to upload it into the database converted, thanks in advanced, any help would be appreciated, thanks!!
    Edited by: saman0suke on 25-dic-2011 14:07
    Edited by: saman0suke on 25-dic-2011 15:08

    I was able already to fill the JLabel with the modified content, just by creating a new BufferedImage, then create this one into a Graphics2D object and the drawing the image into it, last part, inserting the modified image into the database, so far, so good, thanks!
    EDIT: Ok, basic functionality is ok, I can rotate the image using AffineTransform class, and I can save it to the database and being displayed into a JLabel, now, there's a problem, the image for this example is 200 width and 184 height, but when I rotate it the width can be 184 and the height 200 depending on the position, but the BufferedImage that I create always read from original saved image:
    bimage = new BufferedImage(buffImage.getWidth(), buffImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Is there a way that I can tell BufferedImage new width and height after rotate it? :( as far as I understand this cannot be done because before the image bein rotated the bufferedImage is already created and, even being able to do it how can I get width and height from rotated image? thanks!
    Edited by: saman0suke on 25-dic-2011 19:40

  • Exception during rotation transform

    I am trying to rotate a Buffered Image using the following method:
    BufferedImage image; //has been loaded correctly
    BufferedImage image90; //destination for transform
    AffineTransformOp rotate90=new AffineTransformOp (AffineTransform.getRotateInstance Math.toRadians (90)),AffineTransformOp.TYPE_BILINEAR);
    image90=rotate90.filter (image,null);
    This results in the exception:
    Exception in thread "main" java.awt.image.RasterFormatException: Transformed wid
    th (0) is less than or equal to 0.
    at java.awt.image.AffineTransformOp.createCompatibleDestImage(Unknown So
    urce)
    at java.awt.image.AffineTransformOp.filter(Unknown Source)
    at com.DMTool.ImageCoordinateTester.<init>(ImageCoordinateTester.java:63
    at com.DMTool.ImageCoordinateTester.main(ImageCoordinateTester.java:118)
    Why is this happening?

    Using AffineTransformOp to rotate an image is an uphill struggle. I suggest doing it "manually":
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class RotateImage {
        public static void main(String[] args) throws IOException {
            URL url = new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg");
            BufferedImage original = ImageIO.read(url);
            GraphicsConfiguration gc = getDefaultConfiguration();
            BufferedImage rotated1 = tilt(original, -Math.PI/2, gc);
            BufferedImage rotated2 = tilt(original, +Math.PI/2, gc);
            BufferedImage rotated3 = tilt(original, Math.PI, gc);
            display(original, rotated1, rotated2, rotated3);
        public static BufferedImage tilt(BufferedImage image, double angle, GraphicsConfiguration gc) {
            double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
            int w = image.getWidth(), h = image.getHeight();
            int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin);
            int transparency = image.getColorModel().getTransparency();
            BufferedImage result = gc.createCompatibleImage(neww, newh, transparency);
            Graphics2D g = result.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g.translate((neww-w)/2, (newh-h)/2);
            g.rotate(angle, w/2, h/2);
            g.drawRenderedImage(image, null);
            return result;
        public static GraphicsConfiguration getDefaultConfiguration() {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            return gd.getDefaultConfiguration();
        public static void display(BufferedImage im1, BufferedImage im2, BufferedImage im3, BufferedImage im4) {
            JPanel cp = new JPanel(new GridLayout(2,2));
            addImage(cp, im1, "original");
            addImage(cp, im2, "rotate -PI/2");
            addImage(cp, im3, "rotate +PI/2");
            addImage(cp, im4, "rotate PI");
            JFrame f = new JFrame("RotateImage");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(cp);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        static void addImage(Container cp, BufferedImage im, String title) {
            JLabel lbl = new JLabel(new ImageIcon(im));
            lbl.setBorder(BorderFactory.createTitledBorder(title));
            cp.add(lbl);

  • Hit Detection on Scaled or Rotated Lines?

    Hi,
    I'm writing a java program in which I paint a number of line segments.
    I've added the ability to scale or rotate the scene. Now, if the scene
    is neither scaled or rotated, then detecting when the mouse pointer
    is over a particular line is not especially difficult. I just iterate through
    all the line objects and compare their coordinates with the mouse's
    coordinates.
    But I can't figure how to detect when the mouse is over a line when the
    scene has been scaled and/or rotated. I guess this problem requires
    a bit of maths - something I'm bit rusty at. Can someone help me?
    Thanks.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Hashtable;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TransformSelection extends JPanel implements ChangeListener {
        JSlider rotateSlider;
        JSlider scaleSlider;
        Polygon polygon;
        Line2D[] lines;
        int selectedIndex = -1;
        Color[] colors = {
            Color.red, Color.green.darker(), Color.blue, Color.magenta, Color.orange
        AffineTransform at = new AffineTransform();
        double theta = 0;
        double scale = 1.0;
        public void stateChanged(ChangeEvent e) {
            JSlider slider = (JSlider)e.getSource();
            int value = slider.getValue();
            double cx = getWidth()/2.0;
            double cy = getHeight()/2.0;
            if(slider == rotateSlider) {
                theta = Math.toRadians(value);
            if(slider == scaleSlider) {
                scale = value/100.0;
            at.setToTranslation((1.0-scale)*cx, (1.0-scale)*cy);
            at.scale(scale, scale);
            at.rotate(theta, cx, cy);
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
                                RenderingHints.VALUE_STROKE_PURE);
            if(lines == null) {
                initLines();
            AffineTransform orig = g2.getTransform();
            g2.setTransform(at);
            //g2.setPaint(Color.blue);
            //g2.draw(polygon);
            g2.setPaint(Color.red);
            for(int j = 0; j < lines.length; j++) {
                g2.setPaint(colors[j]);
                g2.draw(lines[j]);
                if(j == selectedIndex) {
                    g2.setPaint(Color.red);
                    double cx = (lines[j].getX1() + lines[j].getX2())/2;
                    double cy = (lines[j].getY1() + lines[j].getY2())/2;
                    g2.draw(new Ellipse2D.Double(cx-4, cy-4, 8, 8));
            g2.setTransform(orig);
        public void setSelectedIndex(int index) {
            selectedIndex = index;
            repaint();
        private void initLines() {
            int w = getWidth();
            int h = getHeight();
            double cx = w/2.0;
            double cy = h/2.0;
            int R = Math.min(w,h)/6;
            int sides = 5;
            int[][]xy = generateShapeArrays(w/2, h/2, R, sides);
            polygon = new Polygon(xy[0], xy[1], 5);
            lines = new Line2D[sides];
            double theta = -Math.PI/2;
            for(int j = 0; j < sides; j++) {
                double x1 = cx + (R/2)*Math.cos(theta);
                double y1 = cy + (R/2)*Math.sin(theta);
                double x2 = polygon.xpoints[j];
                double y2 = polygon.ypoints[j];
                lines[j] = new Line2D.Double(x1, y1, x2, y2);
                theta += 2*Math.PI/sides;
        private JPanel getControls() {
            rotateSlider = new JSlider(JSlider.HORIZONTAL, -180, 180, 0);
            rotateSlider.setMajorTickSpacing(30);
            rotateSlider.setMinorTickSpacing(10);
            rotateSlider.setPaintTicks(true);
            rotateSlider.setPaintLabels(true);
            rotateSlider.addChangeListener(this);
            scaleSlider = new JSlider(JSlider.HORIZONTAL, 50, 200, 100);
            scaleSlider.setMajorTickSpacing(50);
            scaleSlider.setMinorTickSpacing(10);
            scaleSlider.setPaintTicks(true);
            scaleSlider.setLabelTable(getLabelTable(50, 200, 50));
            scaleSlider.setPaintLabels(true);
            scaleSlider.addChangeListener(this);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = gbc.HORIZONTAL;
            gbc.gridwidth = gbc.REMAINDER;
            panel.add(rotateSlider, gbc);
            panel.add(scaleSlider, gbc);
            return panel;
        private Hashtable getLabelTable(int min, int max, int inc) {
            Hashtable<Integer,JComponent> table = new Hashtable<Integer,JComponent>();
            for(int j = min; j <= max; j += inc) {
                String s = String.format("%d%%", j);
                table.put(new Integer(j), new JLabel(s));
            return table;
        private int[][] generateShapeArrays(int cx, int cy, int R, int sides) {
            int radInc = 0;
            if(sides % 2 == 0) {
                radInc = 1;
            int[] x = new int[sides];
            int[] y = new int[sides];
            for(int i = 0; i < sides; i++) {
                x[i] = cx + (int)(R * Math.sin(radInc*Math.PI/sides));
                y[i] = cy - (int)(R * Math.cos(radInc*Math.PI/sides));
                radInc += 2;
            // keep base of triangle level
            if(sides == 3) {
                y[2] = y[1];
            return new int[][] { x, y };
        public static void main(String[] args) {
            TransformSelection test = new TransformSelection();
            test.addMouseListener(new LineSelector(test));
            JFrame f = new JFrame("click on lines");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.getContentPane().add(test.getControls(), "Last");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class LineSelector extends MouseAdapter {
        TransformSelection transformSelection;
        Rectangle net;
        int lastSelectedIndex;
        final int SIDE = 4;
        public LineSelector(TransformSelection ts) {
            transformSelection = ts;
            net = new Rectangle(SIDE, SIDE);
        public void mousePressed(MouseEvent e) {
            net.setLocation(e.getX() - SIDE/2, e.getY() - SIDE/2);
            AffineTransform at = transformSelection.at;
            Line2D[] lines = transformSelection.lines;
            for(int j = 0; j < lines.length; j++) {
                Shape xs = at.createTransformedShape(lines[j]);
                if(xs.intersects(net)) {
                    transformSelection.setSelectedIndex(j);
                    lastSelectedIndex = j;
                    break;
    }

  • JLabel (or any text) - vertical orientation.

    hey all,
    I'm replacing a spreadsheet driven system with a swing app - one of the requirements is that it look similar to the spreadsheet. The spreadsheet of course has nice column headings - labels turned clockwise 90 degrees.
    Is there a way to do this? I'm guessing if there is I'm just looking in the wrong spot - a pointer would be appreciated.
    cheers
    dim

    q&d
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.*;
    public class Turn90LabelTest extends JPanel {
          public class Turn90Label extends JLabel {
                public Turn90Label( String s )
                   super( s );
                   setPreferredSize( new Dimension( 30, 90 ) );
                   setMinimumSize( new Dimension( 30, 90 ) );
                public void paintComponent(Graphics g) {
                   Graphics2D g2d = (Graphics2D)g;
                   g2d.translate(10.0, 50.0);
                   g2d.rotate( 300 );
                   g2d.drawString('Java', 0, 0);
          public Turn90LabelTest()
             add( new Turn90Label( "Java" ) );
          public static void main(String[] args) {
             JFrame f = new JFrame();
             JPanel p = (JPanel) f.getContentPane();
             p.add( new Turn90LabelTest() );
             f.pack();
             f.show();
    }

Maybe you are looking for

  • Trying to understand the basic concept of object oriented programming.

    I am trying to understand the basic concept of object oriented programming. Object - a region of storage that define is defined by both state/behavior. ( An object is the actual thing that behavior affects.) State - Represented by a set of variables

  • FCP sequence settings for Sony HandyCam video

    I'm working with video shot on a Sony Handycam HDR-CX550.  I had no problem importing it into iMovie and then to FCP, however I can't figure out what sequence settings I should use.  It appears to be 16x9, but shows up as 4x3 in my FCP bin.  Also, th

  • We are SEVEN!

      (Illustration credit: supermod Erik - who also came up with most of the Communities' graphics and our 5th year anniversary logo.) Slightly more than three years ago I was approached about a role within the Lenovo Forums Community, and being a non-t

  • Need help with swapping footage and solid 3d layer

    Here's my situation: I have a .mov file which i want to place inside that red solid layer [1]. I hold option and drag on top of the solid layer and it is swapped in the timeline. However, it gets placed at the very end of the comp as a single-frame s

  • I need help with setting 2 decimal places

    I am using netbeans to create a GUI. My math works I need help formatting the result to 2 decimal places. Thanks for any help. This is part of my code.. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {