paintComponent () never executes on a JFrame - java

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.*;
import java.util.*;
public class test1 extends JFrame implements MouseListener {
private JPanel JP = new JPanel();
public test1() {
JP.setBorder(BorderFactory.createLineBorder(Color.black));
JP.addMouseListener(this);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.add(JP);
this.pack();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
test1 frame = new test1();
frame.setSize(400,400);
frame.setVisible(true);
}
});
}
public void mouseClicked(MouseEvent e) {
//drawCircle(e.getX(), e.getY());
//repaint();
ballball ball;
ball = new ballball();
//ball.paintComponent(Graphics g);
System.out.println("ballball");
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
//this.mouseX=e.getX();
//this.mouseY=e.getY();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
}
class ballball extends test1 implements Runnable {
private int squareX = 50;
private int squareY = 50;
private int squareW = 100;
private int squareH = 100;
public boolean draw;
private Vector<Object> v = new Vector<Object>();
public ballball() {
/*addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
draw = true;
//Thread thread1 = new Thread(this.moveSquare(50, 50));
repaint();
//moveSquare(e.getX(),e.getY());
}
});*/
/*addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
moveSquare(e.getX(),e.getY());
}
});*/
System.out.println("ball created");
this.repaint();
}
public void run() {
}
private void moveSquare(int x, int y) {
int OFFSET = 1;
if ((squareX!=x) || (squareY!=y)) {
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
squareX=x;
squareY=y;
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
}
}
public void paint(Graphics g) {
g.drawString("abcasdfasffasfas", 10, 10);
}
//#Override
public void paintComponent(Graphics g) {
//if (draw) {
// existing code
System.out.println("paint");
//super.paintComponent(g);
//g.drawString("This is my custom Panel!",10,20);
//g.setColor(Color.RED);
//g.fillRect(squareX,squareY,squareW,squareH);
//g.setColor(Color.BLACK);
//g.drawRect(squareX,squareY,squareW,squareH);
Shape circle = new Ellipse2D.Float(squareX,squareY,100f,100f);
Graphics2D ga = (Graphics2D)g;
ga.draw(circle);
//}
}
}
The aim of the program is to click to create the circle, the ballball class extends the test1, when test1 detect the mouse click, the ballball object created. But the paint/paintComponent method is never be executed. In my program structure, is it possible to paint the circle to the super class JPanel?

JFrame is not a JComponent, it doesn't have a paintComponent method you can override. Instead you could extend a JPanel and add it to the frame.

Related

How to change the color of a panel when I pass over it with another one?

