//I want to paint a ball in a animation
//I can't seem to find a way to repaint the ball
// Any help or tips on how to use repaint here?
//
// Ball class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Ball implements Runnable {
protected Point loc;
protected int dx;
protected int dy;
protected Color color;
protected boolean flag;
private Graphics gra;
public Ball(Point loc,int dx,int dy,Graphics st)
{
this.loc=loc;
this.dx=1;
this.dy=1;
color=Color.blue;
this.gra=st;
flag=false;
}
public void paint(Graphics g)
{
g.fillOval((int)this.loc.getX(),(int)this.loc.getY(),20,20);
}
public void move()
{
this.loc.translate(this.dx,this.dy);
}
#Override
public void run() {
while(flag==false)
{
this.paint(gra);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
move();
}
}
}
//Myframe class
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class myframe extends JFrame {
private Ball b;
public myframe()
{
super("My Frame");
setSize(800,600);
}
public void run()
{
b=new Ball(new Point(100,100),10,10,getGraphics());
b.run();
}
}
//Main class
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame
{
/**
* #param args
*/
public static void main(String[] args) {
myframe jwin = new myframe();
jwin.setSize(600, 600);
jwin.setVisible(true);
jwin.run();
}
}
You should try using repaint() instead of this.paint(gra), and put it inside the thread, you also need to add the component to you graphic interface
You need to override the paintComponent() method of the JComponent class. Have it do your painting and add that component to your GUI.
Related
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;
}
}
}
I've an image and when i click with the left button, it draws a Rectangle. I put on a LinkedList every drawn shape, so I can erase then when i want (actually when i right click the mouse button). When the method paint() or repaint() is called, it should include or remove a shape. Including is fine, but not removing :(.
Here is a short runnable of the problem
package classes;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import views.ImagePanel;
/**
*
* #author Luis
*/
public class Test extends JFrame{
private ImagePanel imgPanel;
public Test() throws HeadlessException {
imgPanel = new ImagePanel();
imgPanel.addMouseListener(imgPanel);
imgPanel.addMouseWheelListener(imgPanel);
setTitle("Test frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
add(imgPanel);
}
public static void main(String[] args) {
Test test = new Test();
test.setVisible(true);
}
}
And ImagePanel class
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.LinkedList;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
/**
*
* #author Luis
*/
public class ImagePanel extends JPanel implements MouseListener,MouseWheelListener{
private BufferedImage imagem = null;
private double txi=0; //Series of variables to do some transformations
private double tyi=0; //
private double txf=0; //
private double tyf=0; //
private double final_translx=0; //
private double final_transly=0; //
private double zoomFactor = 1; //
private LinkedList<Shape> shapes; //List of all shapes added
private boolean zoomer = false; //
public ImagePanel() {
//Initializing the list and doing some config.
shapes = new LinkedList<>();
setBorder(new LineBorder(Color.BLACK,1));
setLayout(new BorderLayout());
setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR));
try {
//This image has 981x651, but you can replace by any other
imagem = ImageIO.read(getClass().getResource("/sources/image.png"));
} catch (IOException ex) {
}
}
#Override
public void paint(Graphics g) {
super.paint(g); //To change body of generated methods, choose Tools | Templates.
//Doing the transformations of the jPanel inside the jFrame (possibly)
Graphics2D panelGraphics = (Graphics2D) g;
AffineTransform at = AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
panelGraphics.drawImage(imagem, at, this);
//Adding shapes in the image
Graphics2D imageGraphics = (Graphics2D)imagem.getGraphics();
imageGraphics.setColor(Color.red);
for (Shape s : shapes){
//This is where i think it should overwrite all the shapes
imageGraphics.draw(s);
}
}
#Override
public void mouseClicked(MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e)){
//creating a new shape when i left click the mouse
shapes.add(new Rectangle(Math.toIntExact((long) (e.getX()/zoomFactor-final_translx)),Math.toIntExact((long) (e.getY()/zoomFactor-final_transly)), 100, 100));
}
else{
if(shapes.size()>0){
//the part when it should remove;
shapes.removeLast();
}
}
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
//Initial point to calculate the translation
if(SwingUtilities.isLeftMouseButton(e)){
txi = e.getX()/zoomFactor;
tyi = e.getY()/zoomFactor;
}
}
#Override
public void mouseReleased(MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e)){
txf = e.getX()/zoomFactor;
tyf = e.getY()/zoomFactor;
final_translx += txf-txi;
final_transly += tyf-tyi;
//final translation
repaint();
}
}
#Override
public void mouseEntered(MouseEvent e) {
//do nothing
}
#Override
public void mouseExited(MouseEvent e) {
//do nothing
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
zoomer=true;
zoomFactor += e.getWheelRotation()*0.01;
repaint();
}
}
The final purpose of this is, in the future, to add balloons and insert information in regions that the user want!
Any ideas about how to properly remove those shapes?
I'm open to any other suggestion too!
thanks in advance
The easiest way is probably to repaint (load) the original image, draw all shapes again and omit the shape you want to remove.
I started a school project trying to draw 9*9 and 17*17 pixels JPanels on a bigger JPanel, imitating a pen in Gimp for instance.
I tried to capture the mouse position using MouseClicked to start, MouseDragged to listen and repaint() the (big)JPanel where i want the pen to draw and MouseReleased to record.
The problem is that the MouseDragged does not listen enough to the mouse so i get random points if i move to fast.
Here is my MVC pattern, Create.java - DrawGame.java - ControleurGame.java
WHat do you think would be best ?
package controleur;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.applet.*;
import java.net.*;
import vue.*;
import vue.Draw.*;
import vue.DrawGame.*;
import modele.*;
/**
*
* #author Yann
*/
public class ControleurGame extends ControleurDraw implements MouseMotionListener {
int mode;
Area zone;
Create draw;
public ControleurGame (Background bg, JButton[] jip, Utilisateur uti, int n, Area j, Create d) {
super(bg);
user = uti;
butts = jip;
mode = n;
zone = j;
draw = d;
resume = new JLabel (user.toString());
resume.setForeground(Color.LIGHT_GRAY);
resume.setBounds(45,600,256+128,32);
resume.setVisible(true);
pan.add(resume);
pan.add(zone);
pan.repaint();
}
#Override
public void focusGained (FocusEvent e) {
if (e.getSource() instanceof JButton) {
but = (JButton)e.getSource();
but.setSelected(true);
pan.repaint();
}
}
#Override
public void focusLost (FocusEvent e) {
if (e.getSource() instanceof JButton) {
but = (JButton)e.getSource();
but.setSelected(false);
pan.repaint();
}
}
#Override
public void keyTyped (KeyEvent e) {
}
#Override
public void keyPressed (KeyEvent e) {
if (e.getSource() instanceof JButton) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
but = (JButton)e.getSource();
but.doClick();
}
}
}
#Override
public void keyReleased (KeyEvent e) {
}
#Override
public void actionPerformed(ActionEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
draw.pixels.add(draw.index,new ArrayList<Point>());
draw.pixels.get(draw.index).add(e.getPoint());
System.out.println(e.getPoint().toString());
zone.addP((int)e.getPoint().getX(),(int)e.getPoint().getY());
pan.repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
draw.pixels.get(draw.index).add(e.getPoint());
System.out.println(e.getPoint().toString());
zone.addP((int)(e.getPoint().getX()),(int)e.getPoint().getY());
pan.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
draw.index++;
}
#Override
public void mouseMoved(MouseEvent e) {
if (draw.dragging) {
}
}
#Override
public void mouseEntered(MouseEvent e) {
pan.repaint();
}
#Override
public void mouseExited(MouseEvent e) {
if (e.getSource() instanceof JButton){
but = (JButton)e.getSource();
but.setSelected(false);
}
pan.repaint();
}
}
Create.java
package modele;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JPanel;
/**
*
* #author Matthew
*/
public class Create {
public static boolean dragging = false;
public int index = 0;
public ArrayList<ArrayList<Point>> pixels;
public Create () {
pixels = new ArrayList<ArrayList<Point>>();
}
}
DrawGame.java
package vue;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.applet.*;
import java.net.*;
import controleur.*;
import modele.*;
/**
*
* #author Yann
*/
public class DrawGame extends Draw {
int mode = 0;
Area tableau;
Create dessin;
public DrawGame (int n, Utilisateur u) {
super(n);
user = u;
library();
dessin = new Create();
try {tableau = new Area();} catch (Exception e) {e.printStackTrace();}
poulet = new ControleurGame(fond,butts,user,mode,tableau,dessin);
tableau.addMouseMotionListener(poulet);
tableau.addMouseListener(poulet);
fond.add(tableau);
fond.repaint();
}
public class Area extends JPanel {
BufferedImage bi = ImageIO.read(new File("../src/png/game/01AreaHL.png"));
public Area () throws IOException {
this.setLayout(null);
this.setBounds(10,50,515,450);
this.setBackground(new Color(0,0,0,0));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}
public void addP (int n, int m) {
try {this.add(new Pix(n,m));} catch (IOException e) {e.printStackTrace();};
}
public class Pix extends JPanel {
BufferedImage bp;
Random rand = new Random();
public Pix (int n, int m) throws IOException {
try {bp = ImageIO.read(new File("../src/png/game/Points16-2/1602"+rand.nextInt(8)+".png"));} catch (IOException e) {e.printStackTrace();};
this.setLayout(null);
this.setBounds(n-8,m-8,17,17);
this.setBackground(new Color(0,0,0,0));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bp, 0, 0, null);
}
}
}
public void library() {
try {icons[0] = ImageIO.read(new File("../src/png/game/00FondGame.png"));}
catch (IOException e) {e.printStackTrace();}
}
public static void main (String[] args){
DrawGame d = new DrawGame(1, Database.getUser("n0x"));
}
}
The problem is that the MouseDragged does not listen enough to the mouse so i get random points if i move to fast.
Yes, you will never get all the points when the mouse is moved fast.
The solution is to change your painting code to draw lines between two points.
So you need to iterate through your ArrayList that contains your Points. Draw an line between the first and second, then the second and third etc.
I am currently writing a small program where I'm supposed to use basic transformations. Right now, I'm working on being able to move the polygon by using the arrow keys. Right now I can move it to the right by pressing the mouse, but I'd rather be able to use the right arrow key. However, I haven't been able to no matter which method I tried.
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
class PolygonPanel extends JPanel implements MouseListener{
Polygon p;
public PolygonPanel(){
p = new Polygon();
p.addPoint(10, 10);
p.addPoint(100,50);
p.addPoint(50,100);
addMouseListener(this);
addKeyListener(new MKeyListener());
}
class MKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode==e.VK_RIGHT){
System.out.println("FFFFUUUUU");
}
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.white);
g.fillPolygon(p);
}
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("hei");
for (int i = 0; i < p.npoints; i++) {
p.xpoints[i] = p.xpoints[i]+10;
repaint();
}
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class PolygonFrame extends JFrame{
public PolygonFrame(){
setTitle("Polygoner");
setSize(700, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.add(new PolygonPanel());
}
}
public class Polygonfun {
public static void main(String[] args) {
JFrame frame = new PolygonFrame();
frame.setVisible(true);
}
}
Nothing happens when I press the right arrow key. I also tried implementing it like this:
class PolygonPanel extends JPanel implements MouseListener,KeyAdapter
And then adding the unimplemented methods, but that didn't work either. I know i've probably overlooked something, but I cant seem to figure it out. Any advice?
Thanks
set this.setFocusable(true); for your panel.
Should be:
public PolygonPanel(){
p = new Polygon();
p.addPoint(10, 10);
p.addPoint(100,50);
p.addPoint(50,100);
addMouseListener(this);
this.setFocusable(true);
this.addKeyListener(new MKeyListener());
}
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.