0
 private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {                                    
// TODO add your handling code here:
        int x, y;
        x = jLabel1.getX();
        y = jLabel1.getY();
        System.out.println(jLabel1.getLocation());//mostramos la posicion de la imagen

        switch (evt.getExtendedKeyCode()) {// captura las teclas
            case KeyEvent.VK_UP:
                jLabel1.setLocation(x, y - 10);//arriba
                //Girar Hacia Arriba Imagen
                break; 
            case KeyEvent.VK_DOWN:
                jLabel1.setLocation(x, y + 6);//abajo
                //Girar Hacia abajo Imagen
                break;
            case KeyEvent.VK_LEFT:
                jLabel1.setLocation(x - 10, y);// derecha
                //Girar Hacia derecha Imagen
                break;
            case KeyEvent.VK_RIGHT:
                jLabel1.setLocation(x + 10, y); //izquierda
                //Girar Hacia izquierda Imagen
                break; // hace que la imagen se mueva con las teclas.
        }

        jLabel1.repaint();

    }               

Como puedo hacer rotar una imagen que esta dentro de un jLabel dependiendo de la tecla que pulse

5
  • Mira este artículo, creo que te podría servir y es bastante sencillo.
    – Benito-B
    el 30 ago. 2020 a las 11:18
  • lo voy a mirrar el 30 ago. 2020 a las 11:19
  • hay que añadir algun import? porque no me va el 30 ago. 2020 a las 11:22
  • Nop, abajo donde pone Get the code te da el código fuente de la clase
    – Benito-B
    el 30 ago. 2020 a las 11:24
  • lo e estado mirando y comprobando pero no me sirvió se puede hacer alguna otra manera? el 30 ago. 2020 a las 11:31

1 respuesta 1

2

Aquí tienes el ejemplo funcionando:

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

public class RotateIcons extends JFrame{

    public static void main(String[] args) {
        RotateIcons w = new RotateIcons();
        w.setVisible(true);
    }

    private JPanel basePanel;
    private JLabel label1;
    private JLabel label2;
    private JLabel label3;

    public RotateIcons(){
        setSize(600, 300);
        setTitle("Rotando iconos");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        basePanel = new JPanel();
        basePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        add(basePanel);

        ImageIcon imageIcon = new ImageIcon(getClass().getResource("android.jpg"));
        //Icono normal
        label1 = new JLabel(imageIcon);
        //Icono rotado 90 grados (down = rota hacia la derecha, up = rota hacia la izquierda)
        label2 = new JLabel(new RotatedIcon(imageIcon, RotatedIcon.Rotate.DOWN));
        //Icono rotado 45 grados
        label3 = new JLabel(new RotatedIcon(imageIcon, 45));
        basePanel.add(label1);
        basePanel.add(label2);
        basePanel.add(label3);
        pack();
    }

}

Clase RotatedIcon:

import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import javax.swing.Icon;

/**
 *  The RotatedIcon allows you to change the orientation of an Icon by
 *  rotating the Icon before it is painted. This class supports the following
 *  orientations:
 *
 * <ul>
 * <li>DOWN - rotated 90 degrees
 * <li>UP (default) - rotated -90 degrees
 * <li>UPSIDE_DOWN - rotated 180 degrees
 * <li>ABOUT_CENTER - the icon is rotated by the specified degrees about its center.
 * </ul>
 */
public class RotatedIcon implements Icon
{
    public enum Rotate
    {
        DOWN,
        UP,
        UPSIDE_DOWN,
        ABOUT_CENTER;
    }

    private Icon icon;

    private Rotate rotate;

    private double degrees;
    private boolean circularIcon;

    /**
     *  Convenience constructor to create a RotatedIcon that is rotated DOWN.
     *
     *  @param icon  the Icon to rotate
     */
    public RotatedIcon(Icon icon)
    {
        this(icon, Rotate.UP);
    }

    /**
     *  Create a RotatedIcon
     *
     *  @param icon the Icon to rotate
     *  @param rotate  the direction of rotation
     */
    public RotatedIcon(Icon icon, Rotate rotate)
    {
        this.icon = icon;
        this.rotate = rotate;
    }

    /**
     *  Create a RotatedIcon. The icon will rotate about its center. This
     *  constructor will automatically set the Rotate enum to ABOUT_CENTER.
     *
     *  @param icon the Icon to rotate
     *  @param degrees   the degrees of rotation
     */
    public RotatedIcon(Icon icon, double degrees)
    {
        this(icon, degrees, false);
    }

    /**
     *  Create a RotatedIcon. The icon will rotate about its center. This
     *  constructor will automatically set the Rotate enum to ABOUT_CENTER.
     *
     *  @param icon the Icon to rotate
     *  @param degrees   the degrees of rotation
     *  @param circularIcon treat the icon as circular so its size doesn't change
     */
    public RotatedIcon(Icon icon, double degrees, boolean circularIcon)
    {
        this(icon, Rotate.ABOUT_CENTER);
        setDegrees( degrees );
        setCircularIcon( circularIcon );
    }

    /**
     *  Gets the Icon to be rotated
     *
     *  @return the Icon to be rotated
     */
    public Icon getIcon()
    {
        return icon;
    }

    /**
     *  Gets the Rotate enum which indicates the direction of rotation
     *
     *  @return the Rotate enum
     */
    public Rotate getRotate()
    {
        return rotate;
    }

    /**
     *  Gets the degrees of rotation. Only used for Rotate.ABOUT_CENTER.
     *
     *  @return the degrees of rotation
     */
    public double getDegrees()
    {
        return degrees;
    }