I'm creating a code where I need to change a Panel color with the one I'm still pressed on when I pass over it. For instance if let's say I pressed on a green panel and drag it over another one, this one should get the green color. However it doesn't work everytime, like sometimes it does change the color but sometimes it doesn't.
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.util.Random;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.*;
import javax.swing.event.MouseInputListener;
public class Etabli extends JFrame {
JPanel paneprinci;
CarrePanel selected;
public Etabli() {
this.setVisible(true);
setTitle("Cadre");
setDefaultCloseOperation(EXIT_ON_CLOSE);
paneprinci=new JPanel(null);
setSize(600,600);
selected=new CarrePanel();
for (int i=0;i<10;i++) {
paneprinci.add(new CarrePanel(new Carre()));
}
this.getContentPane().add(paneprinci);
}
public static void main (String[]args) {
javax.swing.SwingUtilities.invokeLater(
new Runnable() {
public void run() {
Etabli e=new Etabli();
}
});
}
public class CarrePanel extends JPanel implements MouseInputListener{
private Carre carre;
private boolean etat;
private int xprev;
private int yprev;
public CarrePanel(Carre c) {
setBounds(new Random().nextInt(500),new Random().nextInt(500), 50, 50);
addMouseListener(this);
addMouseMotionListener(this);
this.setBackground(c.getColor());
this.carre=c;
}
public CarrePanel() {
setBounds(new Random().nextInt(500),new Random().nextInt(500), 50, 50);
addMouseListener(this);
addMouseMotionListener(this);
}
public void setCarre(Carre c) {
carre=c;
}
public Carre getCarre() {
return carre;
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(this.carre.getColor());
}
#Override
public void mouseEntered(MouseEvent e) {
if (selected.getCarre()!=null) {
this.carre.setColor(selected.getCarre().getColor());
this.setBackground(selected.getCarre().getColor());
}
}
#Override
public void mousePressed(MouseEvent e) {
etat=true;
selected.setCarre(this.carre);
xprev=e.getXOnScreen();
yprev=e.getYOnScreen();
}
#Override
public void mouseReleased(MouseEvent e) {
etat=false;
if(selected.getCarre()==this.carre) {
selected.setCarre(null);;
}
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
if(etat) {
int x=this.getX()+e.getXOnScreen()-xprev;
int y=this.getY()+e.getYOnScreen()-yprev;
this.setLocation(x,y);
xprev=e.getXOnScreen();
yprev=e.getYOnScreen();
}
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
}
Here's the code for Carre ( which is square in French )
import java.awt.Color;
import java.util.Arrays;
import java.util.Random;
import java.awt.Color;
public class Carre {
private Color color;
public Carre() {
color=new Color(new Random().nextInt(255),new Random().nextInt(255),new Random().nextInt(255));
}
public Color getColor() {
return color;
}
public void setColor(Color c) {
color=c;
}
}
What I don't understand is why does it works sometimes, I don't know if the problem comes from how I did my drag event or if there's something wrong elsewhere.
Thank you for your awnser.
What I don't understand is why does it works sometimes,
When you drag a square to another square you will notice that sometimes the dragged square is painted:
below the other square
above the other square
When the square is painted above the other square a mouseEntered event is not generated because the default logic will only generate the event for the top component.
When the square is painted below the other square, then your mouseEntered event is generated and your logic works as expected.
The order of painting of a component is determined by its ZOrder. So you can adjust the ZOrder of the dragged component to be the last component painted.
In the mousePressed logic you can add:
JPanel parent = (JPanel)getParent();
parent.setComponentZOrder(this, parent.getComponentCount() - 1);
This will make sure that the dragged component is always painted below the other components.
Also note that your etat variable is not needed. The mouseDragged event is only generated while the mouse is pressed.
I created the following GUI.
I added a java.awt.Rectangle to the Carre class to holds the bounds of each rectangle. The Carre class now holds all of the information to draw a Carre instance.
I created a CarreModel class to hold a java.util.List of Carre instances. I create all of the Carre instances in the constructor of the CarreModel class.
I created one JFrame and one drawing JPanel. I left your JFrame extend, but generally, you should use Swing components. You only extend a Swing component, like JPanel in CarrePanel, when you want to override one of the class methods.
I separated the MouseListener and MouseMotionListener from the CarrePanel JPanel class. I find it helps to keep separate functions in separate methods and classes. It makes it much easier to focus on one part of the application at a time.
The MouseListener mousePressed method has a function at the bottom to move the selected carre to the top of the Z-order. This makes the carre move more visually appealing.
The MouseListener updateCarreColor method checks for carre intersections and changes the color of any carre that intersects the selected carre.
Here's the complete runnable code. I made all the classes inner classes so I can post the code as one block.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.MouseInputListener;
public class Etabli extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Etabli();
}
});
}
private CarreModel model;
private CarrePanel paneprinci;
public Etabli() {
this.model = new CarreModel();
this.setTitle("Cadre");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
paneprinci = new CarrePanel();
this.add(paneprinci, BorderLayout.CENTER);
this.pack();
this.setLocationByPlatform(true);
this.setVisible(true);
}
public class CarrePanel extends JPanel {
private static final long serialVersionUID = 1L;
public CarrePanel() {
this.setPreferredSize(new Dimension(550, 550));
ColorListener listener = new ColorListener();
this.addMouseListener(listener);
this.addMouseMotionListener(listener);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Carre carre : model.getCarres()) {
g2d.setColor(carre.getColor());
Rectangle r = carre.getBounds();
g2d.fillRect(r.x, r.y, r.width, r.height);
}
}
}
public class ColorListener implements MouseInputListener {
private Carre selectedCarre;
private Point pressedPoint;
#Override
public void mouseClicked(MouseEvent event) {
}
#Override
public void mouseEntered(MouseEvent event) {
}
#Override
public void mousePressed(MouseEvent event) {
pressedPoint = event.getPoint();
selectedCarre = null;
for (Carre carre : model.getCarres()) {
if (carre.getBounds().contains(pressedPoint)) {
selectedCarre = carre;
break;
}
}
if (selectedCarre != null) {
List<Carre> carres = model.getCarres();
carres.remove(selectedCarre);
carres.add(selectedCarre);
}
}
#Override
public void mouseReleased(MouseEvent event) {
updateCarrePosition(event.getPoint());
updateCarreColor();
}
#Override
public void mouseExited(MouseEvent event) {
}
#Override
public void mouseDragged(MouseEvent event) {
updateCarrePosition(event.getPoint());
updateCarreColor();
}
#Override
public void mouseMoved(MouseEvent event) {
}
private void updateCarrePosition(Point point) {
int x = point.x - pressedPoint.x;
int y = point.y - pressedPoint.y;
if (selectedCarre != null) {
selectedCarre.incrementBounds(x, y);
paneprinci.repaint();
pressedPoint.x = point.x;
pressedPoint.y = point.y;
}
}
private void updateCarreColor() {
if (selectedCarre != null) {
for (Carre carre : model.getCarres()) {
if (!carre.equals(selectedCarre) &&
carre.getBounds().intersects(selectedCarre.getBounds())) {
carre.setColor(selectedCarre.getColor());
paneprinci.repaint();
}
}
}
}
}
public class CarreModel {
private final List<Carre> carres;
public CarreModel() {
this.carres = new ArrayList<>();
for (int i = 0; i < 10; i++) {
this.carres.add(new Carre());
}
}
public List<Carre> getCarres() {
return carres;
}
}
public class Carre {
private Color color;
private final Random random;
private Rectangle bounds;
public Carre() {
random = new Random();
int red = random.nextInt(128);
int green = random.nextInt(128);
int blue = random.nextInt(128);
color = new Color(red, green, blue);
int x = random.nextInt(500);
int y = random.nextInt(500);
bounds = new Rectangle(x, y, 50, 50);
}
public void incrementBounds(int x, int y) {
bounds.x += x;
bounds.y += y;
}
public Color getColor() {
return color;
}
public void setColor(Color c) {
color = c;
}
public Rectangle getBounds() {
return bounds;
}
}
}

