Move a rectangle in a JPanel using the keys - java

I have a class called "DisplayPanel" (which extends JPanel) and I draw a square there that comes from a class called "Square" (which extends JComponent). How to move a rectangle in a JPanel using the keys?
The Square class has the usual painting method:
public void paintComponent(Graphics g) {
Dimension dimension = getSize();
super.paintComponent(g);
Graphics2D graphics2D = (Graphics2D) g;
g.setColor(Color.black);
graphics2D.fill(squarishThing);
}
And the "squarishThing" is a normal rectangle:
Rectangle squarishThing = new Rectangle (0, 0, 50, 50);
The thing is: Unlike "game libraries", trying to do such a thing "manually" is quite confusing. I don't know where the "while loop" goes. I tried to put a KeyListener in the DisplayPanel and I failed miserably to update the rectangle. There's no loop, and I can't repaint the rectangle because the method paintComponent takes that unpleasant argument. OBS: Everytime I try to insert a loop, the software crashes dramatically, so I gave up of doing so.
What can I do to repaint the object according to inputs?

can't repaint the rectangle because the method paintComponent takes that unpleasant argument.
Never ever call paintComponent, instead use repaint().
Using KeyBindings simply update "squarishThing" to the appropriate value, then call repaint().

Related

Java Graphics2D Image Moving

So in this block of code, a 40x40 square can move across a window by calling directional methods, and I'm trying to get a spaceship to appear instead of the square. No matter what I try, it just isn't working.
public void paintComponent (Graphics g) {
ImageIcon wallpaper = new ImageIcon("images/JGalagawallpaper.png");
image = wallpaper.getImage();
g.drawImage(image, 400, 400, null);
ImageIcon ship = new ImageIcon("images/galaga.png");
galaga = ship.getImage();
super.paintComponent(g);
Graphics2D graphic = (Graphics2D) g;
graphic.fill(new Rectangle.Double(x, y, 40, 40));
//graphic.drawImage(galaga, x, y, 40, 40);
}
My question is, how do I get that thing to appear? I already tried tinkering with graphic.drawImage, however that didn't really work out as well as I hoped. That's what the commented out code is.
g.drawImage(image, 400, 400, null);
First you draw the image.
super.paintComponent(g);
Then you invoke the above code which is used to pint the background color of the panel, thus overwriting the image. The above statement should be the first statement of the painting method.
ImageIcon wallpaper = new ImageIcon("images/JGalagawallpaper.png");
A painting method is for painting only. Don't do I/O in the method. The image should be read in the constructor of your class so that it is only read once, not every time the component is repainted.
You also need to look at the coordinates of where you paint the image. Maybe the panel is not that big?
Did you verify that the image was read properly by display its size?

Filling circles with color

I am trying to run a program that fills the circles with color I am not sure what I am doing incorrectly I am getting a cannot find symbol error for my fillOval command here is my code. Also the fill should be the same color as the drawn circle.
import javax.swing.JApplet;
import java.awt.*;
import java.util.Random;
public class Drawing extends JApplet
{
public void paint(Graphics page)
{
Random generator=new Random();
float r = generator.nextFloat();
float g = generator.nextFloat();
float b = generator.nextFloat();
Color randomColor = new Color(r, g, b);
int random,randomx,randomy;
int x,y;
int width, height;
setBackground(Color.white);
random=generator.nextInt(24)+8;
randomx=generator.nextInt(24);
randomy=generator.nextInt(24);
x=randomx;
y=randomy;
width=random*2;
height=random*2;
page.drawOval(x, y, width, height);
page.setColor(randomColor);
fillOval(x, y,width,height);
}
}
fillOval is a method of Graphics rather than your custom Drawing class.
fillOval(x, y, width, height);
should be
page.fillOval(x, y, width, height);
Problems:
You're calling fillOval by itself and not on any variable, such as the page variable.
You should not override the paint method of any component except in unusual circumstances.
You should not draw directly in a top-level window such as a JApplet.
You're posting un-formatted all left-justified code, making it somewhat difficult to read and understand.
I suggest:
Create a class that extends JPanel and override its paintComponent(Graphics g) method.
Don't forget to call the super's paintComponent method, super.paintComponent(g), in your paintComponent override method, so that the component does all its housekeeping painting before doing your painting.
Draw with its Graphic object that is passed into the method's parameter.
Add the JPanel to your JApplet to display it.
When posting code here, please format your posted code by giving it proper indentations, usually 3 spaces per block, and making sure that all code on the same block is on the same indentation level. Your cooperation in this would be greatly appreciated and will likely improve your chances of getting a decent and prompt answer. Remember that we are all volunteers and thus you should strive to make helping you as easy as possible.

Calling repaint() without loosing previous graphic

Im making a small program that needs previous graphics to stay "put" and visible, even after a repaint causes a variable location to change.
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.red);
g.fillOval(mouseLocX,mouseLocY,30,30);
}
this is all i have in the paint class, and i want to change the mouseLocX and mouseLocY values, and call repaint without having the previous location there. Ive done this before, and most people want the opposite, but i forgot how. Im calling repaint from a MouseMotionListener using mouseDragged();
If you want to preserve what's already been painted so that you get a trail of red ovals instead of a single red oval as the mouse moves, then you shouldn't paint directly on the Graphics object provided by paint(). Instead, use a BufferedImage to store your state. Then render the BufferedImage onto the Graphic provided by paint().
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
public void paint(Graphics g) {
super.paint(g);
Graphics imageGraphics = image.getGraphics();
imageGraphics.setColor(Color.red);
imageGraphics.fillOval(mouseLocX,mouseLocY,30,30);
g.drawImage(image, 0, 0, null);
}
The BufferedImage provides the persistence for the previous draw operations.

Elements not drawing when paint() is directly invoked, but drawing when added to content pane

A Graph object is being added to a JFrame. This object draws axes followed by a graph plot. When the object's paint() is invoked implicitly through the JFrame using:
this.getContentPane().add(new Graph());
both the axes and the function draw. However, when the paint() method is explicitly invoked, via:
Graph g = new Graph();
g.paint(this.getContentPane().getGraphics());
the axes do not draw, however the function does. The full constructor for the JFrame is as follows:
public GraphFrame() {
super("");
setSize(800, 800);
setVisible(true);
//One of the above blocks is called here
}
The function paint in object Graph is as follows:
public void paint(Graphics w) {
w.setColor(Color.WHITE);
w.fillRect(0, 0, 800, 800); //Clears the screen
w.setColor(Color.BLACK);
w.drawLine(100, 0, 100, 800);
w.drawLine(0, 700, 800, 700); //(Should) Draw the axes
for(int i = 1; i < 650; i++) {
//Draws the function
//This is just a repeated drawLine call.
}
}
Why would the axes draw when implicitly called when components paint, but not draw when explicitly invoked? Remember that the function draws (the block in the for loop), while the axes preceding the for loop do not.
Don't call paint directly on a component. Also for custom painting in Swing use paintComponent rather than paint and remember to call super.paintComponent(g). Also getGraphics returns a transient Graphics reference so should not be used for custom painting. In contrast the Graphics reference in paint (and paintComponent) is always initialized correctly and will display graphical output as expected.
Performing Custom Painting
Painting in AWT and Swing

I am having problems setting graphics2D

I am making a simple game where there are two rectangles drawn on the screen and with user input from the keyboard arrow keys one of the rectangles (the player) will move. I have made a Main class and a Play class which consists of all my game code, this code includes methods such as init(), update() and render(), the init() deals with all the initial conditions, the update() deals with the movement and key inputs from the input and the render() method deals with drawing the stuff onto the screen such as the background and rectangles.
The problem I am having is drawing my rectangles (which are set up with my variables) on my screen by putting them in my render class, my method is set up with Graphics and I have been told I require Graphics2D so I am attempting to change my graphics to Graphics2D so that I can draw my rectangles.
Here are my Rectangles which have been set up with my variables at the top of my ode:
Rectangle rectOne = new Rectangle(shiftX, shiftY,90,90);
Rectangle rectTwo = new Rectangle(500 + buckyPositionX, 330 + buckyPositionY, 210, 150);
and here is my render method where I am trying to draw my rectangles using the graphics2D:
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
if(rectOne.intersects(rectTwo)){
g.drawString("Intersect", 100, 100);}
if(g instanceof Graphics2D){//error: Incompatible conditional operand type Graphics and Graphics2D
Graphics2D g2 = (Graphics2D)g;}//cannot cast from Graphics to Graphics2D
((Graphics2D)g).fill(rectOne);//cannot cast from Graphics to Graphics2D
((Graphics2D)g).fill(rectTwo);//cannot cast from Graphics to Graphics2D
}
The comments next to my code shows the errors that are appearing when I try to use this code. If any more code or information is required from my Play class please tell me and I will post it.

Categories