2011-11-20 78 views
1

基本上我加载了一个图像,当我点击图像的一部分时,出现了一个矩形(没有填充)。如果我再次点击图像的另一部分,该矩形将再次显示。随着每次点击,应该出现相同的矩形。如何在图像中制作矩形移动?

到目前为止,我有这个代码,现在我不知道如何让图像出现。我的文件目录中的图像。我已经让代码从我的文件目录中获取图像。

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.event.MouseEvent; 
import java.awt.event.MouseListener; 

import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 

public class MP2 extends JPanel implements MouseListener{ 

    JFrame frame; 
    JPanel panel; 

    int x = 0; 
    int y = 0; 
    String input; 

    public MP2(){ 

    } 

    public static void main(String[] args){ 
     JFrame frame = new JFrame(); 
     MP2 panel = new MP2(); 
     panel.addMouseListener(panel); 
     frame.add(panel); 
     frame.setSize(200,200); 
     frame.setVisible(true); 

    } 

    public void mouseClicked(MouseEvent event) { 
     // TODO Auto-generated method stub 

     this.x = event.getX(); 
     this.y = event.getY(); 
     this.repaint(); 
     input = JOptionPane.showInputDialog("Something pops out"); 
     System.out.println(input); 

    } 

    public void mouseEntered(MouseEvent arg0) { 
     // TODO Auto-generated method stub 
    } 

    public void mouseExited(MouseEvent arg0) { 
     // TODO Auto-generated method stub 

    } 

    public void mousePressed(MouseEvent arg0) { 
     // TODO Auto-generated method stub 

    } 

    public void mouseReleased(MouseEvent arg0) { 
     // TODO Auto-generated method stub 

    } 

    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 

     // this.setBackground(Color.white); *Sets the bg color of the panel 

     g.setColor(new Color(255,0,0)); 
     g.drawRect(x, y, 100, 100); 
    } 
} 
+0

你的目标不是很清楚。 – mre

+0

我点击图像的一部分,出现一个矩形。而已。 – alicedimarco

+0

听起来像你需要在初始化加载图像,然后重写绘画代码,并在那里,blit当前标记为可见的图像矩形。 – Nerdtron

回答

1

this.x和this.y指向您的JPanel的x和y,而不是您要绘制的矩形。您需要创建两个附加字段rectX和rectY。这些设置在mouseClicked中并由paintComponent()使用。

编辑

对不起,我的坏。我现在感到困惑。你确实声明了一个x和y。这些仍然应该重命名,因为它们可能会与Component中定义的x和y混淆,但它们不是问题。当我运行你的代码并单击时,出现红色矩形(连同一个对话框)。所以我不知道是什么问题?

+0

我应该把它们放在哪里? – alicedimarco

+0

问题是,我必须将矩形放在图像上:)) – alicedimarco

+0

我没有在文件的任何位置看到单词图像。我想在paintComponent的某处你需要调用g.drawImage()。 – user949300

2

您可能想要看看如何绘制The Glass Pane上的矩形,如GlassPaneDemo所示。例如,在paintComponent()中,将g.fillOval()替换为g.drawRect()

我不知道如何让图像出现。

example显示如何在JLabel中显示图像。