Java: How do I edit a JFrame using variables?

I am fairly new to Java programming and I can't figure out why this code always produces a blank JFrame:
mainClass.java:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
public class mainClass {
public static void main(String[] args) {
drawing d = new drawing();
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.setSize(1000, 1000);
d.setTitle("Test Game");
d.setVisible(true);
d.repaint();
d.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
d.repaint();
}
});
}
}
drawing.java:
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.*;
public class drawing extends JFrame implements MouseListener{
public List<units> p1 = new ArrayList<units>();
public List<units> p2 = new ArrayList<units>();
JFrame frame = new JFrame();
public void paint(Graphics g) {
for(units u : p1) {
g.setColor(new Color(0,0,255));
g.drawRect(u.unitX-1, u.unitY-1, u.unitX+1, u.unitY+1);
}
}
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
p1.add(new units(x,y));
boolean tryPrint = true;
if(p1.size()==10 && tryPrint) {
for(units u : p1) {
System.out.println(u.unitX + "," + u.unitY);
}
tryPrint = false;
}
frame.repaint();
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
units.java:
public class units {
int unitX;
int unitY;
units(int x, int y) {
unitX = x;
unitY = y;
}
}
Sorry for the wordy code. I believe the issue lies somewhere in my handling of the variables or classes. Any help is appreciated.
Also, this code is edited so that may be the reason some comments don't make sense.
First think I advise you to use more cohesive classes. Besides that I would like to say you need to override JFrame's paint method instead of creating a new class for it, see an example here: http://www.gailer-net.de/tutorials/java3/Notes/chap56/ch56_8.html.
I hope you conclude your application.
Regards,
-Rod
It appears that the issue was in my inclusion of the drawing class into a JFrame and where to locate that JFrame. My final, solved code follows:
mainClass.java:
import java.awt.event.*;
import javax.swing.*;
public class mainClass {
private static int x, y;
private static drawing d = new drawing();
public static void main(String[] args) {
JFrame frame = new JFrame("Mouse");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 1000);
frame.setResizable(false);
frame.add(d);
d.addMouseListener(new AL());
}
static class AL extends MouseAdapter{
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
d.draw(x,y);
}
}
}
drawing.java:
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class drawing extends JPanel {
public void draw(int x, int y) {
p1.add(new ArrayList<Integer>());
p1.get(p1.size()-1).add(x);
p1.get(p1.size()-1).add(y);
repaint();
}
public List<List<Integer>> p1 = new ArrayList<List<Integer>>();
public List<List<Integer>> p2 = new ArrayList<List<Integer>>();
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(List<Integer> u : p1) {
g.setColor(new Color(0,0,255));
g.fillRect(u.get(0)-1, u.get(1)-1, 3, 3);
}
}
}

