Hello everyone!
I've been messing around withJava swing for a while now. I'm trying a draw a text in the mouse position everytime a mousebutton is pressed,
but the problem is that everytime you release the mousebutton the string stays on the screen.
package windowtraining; import javax.swing.SwingUtilities; import javax.swing.JPanel; import javax.swing.JFrame; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.Color; public class Windowtraining{ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ public void run(){ createAndShowGUI(); } }); } public static void createAndShowGUI(){ JFrame f = new JFrame("JFrame test!"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new myPanel()); f.pack(); f.setVisible(true); } } class myPanel extends JPanel{ private int squarex; private int squarey; private int squarew = 32; private int squareh = 32; private int switchmouse = 0; private int smilex; private int smiley; public myPanel(){ addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ moveSquare(e.getX(),e.getY()); } }); addMouseMotionListener(new MouseAdapter(){ public void mouseDragged(MouseEvent e){ switchmouse = 1; smilex = e.getX(); smiley = e.getY(); } }); addMouseMotionListener(new MouseAdapter(){ public void mouseReleased(MouseEvent e){ switchmouse = 0; } }); addMouseMotionListener(new MouseAdapter(){ public void mouseDragged(MouseEvent e){ moveSquare(e.getX(),e.getY()); } }); } private void moveSquare(int x, int y){ int Offset = 1; if (squarex != x || squarey != y) { repaint(squarex,squarey,squarew,squareh); squarex = x - 16; squarey = y - 16; repaint(squarex,squarey,squarew,squareh); } } /*private void drawSmile(int x, int y){ if (smilex != x || smiley != y){ update(smilex, smiley ); } }*/ public Dimension getPreferredSize(){ return new Dimension(640,480); } public void paintComponent(Graphics g){ super.paintComponent(g); { super.paintComponent(g); g.setColor(Color.RED); g.fillRect(squarex, squarey, squarew, squareh); //if (dragSwitch == 1) g.setColor(Color.WHITE); g.fillRect(0,0,640,480); g.setColor(Color.BLUE); if (switchmouse == 1) {g.drawString(":D",smilex,smiley);} } } }
What should I do to draw a string in the mouse position when the player presses a
mouse button but which disappears when you release it?