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);
}
}
如何在框架上保存此文本,并在需要时清除所有框架。 例:
答案 0 :(得分:1)
你使用鼠标坐标吗?您可以使用鼠标监听器并使用鼠标单击方法(鼠标单击后,它将使您的字符串生成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();
}