I'm not sure why the fr.repaint(); method isn't working here. If I use the set visible false, then set it true after making changes it makes the screen go black which isn't what I'm trying to do.
Any help?
This code is for a school project, so if it's possible please provide somewhat detailed explanation to understand.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
class Main {
static int startingposx;
static int startingposy;
static int endingposx;
static int endingposy;
public static void main(String[] args) {
JFrame fr = new JFrame();
fr.setBounds(10,10,512,512);
fr.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
fr.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
startingposx = e.getX();
startingposy = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
endingposx = e.getX();
endingposy = e.getY();
//fr.setVisible(false);// i tried to use this to refresh it but it makes the frame black for a second
JPanel x = new JPanel(){
#Override
public void paint(Graphics g){
g.setColor(Color.RED);
g.fillRect(startingposx-(32-15),startingposy-32,30,30);
g.setColor(Color.BLUE);
g.fillRect(endingposx-(32-15),endingposy-32,30,30);
}
};
fr.add(x);
fr.repaint();// why does this not work??
//fr.setVisible(true);
System.out.print("\033[H\033[2J");
System.out.println("starting pos: " + startingposx+ ","+ startingposy+"\n" + "ending pos: " + endingposx+ "," + endingposy);
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Frame made shorter in height purely to save space in answer
See further comments in the code. Note that the blue rectangle completely covers the red rectangle.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestCustomPaint {
// Don't use static! Make them instances of the x class and give it a constructor
static int startingposx;
static int startingposy;
static int endingposx;
static int endingposy;
public static void main(String[] args) {
JFrame fr = new JFrame();
// this is the wrong size if the content should be square
fr.setBounds(10,10,512,512);
// unused MouseMotionListener removed
fr.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) { }
#Override
public void mousePressed(MouseEvent e) {
startingposx = e.getX();
startingposy = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
endingposx = e.getX();
endingposy = e.getY();
fr.repaint();
System.out.print("\033[H\033[2J");
System.out.println("starting pos: " + startingposx+ ","+ startingposy+"\n" +
"ending pos: " + endingposx+ "," + endingposy);
}
#Override
public void mouseEntered(MouseEvent e) { }
#Override
public void mouseExited(MouseEvent e) { }
});
// This is when the panel should be created and added.
JPanel x = new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(startingposx-(32-15),startingposy-32,30,30);
g.setColor(Color.BLUE);
g.fillRect(endingposx-(32-15),endingposy-32,30,30);
}
};
fr.add(x);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Related
i am writing a program that when the mouse is clicked, a circle will be drawn. The below code i've wrote so far.
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.event.*;
import java.awt.geom.*;
public class test extends JFrame implements ActionListener, MouseListener {
Shape circle = new Ellipse2D.Float(10, 10, 10, 10);
public test () {
setSize(250,150);
addMouseListener(this);
}
public static void main(String[] args) {
//TODO code application logic here
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
test frame = new test();
frame.setVisible(true);
}
});
}
public void actionPerformed(ActionEvent ae) {
}
public void drawCircle(int x, int y) {
Graphics g = this.getGraphics();
g.drawOval(x, y, x, y);
g.setColor(Color.BLACK);
g.fillOval(x, y, 2, 2);
}
public void mouseClicked(MouseEvent e) {
drawCircle(e.getX(), e.getY());
repaint();
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
}
The code is a 400X400 jframe, when clicked open display a circle at a half seconds, The problem is that, when i release the mouse, the circle disappear. why?
Change your mouseClick(...) to:
int x, y;
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
Override paint(...):
#Override
public void paint(Graphics g) {
drawCircle(x, y);
}
When you call repaint(), the component gets painted again from scratch. You're circle is wiped away. You will want to override paintComponent(Graphics) which is called every time the component is painted.
I am trying to implement a click and drag method, for which I need mousePressed and mouseReleased events. I will also be using mouseClicked events, so I implemented MouseMotionListener and MouseListener.
However, when I go to write mousePressed, mouseReleased, mouseEntered, mouseExited methods I get the following error:
method mousePressed(MouseEvent) is already defined in class BoingPanel
Here is the entire class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JPanel;
public class BoingPanel extends JPanel implements MouseMotionListener, MouseListener {
private int width;
private int height;
private int updateRate=40;
ArrayList<Ball> balls;
ArrayList<Line> lines;
private Container box;
private boolean drag = false;
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public BoingPanel()
{
balls = new ArrayList<Ball>();
balls.add(new Ball(100,0)); // adds test ball
balls.get(0).setXVelocity(5);
balls.add(new Ball(100,0));
balls.add(new Ball(400,50));
lines = new ArrayList<Line>();
lines.add(new Line(0, height, width, height));
gameStart();
}
public BoingPanel(int x, int y)
{
width=x;
height=y;
balls = new ArrayList<Ball>();
balls.add(new Ball(100,0)); // adds test ball
balls.get(0).setXVelocity(5);
balls.add(new Ball(100,0));
balls.add(new Ball(400,50));
lines = new ArrayList<Line>();
box = new Container(width, height);
gameStart();
}
#Override
public void mouseDragged(MouseEvent me) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public void gameStart() {
// Run the game logic in its own thread.
Thread gameThread = new Thread() {
public void run() {
while (true) {
// Execute one time-step for the game
update();
// Refresh the display
repaint();
// Delay and give other thread a chance
try {
Thread.sleep(1000 /updateRate);
} catch (InterruptedException ex) {}
}
}
};
gameThread.start(); // Invoke GaemThread.run()
}
private void update()
{
for(Ball a:balls) //calls balls updated position
{
a.update(box);
}
}
public void paintComponent(Graphics g)
{
box.paint(g);
for(Ball a:balls) //calls balls updated position
{
a.paint(g);
}
for(Line b:lines) //draws lines
{
b.paint(g);
}
}
public void actionPerformed(ActionEvent e)
{
update(); //changes ball position
repaint(); //refreshes image
}
}
What is causing this error? Thanks!
I would suggest this, just below your variable declarations and before you constructor, isn't helping...
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
You've basically implemented these methods twice. Just before and after the constructor.
Simply remove on of these groups of declarations...
please remove public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { } and then try
I made a Frame which repaints itself when I click on it(also the new geometric figure is painted) but when I click rapidly It does not responds so fast, it needs like half a sec beetween clicks. What have I done wrong?
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Okienko extends Frame implements MouseListener{
public static final int SIZE = 500;
public static int mX = 0,mY = 0;
public ArrayList<Wyrysowywalny> l; //COLLECTION OF OBJECT TO DRAW
Okienko(){
l = new ArrayList<Wyrysowywalny>();
createGUI();
}
public void createGUI(){
setSize(SIZE, SIZE);
setVisible(true);
setAlwaysOnTop(true);
setTitle("Zadanie 1");
addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowClosed(WindowEvent arg0) {}
#Override
public void windowClosing(WindowEvent arg0) {
JOptionPane.showConfirmDialog(null, "dziekujemy za skorzystanie z programu","",JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
#Override
public void windowActivated(WindowEvent arg0) {
repaint();
}
});
addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {/// IMPORTANT!
System.out.println(e.getX() + " " + e.getY());
mX = e.getX();
mY = e.getY();
int r;
r = (int) (Math.random() * 6);
switch(r){
case 0: l.add(new Trojkat(mX,mY,lXY(),lXY(),lXY(),lXY()));break; // OBJECTS TO DRAW
case 1: l.add(new Prostokat(mX,mY,lR(),lR()));break;
case 2: l.add(new Kwadrat(mX,mY,lR()));break;
case 3: l.add(new Kolo(mX,mY,lR()));break;
case 4: l.add(new Elipsa(mX,mY,lR(),lR())); break;
case 5: l.add(new TrojkatRownoboczny(mX,mY,lR())); break;
}
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {}
#Override
public void mouseExited(MouseEvent arg0) {}
#Override
public void mousePressed(MouseEvent arg0) {}
#Override
public void mouseReleased(MouseEvent arg0) {}
public static int lXY(){
return (int) (Math.random()*SIZE * 4d/5 + 1d/40*SIZE);
}
public static int lR(){
return (int) (Math.random()*200 - 1d/40*SIZE);
}
public void paint(Graphics g){
super.paint(g);
for(Wyrysowywalny w : l)
w.draw(g);//DRAW OBJECT
}
public static void main(String[] args) {
new Okienko();
}
}
Absent a complete example, I can only make several observations:
Instead of mouseClicked(), which fires when the mouse is released in the same component, you may want to respond to mousePressed().
Also consider MouseAdapter over implements MouseListener.
As mentioned here, "Swing programs should override paintComponent() instead of overriding paint()."
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
A more elaborate example with no perceptible latency is cited here.
Let me start off by saying I know I've violated some basic Java principles in this messy code, but I'm desperately trying to finish a program by Tuesday for a social science experiment, and I don't know Java, so I'm basically just fumbling through it for now.
With that disclaimer out of the way, I have a separate program working where a circle is moving around the screen and the user must click on it. It works fine when its in its own separate class file, but when I add the code to my main program, it's no longer working. I don't even really understand why repaint() calls my paint() function — as far as I'm concerned, it's magic, but I've noticed that repaint() calls paint() in my test program, but not in the more complicated actual program, and I assume that's why the circle is no longer painting on my program.
Entire code is below:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;
public class Reflexology1 extends JFrame{
private static final long serialVersionUID = -1295261024563143679L;
private Ellipse2D ball = new Ellipse2D.Double(0, 0, 25, 25);
private Timer moveBallTimer;
int _ballXpos, _ballYpos;
JButton button1, button2;
JButton movingButton;
JTextArea textArea1;
int buttonAClicked, buttonDClicked;
private long _openTime = 0;
private long _closeTime = 0;
JPanel thePanel = new JPanel();
JPanel thePlacebo = new JPanel();
final JFrame frame = new JFrame("Reflexology");
final JFrame frame2 = new JFrame("The Test");
JLabel label1 = new JLabel("Press X and then click the moving dot as fast as you can.");
public static void main(String[] args){
new Reflexology1();
}
public Reflexology1(){
frame.setSize(600, 475);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Reflexology 1.0");
frame.setResizable(false);
frame2.setSize(600, 475);
frame2.setLocationRelativeTo(null);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setTitle("Reflexology 1.0");
frame2.setResizable(false);
button1 = new JButton("Accept");
button2 = new JButton("Decline");
//movingButton = new JButton("Click Me");
ListenForAcceptButton lForAButton = new ListenForAcceptButton();
ListenForDeclineButton lForDButton = new ListenForDeclineButton();
button1.addActionListener(lForAButton);
button2.addActionListener(lForDButton);
//movingButton.addActionListener(lForMButton);
JTextArea textArea1 = new JTextArea(24, 50);
textArea1.setText("Tracking Events\n");
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
textArea1.setSize(15, 50);
textArea1.setEditable(false);
FileReader reader = null;
try {
reader = new FileReader("EULA.txt");
textArea1.read(reader, "EULA.txt");
} catch (IOException exception) {
System.err.println("Problem loading file");
exception.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
AdjustmentListener listener = new MyAdjustmentListener();
thePanel.add(scrollBar1);
thePanel.add(button1);
thePanel.add(button2);
frame.add(thePanel);
ListenForMouse lForMouse = new ListenForMouse();
thePlacebo.addMouseListener(lForMouse);
thePlacebo.add(label1);
frame2.add(thePlacebo);
ListenForWindow lForWindow = new ListenForWindow();
frame.addWindowListener(lForWindow);
frame2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
if(e.getKeyChar() == 'X' || e.getKeyChar() == 'x') {moveBallTimer.start();}
}
});
frame.setVisible(true);
moveBallTimer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveBall();
System.out.println("Timer started!");
repaint();
}
});
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(frame2.isVisible()){ moveBallTimer.start(); }
}
});
}
private class ListenForAcceptButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
Calendar ClCDateTime = Calendar.getInstance();
System.out.println(ClCDateTime.getTimeInMillis() - _openTime);
_closeTime = ClCDateTime.getTimeInMillis() - _openTime;
//frame.getContentPane().remove(thePanel);
//thePlacebo.addKeyListener(lForKeys);
//frame.getContentPane().add(thePlacebo);
//frame.repaint();
//moveBallTimer.start();
frame.setVisible(false);
frame2.setVisible(true);
frame2.revalidate();
frame2.repaint();
}
}
}
private class ListenForDeclineButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button2){
JOptionPane.showMessageDialog(Reflexology1.this, "You've declined the license agreement. DO NOT RESTART the program. Please go inform a researcher that you have declined the agreement.", "WARNING", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}
private class ListenForWindow implements WindowListener{
public void windowActivated(WindowEvent e) {
//textArea1.append("Window is active");
}
// if this.dispose() is called, this is called:
public void windowClosed(WindowEvent arg0) {
}
// When a window is closed from a menu, this is called:
public void windowClosing(WindowEvent arg0) {
}
// Called when the window is no longer the active window:
public void windowDeactivated(WindowEvent arg0) {
//textArea1.append("Window is NOT active");
}
// Window gone from minimized to normal state
public void windowDeiconified(WindowEvent arg0) {
//textArea1.append("Window is in normal state");
}
// Window has been minimized
public void windowIconified(WindowEvent arg0) {
//textArea1.append("Window is minimized");
}
// Called when the Window is originally created
public void windowOpened(WindowEvent arg0) {
//textArea1.append("Let there be Window!");
Calendar OlCDateTime = Calendar.getInstance();
_openTime = OlCDateTime.getTimeInMillis();
//System.out.println(_openTime);
}
}
private class MyAdjustmentListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent arg0) {
AdjustmentEvent scrollBar1;
//System.out.println(scrollBar1.getValue()));
}
}
public void paint(Graphics g) {
//super.paint(g);
frame2.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
System.out.println("Calling fill()");
}
protected void moveBall() {
//System.out.println("I'm in the moveBall() function!");
int width = getWidth();
int height = getHeight();
int min, max, randomX, randomY;
min =200;
max = -200;
randomX = min + (int)(Math.random() * ((max - min)+1));
randomY = min + (int)(Math.random() * ((max - min)+1));
//System.out.println(randomX + ", " + randomY);
Rectangle ballBounds = ball.getBounds();
//System.out.println(ballBounds.x + ", " + ballBounds.y);
if (ballBounds.x + randomX < 0) {
randomX = 200;
} else if (ballBounds.x + ballBounds.width + randomX > width) {
randomX = -200;
}
if (ballBounds.y + randomY < 0) {
randomY = 200;
} else if (ballBounds.y + ballBounds.height + randomY > height) {
randomY = -200;
}
ballBounds.x += randomX;
ballBounds.y += randomY;
_ballXpos = ballBounds.x;
_ballYpos = ballBounds.y;
ball.setFrame(ballBounds);
}
public void start() {
moveBallTimer.start();
}
public void stop() {
moveBallTimer.stop();
}
private class ListenForMouse implements MouseListener{
// Called when the mouse is clicked
public void mouseClicked(MouseEvent e) {
//System.out.println("Mouse Panel pos: " + e.getX() + " " + e.getY() + "\n");
if (e.getX() >=_ballXpos && e.getX() <= _ballXpos + 25 && e.getY() <=_ballYpos && e.getY() >= _ballYpos - 25 ) {
System.out.println("TRUE");
}
System.out.println("{e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos + " | " + "{e.getY(): " + e.getY() + " / " + "_ballYpos: " + _ballYpos);
}
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
}
}
// System.out.println("e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos);
// Mouse over
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
// Mouse left the mouseover area:
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
}
}
Could anyone tell me what I need to do to get repaint() to call the paint() method in the above program? I'm assuming the multiple frames is causing the problem, but that's just a guess. Thanks.
You should not paint directly on JFrame. JPanel or extension of JComponent should be used. For painting override paintComponent() rather than paint(). Don't forget to call super.paintComponent(g);.
Also, keep in mind that repaint() only schedules component update, it does not trigger immediate paint().
For more details see Performing Custom Painting and Painting in AWT and Swing.
For example you can apply the following changes. TestPanel will paint the ball.
class TestPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
}
}
Then, update thePlacebo panel:
JPanel thePlacebo = new TestPanel();
Add repaint in moveBall():
thePlacebo.repaint();
Here is an example based on original code:
package so;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.Random;
import javax.swing.*;
public class TestBall {
private static void createAndShowUI() {
final TestPanel panel = new TestPanel();
panel.validate();
JFrame frame = new JFrame("TestBall");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 300));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ActionListener timerAction = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.moveBall();
}
};
Timer timer = new Timer(1000, timerAction);
timer.setRepeats(true);
timer.start();
}
static class TestPanel extends JPanel {
public static int BALL_SIZE = 25;
private Ellipse2D ball = new Ellipse2D.Double(0, 0, BALL_SIZE,
BALL_SIZE);
Random rand = new Random();
public TestPanel() {
this.addMouseListener(new MouseAdapter() {
// Called when the mouse is clicked
public void mouseClicked(MouseEvent e) {
if (ball.contains(e.getPoint())) {
System.out.println("hit the ball");
}
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
}
public void moveBall() {
Rectangle ballBounds = ball.getBounds();
ball.setFrame(ballBounds);
ballBounds.x = rand.nextInt(getWidth() - BALL_SIZE + 1) + 1;
ballBounds.y = rand.nextInt(getHeight() - BALL_SIZE + 1) + 1;
ball.setFrame(ballBounds);
repaint();
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Can't seem to figure out how to only show one circle. Was trying to //g.clearRect(0, 0, 400, 400); but that clears the background too. Was also trying to just fill the background with yellow again but couldn't get that working either. Any suggestions?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JMouseFrame extends JFrame
implements MouseListener {
Container con = null;
int x, y;
int size;
public JMouseFrame() {
setTitle("JMouseFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
con = this.getContentPane();
addMouseListener(this);
}
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseClicked(MouseEvent e) {
int whichButton = e.getButton();
if (whichButton == MouseEvent.BUTTON1) {
size = 15;
} else if (whichButton == MouseEvent.BUTTON3) {
size = 4;
}
repaint();
}
public void mouseEntered(MouseEvent e) {
con.setBackground(Color.yellow);
}
public void mouseExited(MouseEvent e) {
con.setBackground(Color.black);
}
public void paint(Graphics g) {
//g.clearRect(0, 0, 400, 400);
g.drawOval(x - size, y - size, size * 3, size * 3);
}
public static void main(String[] args) {
JMouseFrame mFrame = new JMouseFrame();
mFrame.setSize(400, 400);
mFrame.setVisible(true);
}
public void mouseReleased(MouseEvent e) {
}
}
It looks like you're mixing AWT and Swing painting. Instead, override paintComponent(), as suggested in the example below. See Painting in AWT and Swing for details.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/questions/3898775 */
public class MousePanel extends JPanel {
private static final int SIZE = 20;
Point p = new Point(Short.MAX_VALUE, Short.MAX_VALUE);
public MousePanel() {
this.setPreferredSize(new Dimension(400, 400));
this.setBackground(Color.yellow);
this.addMouseListener(new MouseHandler());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawOval(p.x - SIZE, p.y - SIZE, SIZE * 2, SIZE * 2);
}
private final class MouseHandler extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
p = e.getPoint();
repaint();
}
}
private void display() {
JFrame f = new JFrame("MousePanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MousePanel().display();
}
});
}
}
Addendum:
I can't figure out how to make the code you posted work with what I have...
You can restore your mouse methods to the MouseHandler almost verbatim. The only difference is the need to qualify this, e.g.
#Override
public void mouseClicked(MouseEvent e) {
int whichButton = e.getButton();
if (whichButton == MouseEvent.BUTTON1) {
MousePanel.this.size = 15;
} else if (whichButton == MouseEvent.BUTTON3) {
MousePanel.this.size = 4;
}
repaint();
}
#Override
public void mouseEntered(MouseEvent e) {
MousePanel.this.setBackground(Color.yellow);
}
#Override
public void mouseExited(MouseEvent e) {
MousePanel.this.setBackground(Color.black);
}