Ola, pessoal. Gostaria de movimentar um jlabel com uma imagem nele, sendo que este está em um jFrame que possui uma imagem de fundo (setada com Graphics). A janela tá abrindo e a imagem de fundo tá aparecendo sem problemas. O movimento de arrasto do mouse tambem está bacana. O jLabel com a imagem é que nao aparece. Meu código tah todo ai abaixo. Vlw!
public class AdicionarImagem extends JFrame{
JLabel labelImagem;
JPanel panelImagem;
JPanel panelGeral;
int X = 50, Y = 50;
static ImageIcon fundo;
public AdicionarImagem(){
super("Adicionar Imagem");
criaComponentesJanela();
Dimension tela = Toolkit.getDefaultToolkit().getScreenSize();
setSize(tela.width-310, tela.height-350);
this.setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(fundo.getImage(), 0, 0, this.getWidth(), this.getHeight(), null);
g2d.dispose();
}
public void moveLabel() {
labelImagem.setLocation(X, Y);
labelImagem.repaint();
}
public void criaComponentesJanela (){
final Container parent=this;
MouseMotionListener myCommonListener=new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
X = e.getX();
Y = e.getY();
System.out.println("X: " +e.getX() + " Y: " + e.getY());
moveLabel();
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
};
try {
BufferedImage buf = ImageIO.read(new File("C:/cursor.png"));
ImageIcon im = new ImageIcon(buf);
labelImagem = new JLabel(im);
labelImagem.setLocation(X, Y);
panelImagem = new JPanel();
panelImagem.setLayout( new BoxLayout( panelImagem, BoxLayout.Y_AXIS));
panelImagem.add( new JScrollPane(labelImagem));
panelGeral = new JPanel();
panelGeral.setLayout( new BoxLayout( panelGeral, BoxLayout.X_AXIS));
panelGeral.add(panelImagem);
panelGeral.add( new JSeparator(SwingConstants.VERTICAL ));
labelImagem.addMouseMotionListener(myCommonListener);
parent.add(panelGeral);
}
catch (IOException ex) {
Logger.getLogger(AdicionarImagem.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args){
try {
BufferedImage buf = ImageIO.read(new File("c:/Ad.jpg"));
fundo = new ImageIcon(buf);
}
catch (IOException ex) {
Logger.getLogger(AdicionarTemplate.class.getName()).log(Level.SEVERE, null, ex);
}
new AdicionarTemplate();
}
}