简体   繁体   English

我可以更改在代码中放在JLabel上的ImageIcon的位置吗?

[英]Can I change the location of the ImageIcon that I put on a JLabel in my code?

I tried using, "label.setBounds(100,100,250,250)" and "label.setLocation(100,100)" but the image does not move from the top and center of the JLabel. 我尝试使用“ label.setBounds(100,100,250,250)”和“ label.setLocation(100,100)”,但是图像不会从JLabel的顶部和中央移动。

import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Machine extends JPanel
{
    public Machine()
    {
         ImageIcon imageIcon = new ImageIcon("res/robot.png");
         JLabel label = new JLabel(imageIcon);
         add(label);
    }

     public static void main(String[] args)
     {
         JFrame frame = new JFrame();
         frame.add(new Machine());
         frame.setVisible(true);
         frame.setSize(new Dimension(1080, 720));
     }
}

What are you trying to do? 你想做什么?

The default layout of a JPanel is a FlowLayout with center alignment and the label is displayed at its preferred size. JPanel的默认布局是具有中心对齐的FlowLayout ,并且标签以其首选大小显示。 So the label is displayed in the center. 因此标签显示在中间。

You have a couple of options: 您有两种选择:

  1. Change the alignment of the FlowLayout to be either LEFT or RIGHT 将FlowLayout的对齐方式更改为LEFT或RIGHT

  2. Don't add the label to the panel. 不要在面板上添加标签。 Just add it directly to the frame which uses a BorderLayout . 只需将其直接添加到使用BorderLayout的框架中即可。

Then you can do something like: 然后,您可以执行以下操作:

 label.setHorizontalAlignment(JLabel.LEFT);
 label.setVerticalAlignment(JLabel.CENTER);

Edit: 编辑:

was just trying to get the image to be in the middle of the frame 只是试图使图像位于帧的中间

Then post your actual requirement when you ask a question. 然后在提出问题时发布您的实际要求。 We don't know what "can I change the location" means to you. 我们不知道“我可以更改位置”对您意味着什么。

So you would either use the BorderLayout and adjust the horizontal/vertical alignment as already demonstrated. 因此,您已经可以使用BorderLayout并调整水平/垂直对齐方式了。

Or, you could set the layout manager of the frame to be a GridBagLayout and then add the label directly to the frame and use: 或者,您可以将框架的布局管理器设置为GridBagLayout ,然后将标签直接添加到框架并使用:

frame.add(label, new GridBagConstraints());

Now the label will move dynamically as the frame is resized. 现在,标签将随着调整框架的大小而动态移动。

If you want to place an image in a certain location, perhaps best is to draw it directly in your JPanel in a paintComponent method override, using one of Graphics drawImage(...) methods, one that allows placement of the image. 如果要将图像放置在某个位置,则最好的方法是使用Graphics drawImage(...)方法之一在paintComponent方法重写中直接在JPanel中绘制它,该方法允许放置图像。

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class Machine extends JPanel {
    private static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia/commons/"
            + "thumb/f/f2/Abraham_Lincoln_O-55%2C_1861-crop.jpg/"
            + "250px-Abraham_Lincoln_O-55%2C_1861-crop.jpg";
    private BufferedImage img;
    private int x;
    private int y;

    public Machine() {
        setPreferredSize(new Dimension(1080, 720));
        x = 100; // or wherever you want to draw the image
        y = 100; 

        try {
            URL imgUrl = new URL(IMG_PATH);
            img = ImageIO.read(imgUrl);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            g.drawImage(img, x, y, this);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Machine());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Version 2: MouseListener / MouseMotionListener so that the image can be moved 版本2:MouseListener / MouseMotionListener,以便可以移动图像

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class Machine extends JPanel {
    private static final String IMG_PATH = "https://upload.wikimedia.org/"
            + "wikipedia/commons/thumb/f/f2/"
            + "Abraham_Lincoln_O-55%2C_1861-crop.jpg/" 
            + "250px-Abraham_Lincoln_O-55%2C_1861-crop.jpg";
    private BufferedImage img;
    private int x;
    private int y;

    public Machine() {
        setPreferredSize(new Dimension(1080, 720));
        x = 100; // or wherever you want to draw the image
        y = 100;

        MyMouse mouse = new MyMouse();
        addMouseListener(mouse);
        addMouseMotionListener(mouse);

        try {
            URL imgUrl = new URL(IMG_PATH);
            img = ImageIO.read(imgUrl);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            g.drawImage(img, x, y, this);
        }
    }

    private class MyMouse extends MouseAdapter {
        private Point offset;

        @Override
        public void mousePressed(MouseEvent e) {
            // check if left mouse button pushed
            if (e.getButton() != MouseEvent.BUTTON1) {
                return;
            }

            // get bounds of the image and see if mouse press within bounds
            Rectangle r = new Rectangle(x, y, img.getWidth(), img.getHeight());
            if (r.contains(e.getPoint())) {
                // set the offset of the mouse from the left upper 
                // edge of the image
                offset = new Point(e.getX() - x, e.getY() - y);
            }
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if (offset != null) {
                moveImg(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (offset != null) {
                moveImg(e);
            }
            offset = null;
        }

        private void moveImg(MouseEvent e) {
            x = e.getX() - offset.x;
            y = e.getY() - offset.y;
            repaint();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Machine());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM