MouseLintener does not work - java

I am learning the template method and delegation now. I do not understand what interface inheritance to the newClass, and then the newClass past its inside method to NextClass.
When I ran it, MouseLintener does not work.
Could you please teach me how to fix my codes?
Thank you!
public class KiteComponent extends JComponent{
private ArrayList<Kite> kites;
private Point mousePoint;
public KiteComponent() {
kites = new ArrayList<Kite>();
ColoredCompoundShape c = new ColoredCompoundShape();
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
mousePoint = e.getLocationOnScreen();
for (Kite s: kites){
if (s.contains(mousePoint))
s.setColor(s.getColor());}
repaint();
}
});
}
public void add(Kite k){ kites.add(k);repaint();}
public void paintComponent (Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Kite s : kites){ s.drawInColor(g2); }
}
}

s.setColor(s.getColor())
Isn't this useless, it's setting the same color it already is... If you think that this actually isn't being called, print a line in your mouseClicked method to check if it's actually being called.

Related

Dynamic graphic programming (Animation)

I am trying to code a simple animation like a moving circle. I have tried using getGraphics() and work with that but it's not dynamic and it's painted for just one time
So please help me and guide me to code a dynamic graphic program.
I mean for example defining a function and every time when it called, it draws a line on a label.
Here is how to make a growing rectangle:
public class MovingRectangle extends JPanel {
private Timer timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent event) {
rectWidth += 100;
repaint();
}
};
private int rectWidth = 100;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0, 0, 100. rectWidth);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
public void reset() {
rectWidth = 100;
repaint();
}
}
you should override the paintComponent(Graphic g).
This method is called every time the repaint() is called, so you should periodic calling that method.
You should also set DoubleBuffering on true: setDoubleBuffered(true)
It will prevent possible flicker of your animation

how to draw multiple rectangles

so I am trying to make a simple program where you click on the screen and it creates a block that falls and collides with a larger block beneath and sticks to it. Kind of like a simple collision program. The problem is when I create one block it deletes the block previously. I made an array, but it still does this. Do any of you know what Im doing wrong? Im sure its a simple fix.
public class Screen extends JPanel implements Runnable {
public static JLabel statusbar; //displays a status bar showing what mouse movements are taking place
private Image cat; //image of the cat
public int xCoord ; //get the coordinates of the mouse pressed
public int yCoord ;
public int xCreate;
public int yCreate;
public Rectangle Ground;
public Rectangle Block;
public boolean isClicked = false;
public int clickCount = 0;
Rectangle blocks[] = new Rectangle[10];
int blocknum = 0;
public Screen(Frame frame) {
loadPic(); //calls the loadPic method above
Handlerclass handler = new Handlerclass(); //creates a new class to use the mouse motion listener
System.out.println("mouse works!");
addMouseListener(handler);
addMouseMotionListener(handler);
statusbar = new JLabel("default");
add(statusbar);
}
public void run(){ //this is the game run loop
System.out.println("this is running");
try{
} catch(Exception e) {} //exception handling
}
public void loadPic(){ //loads the picture from the other project but its the same pic
cat = new ImageIcon("C:\\Users\\Camtronius\\Documents\\NetBeansProjects\\Moving Block Proj\\src\\MovingBlock\\catIcon1.png").getImage(); //gets the image
System.out.println("Image Loaded!");
}
#Override public void paintComponent(Graphics g){
super.paintComponent(g); //paints the component, the picture, on top
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(cat, xCoord, yCoord, null);
g2d.setColor(Color.BLUE);
Ground = new Rectangle(0,450,550,50);
g2d.fillRect(0,450, 550, 50);
for(Rectangle blocknum : blocks){
if (blocks != null) {
g2d.setColor(Color.RED);
g2d.fillRect(xCreate,yCreate,50,50);
System.out.println(blocknum);
}
}
//move();
}
public void move(){
if(yCreate<400){
yCreate+=1;
}else{
}
if(Ground.intersects(blocks[blocknum])){
yCreate=400;
System.out.println("contains!");
}
}
private class Handlerclass implements MouseListener, MouseMotionListener{
public void mouseClicked(MouseEvent event){
}
public void mousePressed(MouseEvent event){
}
public void mouseReleased(MouseEvent event){
if(blocknum<blocks.length){
xCreate=event.getX();
yCreate=event.getY();
blocks[blocknum] = new Rectangle(50,50, xCreate, yCreate);
repaint();
}
blocknum=blocknum+1;
}
public void mouseEntered(MouseEvent event){
}
public void mouseExited(MouseEvent event){
}
public void mouseDragged(MouseEvent event){
}
public void mouseMoved(MouseEvent event){
statusbar.setText(String.format("Coordinates are: %d, %d", event.getX(),event.getY()));
xCoord=event.getX();
yCoord=event.getY();
}
}
}
Painting is a destructive process. That is, when a new paint cycle runs, the previous contents of the Graphics context should be cleared...
So, in you paintComponent method you are only painting the last block...
if(isClicked = true){
blocks[blocknum] = new Rectangle(50,50, xCreate, yCreate);
g2d.setColor(Color.RED);
g2d.fillRect(xCreate,yCreate,50,50);
System.out.println(blocknum);
repaint(); // THIS IS A BAD IDEA
}
DO NOT call any method that might cause repaint to be called. This will put you in a potential cycle of death that will consume your CPU.
Instead, you should loop through the blocks array and paint each one...
for (Rectangle block : blocks) {
if (block != null) {
g2d.setColor(Color.RED);
g2d.fill(block);
}
}
And in you mouseReleased method, you should be adding the new rectangles...
public void mouseReleased(MouseEvent event){
blocknum=blocknum+1;
if (blocknum < blocks.length) {
xCreate=event.getX();
yCreate=event.getY();
blocks[blocknum] = new Rectangle(xCreate, yCreate, 50, 50);
}
}
I'd suggest you take a look at Custom Painting, Painting in AWT and Swing and Concurrency in Swing for more details

Java Draw Shapes Error

I have to write a program using applet it should have 3 Button line,rect,circle.Upon clicking on them the desired shape should be drawn.
I have written the following code but it is showing error that Graphics is not initialized.
What to do now?
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Drawshapes extends Applet implements ActionListener
{
Button line,rect,circle;
public void init()
{
line=new Button("Line");
rect=new Button("Rectangle");
circle=new Button("Circle");
add(line);
add(circle);
add(rect);
line.addActionListener(this);
rect.addActionListener(this);
circle.addActionListener(this);
}
public void paint(Graphics g)
{
}
public void actionPerformed(ActionEvent ae)
{
Graphics g;
if(ae.getSource()==line)
{
g.drawLine(0,100,100,10);
}
else if(ae.getSource()==rect)
{
g.drawRect(10,10,60,50);
}
else
{
g.drawOval(10,10,50,50);
}
}
}
As with all local variables, the Graphics g is required to be initialized. However, doing custom painting from the ActionListener is a bad idea. Use the Graphics object in the paint method which has been properly instantiated.
Set a flag in the ActionListener and then call repaint:
For example in ActionListener for line:
drawLine = true;
repaint();
paint:
#Override
public void paint(Graphics g) {
super.paint(g);
if (drawLine) {
g.drawLine(0, 100, 100, 10);
} else if (drawRect) {
g.drawRect(10, 10, 60, 50);
} else {
g.drawOval(10, 10, 50, 50);
}
}
You didn't initialize your Graphics reference. You can initialize it by calling the getGraphics() method that Applet inherits from Component.
Graphics g = getGraphics();
Your are calling methods from g which is not intialized as your error says : you have only declared it.
Edit : as others have said, your Graphics object is a member of Applet, and is accessible from the method getGraphics. Therefore you can call this method everytime you need it, or create a member in your DrawShapes class.
Graphics g = getGraphics();
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==line)
{
g.drawLine(0,100,100,10);
}
// etc
}

painting from an external method

In my applet I have a method paint that paints on screen.
public void init() {
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent evt) {
storeCoordinates(evt,Graphics g); // results in error
}
});
}
public void paint(Graphics g) {
// do something
}
public void storeCoordinates(MouseEvent evt , Graphics g) {
// from this method i want to modify the scene painted by paint
}
Now in another method I want to modify a bit of a scene that was painted by the paint method. How can I do this ? Like I want to draw blue lines using g.drawLine(.,.,.,.) from another method.
The above snippet generates an error saying ) expected ; expected , cannot find symbol variable Graphics when i call the function from mouseMoved
In response to edits:
So what I would do in this case is not use the graphics right there. Instead, I would do something like this... Keep a list of your points, and when you click, add the point to your list. Then when you draw, draw your points. (If you're only going to be drawing on click, you could just store the last point, draw a line between the current point and the last point, and set the last point to the current point. But this is more extensible.)
List<Point> points = new ArrayList<Points>();
public void init() {
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent evt) {
storeCoordinates(evt); // graphics removed
}
});
}
public void paint(Graphics g) {
for(int i = 1; i < points.size(); i++) {
Point first = points.get(i - 1);
Point second = points.get(i);
g.setColor(Color.BLUE);
g.drawLine(first.getX(), first.getY(), second.getX(), second.getY());
}
}
public void storeCoordinates(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
points.add(new Point(x,y));
}
.
Old Answer
Pass your graphics object as a parameter to that other method.
public void paint(Graphics g) {
externalPaint(g);
}
private void externalPaint(Graphics g) {
g.drawLine(1,2,3,4);
}
Now in another method I want to modify a scene on that was painted by the paint method. How can I do this?
Call Component.repaint(int,int,int,int) or JComponent.repaint(Rectangle).

How to render a 2d image in Java

I have a quick question about Java. I'm sorry if this question is really basic, but I'm a beginner Java programmer :D
I want to render a 2d image in a window, but I can't figure it out. I've looked at the graphics API here:
http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html
and the only method I could find that might work is drawImage().
It wasn't working for me, though, but maybe it has to do with the ImageObserver Observer parameter? I just put null for that following some tutorial I found somewhere, but I still get a compile error:
Here is my paint method:
public void paint(Graphics g)
{
Image img1 = Toolkit.getDefaultToolkit().getImage("theImage.png");
g.drawImage(img1, 100, 100, null);
} // public void paint(Graphics g)
and here are the methods that call it:
public static void main(String[] args)
{
MyGame game = new MyGame();
game.setVisible(true);
game.play();
} // public static void main(String[] args)
/** The play method is where the main game loop resides.
*/
public void play()
{
boolean playing = true;
//Graphics g = new Graphics();
while (playing)
{
paint();
}
} // public void play()
The thing is when I call paint in the while loop, I get this error:
paints(java.awt.Graphics) in MyGame cannot be applied to ()
What does that mean? How can I fix it so I can successfully render a 2d image?
Thanks in advance :D
Instead of paint(); use repaint();
You should be overriding paintComponent(Graphics g). Also, as #TotalFrickinRockstarFromMars suggested, you should be invoking repaint().
You overrid the paintComponent(Graphics g)
class Game extends JComponent { // Your game class
Image img = null;
public Game() {
img = getImage("/theImage.png");
}
private Image getImage(String imageUrl) {
try {
return ImageIO.read(getClass().getResource(imageUrl));
} catch (IOException exp) {}
return null;
}
paintComponent(Graphics g) {
g.drawImage(img, 100, 100, null);
}
}

Categories

Resources