Java repaint method do not working ,why?

Well my English is not so good but i will try to explain.
I was make two class,First Class and Second Class(Second was named "Grafika").
I want that my rectangle move to position where i was clicked , but obviously he dont move and i cant understand why, please help .
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class Grafika extends JPanel implements MouseListener{
static int x=0,y=0;
#Override
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(x, y, 20, 30);
}
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub``
x=arg0.getX();
y=arg0.getY();
this.repaint(x, y, 20, 30);
}
i will show you a full code, it was small .This was second class.And my(i think) only problem is repaint() method . Why i dont know :D .
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class Grafika extends JPanel implements MouseListener{
static int x=0,y=0;
#Override
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(x, y, 20, 30);
}
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
x=arg0.getX();
y=arg0.getY();
this.repaint(x, y, 20, 30);
}
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
}
}
Now i will show you first class from where i was calling second class.
import java.awt.*;
import javax.swing.*;
public class Glavna extends Grafika {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Grafika g=new Grafika();
JFrame wi=new JFrame("Grafika");
wi.setBounds(50, 50, 500, 600);
wi.add(g);
wi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wi.setVisible(true);
}
}
You've several problems in that code:
You're sort of creating a MouseListener (you're still missing several of the interface's methods), but I don't see anywhere that you've added it to your GUI. You must somewhere have addMouseListener(this); in your code for the listener to work.
Repaint by itself doesn't move the rectangle. Changing the X and Y does, but again, not without adding the MouseListener first.
You probably want to call repaint(); without parameters to paint the whole component. Otherwise the old rectangle might not get erased.
Your paintComponent method should call the super.paintComponent(g); as the first method call of your override method. Without this you won't erase the old rectangle, and you break the painting chain which could have painting side effects in child components.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Grafika extends JPanel {
private static final int RECT_W = 20;
private static final int RECT_H = 30;
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color MY_COLOR = Color.RED;
private int myX = 0;
private int myY = 0;
public Grafika() {
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse); // add MouseListener
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // **MUST** call this
g.setColor(MY_COLOR);
g.fillRect(myX, myY, RECT_W, RECT_H);
}
private class MyMouse extends MouseAdapter {
public void mousePressed(MouseEvent e) {
myX = e.getX();
myY = e.getY();
repaint(); // repaint the whole JPanel
}
}
#Override // to make the GUI larger
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Grafika mainPanel = new Grafika();
JFrame frame = new JFrame("Grafika");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
If you want to get fancier and start dragging the square around:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Grafika extends JPanel {
private static final int RECT_W = 20;
private static final int RECT_H = RECT_W;
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color MY_COLOR = Color.RED;
private int myX = 0;
private int myY = 0;
public Grafika() {
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(MY_COLOR);
g.fillRect(myX, myY, RECT_W, RECT_H);
}
private class MyMouse extends MouseAdapter {
public void mousePressed(MouseEvent e) {
moveRect(e);
}
#Override
public void mouseDragged(MouseEvent e) {
moveRect(e);
}
#Override
public void mouseReleased(MouseEvent e) {
moveRect(e);
}
private void moveRect(MouseEvent e) {
myX = e.getX() - RECT_W / 2;
myY = e.getY() - RECT_H / 2;
repaint();
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Grafika mainPanel = new Grafika();
JFrame frame = new JFrame("Grafika");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
you have to add mouse listener to component porobably
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class Grafika extends JPanel implements MouseListener{
static int x=0,y=0;
public Grafika(){
super();
addMouseListener(this); // add to constructor
}
#Override
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(x, y, 20, 30);
}
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub``
x=arg0.getX();
y=arg0.getY();
this.repaint(x, y, 20, 30);
}

Java - drawing image with Timer

I'm creating an animation that looks like this.
I'd like the swirly icon on the left (which is an ImageIcon) to display for 3 seconds and disappear. However, the swirly icon does not disappear.
Here's my code.
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("random title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public int x;
public int y;
public int remoteControllerX = 473;
public int remoteControllerY = 340;
public int buttonX = 166;
public int buttonY = 208;
Image img;
Image remoteController;
ImageIcon button = new ImageIcon("graphics/button.gif");
Component buttonTrigger = this;
public MyPanel() {
try {
img = ImageIO.read(new File("graphics/close_0.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
try {
remoteController = ImageIO.read(new File("graphics/pilot.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setBorder(BorderFactory.createLineBorder(Color.black));
new Timer(3000, paintTimer).start();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
// Here goes action on background, which is unrelated to this example.
}
});
}
public Dimension getPreferredSize() {
return new Dimension(1048, 484);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
g.drawImage(remoteController, remoteControllerX, remoteControllerY, null);
Toolkit.getDefaultToolkit().sync();
button.paintIcon(buttonTrigger, g, buttonX, buttonY);
}
Action paintTimer = new AbstractAction() {
private static final long serialVersionUID = -2121714427110679013L;
public void actionPerformed(ActionEvent e) {
buttonTrigger = null;
repaint();
}
};
}
You'll also need these 3 images for the code to run:
http://ajks.pl/graveyard/close_0.jpg
http://ajks.pl/graveyard/pilot.png
http://ajks.pl/graveyard/button.gif
They are placed in a graphics folder under the main Java project.
I added a boolean to determine whether or not to paint the swirly image icon.
Here's the corrected code.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("random title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public boolean paintButton = true;
public int x;
public int y;
public int remoteControllerX = 473;
public int remoteControllerY = 340;
public int buttonX = 166;
public int buttonY = 208;
Image img;
Image remoteController;
ImageIcon button = new ImageIcon(
"graphics/button.gif");
Component buttonTrigger = this;
public MyPanel() {
try {
img = ImageIO.read(new File("graphics/close_0.jpg"));
remoteController = ImageIO.read(new File("graphics/pilot.png"));
} catch (IOException e) {
e.printStackTrace();
}
setBorder(BorderFactory.createLineBorder(Color.black));
new Timer(3000, paintTimer).start();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
// Here goes action on background, which is unrelated to this
// example.
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1048, 484);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
g.drawImage(remoteController, remoteControllerX, remoteControllerY,
null);
Toolkit.getDefaultToolkit().sync();
if (paintButton) {
button.paintIcon(buttonTrigger, g, buttonX, buttonY);
}
}
Action paintTimer = new AbstractAction() {
private static final long serialVersionUID = -2121714427110679013L;
#Override
public void actionPerformed(ActionEvent e) {
paintButton = false;
repaint();
}
};
}

Clear painted screen at each click of the mouse?

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);
}

Categories

Resources