开发者

how to add images to a panel at any location (x,y)

i want to add images or labels with image in it to a panel at any location which will be decided by the user clicking on the panel(add image where us开发者_开发技巧er clicks in the panel). how to do this.

thanks


try (and tweak) this sscce:

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JLabelOnClick extends JFrame {

    public static void main(String[] args) {
    final JFrame frame = new JLabelOnClick();
    final JPanel panel = new JPanel();
    panel.setLayout(null);
    frame.setContentPane(panel);

    frame.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        // if you want an image instead, use the JLabel(Icon image)
        // constructor
        JLabel label = new JLabel("test");
        label.setBounds(e.getX(), e.getY(), label.getPreferredSize().width, label
            .getPreferredSize().height);
        panel.add(label);
        panel.validate();
        frame.repaint();
        }
    });

    frame.setSize(new Dimension(200, 200));
    frame.setVisible(true);
    }

}


set null as LayoutManager for that panel and then manually set position for each image.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