2011-11-20 82 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中顯示圖像。