2014-02-18 27 views
1
public class Drawing extends JPanel { 

int Mouse_x = 0, Mouse_y = 0; 

@Override 
protected void paintComponent(Graphics g) { 
    // TODO Auto-generated method stub 
    super.paintComponent(g); 
    Graphics2D g2 = (Graphics2D) g; 
    this.setOpaque(true); 
    this.setBackground(Color.WHITE); 
    g2.drawString(Mouse_x + "," + Mouse_y, Mouse_x, Mouse_y); 
} 
} 

如何在框架上保存此文本並在需要時清除所有框架。 例如: enter image description here如何保持重繪後的圖形g中繪製的文本()

+0

目前還不清楚你問什麼。請更具體地說明目前發生的事情與您希望發生的事情。 – ApproachingDarknessFish

+0

ValekHalfHeart,添加截圖 – user2650128

回答

1

您是否在使用鼠標作爲座標?你可以使用鼠標監聽和使用方法的mouseClicked(後鼠標點擊它將使X,Y與您的字符串座標。)

public void createDot(int x, int y){ 
    g.drawString(Mouse_x + "," + Mouse_y, x, y); 
} 

您必須添加addMouseListener(this);並實現它的方法。我只寫了mouseClicked方法

public void mouseClicked(MouseEvent e) { 
    int x = e.getX(); 
    int y = e.getY(); 

    createDot(x,y); 

} 

protected void paintComponent(Graphics g) { 
    // TODO Auto-generated method stub 
    super.paintComponent(g); 
    Graphics2D g2 = (Graphics2D) g; 

} 

並在另一個方法中創建GUI:

public static void createGUI(){ 
    JFrame frame = new JFrame("My Frame"); 
    JComponent component = new Drawing(); 
    component.setOpaque(true); 
    frame.add(component); 
    frame.setSize(600,400); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 

} 

然後在main方法運行在:

public static void main(String [] args){ 
      createGUI(); 
     } 
+0

我添加了MouseAdapter,謝謝我解決了我的問題 – user2650128

+0

歡迎:) – DRastislav