    /**
     *  Set the degrees of rotation. Only used for Rotate.ABOUT_CENTER.
     *  This method only sets the degress of rotation, it will not cause
     *  the Icon to be repainted. You must invoke repaint() on any
     *  component using this icon for it to be repainted.
     *
     *  @param degrees the degrees of rotation
     */
    public void setDegrees(double degrees)
    {
        this.degrees = degrees;
    }

    /**
     *  Is the image circular or rectangular? Only used for Rotate.ABOUT_CENTER.
     *  When true, the icon width/height will not change as the Icon is rotated.
     *
     *  @return true for a circular Icon, false otherwise
     */
    public boolean isCircularIcon()
    {
        return circularIcon;
    }

    /**
     *  Set the Icon as circular or rectangular. Only used for Rotate.ABOUT_CENTER.
     *  When true, the icon width/height will not change as the Icon is rotated.
     *
     *  @param circularIcon true for a circular Icon, false otherwise
     */
    public void setCircularIcon(boolean circularIcon)
    {
        this.circularIcon = circularIcon;
    }

//
//  Implement the Icon Interface
//

    /**
     *  Gets the width of this icon.
     *
     *  @return the width of the icon in pixels.
     */
    @Override
    public int getIconWidth()
    {
        if (rotate == Rotate.ABOUT_CENTER)
        {
            if (circularIcon)
                return icon.getIconWidth();
            else
            {
                double radians = Math.toRadians( degrees );
                double sin = Math.abs( Math.sin( radians ) );
                double cos = Math.abs( Math.cos( radians ) );
                int width = (int)Math.floor(icon.getIconWidth() * cos + icon.getIconHeight() * sin);
                return width;
            }
        }
        else if (rotate == Rotate.UPSIDE_DOWN)
            return icon.getIconWidth();
        else
            return icon.getIconHeight();
    }

    /**
     *  Gets the height of this icon.
     *
     *  @return the height of the icon in pixels.
     */
    @Override
    public int getIconHeight()
    {
        if (rotate == Rotate.ABOUT_CENTER)
        {
            if (circularIcon)
                return icon.getIconHeight();
            else
            {
                double radians = Math.toRadians( degrees );
                double sin = Math.abs( Math.sin( radians ) );
                double cos = Math.abs( Math.cos( radians ) );
                int height = (int)Math.floor(icon.getIconHeight() * cos + icon.getIconWidth() * sin);
                return height;
            }
        }
        else if (rotate == Rotate.UPSIDE_DOWN)
            return icon.getIconHeight();
        else
            return icon.getIconWidth();
    }

    /**
     *  Paint the icons of this compound icon at the specified location
     *
     *  @param c The component on which the icon is painted
     *  @param g the graphics context
     *  @param x the X coordinate of the icon's top-left corner
     *  @param y the Y coordinate of the icon's top-left corner
     */
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y)
    {
        Graphics2D g2 = (Graphics2D)g.create();

        int cWidth = icon.getIconWidth() / 2;
        int cHeight = icon.getIconHeight() / 2;
        int xAdjustment = (icon.getIconWidth() % 2) == 0 ? 0 : -1;
        int yAdjustment = (icon.getIconHeight() % 2) == 0 ? 0 : -1;

        if (rotate == Rotate.DOWN)
        {
            g2.translate(x + cHeight, y + cWidth);
            g2.rotate( Math.toRadians( 90 ) );
            icon.paintIcon(c, g2,  -cWidth, yAdjustment - cHeight);
        }
        else if (rotate == Rotate.UP)
        {
            g2.translate(x + cHeight, y + cWidth);
            g2.rotate( Math.toRadians( -90 ) );
            icon.paintIcon(c, g2,  xAdjustment - cWidth, -cHeight);
        }
        else if (rotate == Rotate.UPSIDE_DOWN)
        {
            g2.translate(x + cWidth, y + cHeight);
            g2.rotate( Math.toRadians( 180 ) );
            icon.paintIcon(c, g2, xAdjustment - cWidth, yAdjustment - cHeight);
        }
        else if (rotate == Rotate.ABOUT_CENTER)
        {
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setClip(x, y, getIconWidth(), getIconHeight());
            g2.translate((getIconWidth() - icon.getIconWidth()) / 2, (getIconHeight() - icon.getIconHeight()) / 2);
            g2.rotate(Math.toRadians(degrees), x + cWidth, y + cHeight);
            icon.paintIcon(c, g2, x, y);
        }

        g2.dispose();
    }
}

Para modificar el icono simplemente usa el método setIcon de JLabel:

jLabel1.setIcon(new RotatedIcon(imageIcon, 45)); //Pone un icono rotado 45 grados

Tan solo necesitas tener una referencia al ImageIcon que usaste para crear los jLabel en principio para poder rotarlo con new RotatedIcon(ImageIcon, angulo)

Resultado:

Diferentes labels girados

11
  • a mi la imagen me funciona pero el problema esta en como hago para colocarlo en la parte de private void jButton1KeyPressed(java.awt.event.KeyEvent evt) porque el coche se mueve pero la imagen no se gira el 30 ago. 2020 a las 12:47
  • Prueba con jLabel1.setIcon() pasándole un nuevo RotatedIcon con la referencia del ImageIcon que usaste para crear el JLabel en un principio y los grados de rotación que quieras
    – Benito-B
    el 30 ago. 2020 a las 13:01
  • vale lo voy a mirrar el 30 ago. 2020 a las 13:03
  • me funciono voy a ajustar los grados´ el 30 ago. 2020 a las 13:35
  • No hay método initComponents(). Ese método lo crea NetBeans cuando añades un nuevo formulario o GUI o cómo les llame. Este código está escrito por mí a mano y si te fijas, no hay método ninguno que se llame así en él.
    – Benito-B
    el 30 ago. 2020 a las 19:45

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.