Home > Net >  ImageIcon it is not drawn outside the borders of JFrame
ImageIcon it is not drawn outside the borders of JFrame

Time:02-02

I have a picture that is larger than the screen size, and I want to move the mouse over the image. I wrote the following code

public class Rotation extends JComponent{

int xStart=0;
int yStart=0;
public void rotate(){

    JFrame a = new JFrame("example");
    ImageIcon imageIcon=new ImageIcon("src/main/resources/img.png");
    JLabel label=new JLabel(imageIcon);
    a.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            xStart=e.getX()-label.getX();
            yStart=e.getY()-label.getY();
        }
    });
    a.addMouseMotionListener(new MouseAdapter() {
        @Override
        public void mouseDragged(MouseEvent e) {
            label.setLocation(e.getX()-xStart, e.getY()-yStart);
        }
    });

    a.add(label);
    a.setSize(300,300);
    a.setVisible(true);
    a.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}

Here I'm just moving the image. But it turns out that jlabel does not draw my image outside of the JFrame boundaries

before dragged

after dragged

How can I fix it?

CodePudding user response:

Just to get you going...add the JLabel to a JPanel then size the JLabel to the size of the image. Add the JPanel to the JFrame, for example:

// JFrame:
JFrame frame = new JFrame("example");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400,400);
    
// JPanel:
JPanel panel = new JPanel();
            
//JLabel and Image:
ImageIcon imageIcon = new ImageIcon("src/main/resources/img.png");
JLabel label = new JLabel();
    
// Set JLabel size to Image Size:
label.setSize(new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight()));
    
// Ensure Horizonal and Vertical alignments in JLabel:
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
label.setIcon(imageIcon);
    
// Add JLabel to JPanel:
panel.add(label);
    
// Add JPanel to JFrame:
frame.add(panel);
    
// Display JFrame with Image:
java.awt.EventQueue.invokeLater(() -> {
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);  // Center form to screen.
});
    
// Add Mouse Listeners:
frame.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        xStart = e.getX() - label.getX();
        yStart = e.getY() - label.getY();
    }
});
 
frame.addMouseMotionListener(new MouseAdapter() {
    @Override
    public void mouseDragged(MouseEvent e) {
        label.setLocation(e.getX() - xStart, e.getY() - yStart);
    }
});
  • Related