How to create a Rectangle object in Java using g.fillRect method - java

I need to create a rectangle object and then paint it to the applet using paint(). I tried
Rectangle r = new Rectangle(arg,arg1,arg2,arg3);
Then tried to paint it to the applet using
g.draw(r);
It didn't work. Is there a way to do this in java? I have scoured google to within an inch of its life for an answer, but I haven't been able to find an answer. Please help!

Try this:
public void paint (Graphics g) {
Rectangle r = new Rectangle(xPos,yPos,width,height);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}
[edit]
// With explicit casting
public void paint (Graphics g) {
Rectangle r = new Rectangle(xPos, yPos, width, height);
g.fillRect(
(int)r.getX(),
(int)r.getY(),
(int)r.getWidth(),
(int)r.getHeight()
);
}

You may try like this:
import java.applet.Applet;
import java.awt.*;
public class Rect1 extends Applet {
public void paint (Graphics g) {
g.drawRect (x, y, width, height); //can use either of the two//
g.fillRect (x, y, width, height);
g.setColor(color);
}
}
where x is x co-ordinate
y is y cordinate
color=the color you want to use eg Color.blue
if you want to use rectangle object you could do it like this:
import java.applet.Applet;
import java.awt.*;
public class Rect1 extends Applet {
public void paint (Graphics g) {
Rectangle r = new Rectangle(arg,arg1,arg2,arg3);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
g.setColor(color);
}
}

Note:drawRect and fillRect are different.
Draws the outline of the specified rectangle:
public void drawRect(int x,
int y,
int width,
int height)
Fills the specified rectangle. The rectangle is filled using the graphics context's current color:
public abstract void fillRect(int x,
int y,
int width,
int height)

Related

JLabel text not updating [duplicate]

I am aware this is my error. My question is why isn't this working what am i missing i can call this is i put it a method instead of a class so i am assuming theirs something wrong with the third class?
Class 1:
package assignment.pkg1.java;
import java.awt.Color;
import javax.swing.JFrame;
public class JVMVeiwer {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final int FRAME_WIDTH = 1000; // Frame Width
final int FRAME_HEIGHT = 800; // Frame Height
JFrame frame = new JFrame();
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); //Sets Frame Size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("JVM Diagram");// Sets the Title
JVMComponent component = new JVMComponent();
frame.setBackground(Color.WHITE);
frame.add(component); // adds the diagram to the JFrame
frame.setVisible(true); // Makes the frame visible
}
}
Class 2:
package assignment.pkg1.java;
import java.awt.*;
import javax.swing.JComponent;
public class JVMComponent extends JComponent {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g; // recover the graphic
JVMDiagram diagram = new JVMDiagram(); // creates an instance of JVM Diagram
diagram.draw(g2);
}
}
Class 3 this is the one i i cant use o paint to the jframe:
package assignment.pkg1.java;
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class JVMDiagram {
// Constructor
public JVMDiagram() {
}
// Draw method for shape
public void draw(Graphics2D g2) {
// Detailed instructions to draw shape
int x = getWidth();
int y = getHeight();
int temp, temp2;
int width = x / 2;
int height = x / 2;
x = (x - width) / 2;
y= (y - height) / 2;
g2.setColor(Color.RED);
g2.drawOval(x, y, width, height);
g2.drawRect(x, y, width, height);
g2.setColor(Color.RED);
g2.drawLine(x, y, width + x, height + y);
g2.drawRoundRect(x, y, width, height, y, y);
g2.drawLine(x + width, y, x, height + y);
}
}
Your problem is that you're misusing inheritance. Your JVMDiagram is extending JVMComponent and it shouldn't. Yes, you gain JVMComponent's getWidth() and getHeight() method, but they don't mean anything since JVMDiagram isn't being added to the GUI as a component, shouldn't be added as a component, and it has 0 height and width (print them out).
Rethink your design, don't use inheritance for this. Instead pass in values from one object to the other if needed. For instance, create a JVMDiagram field within JVMComponent and initialize it. Pass in the width and height with the Graphics2D in the JVMDiagram draw method in JVMComponent's paintComponent method.
Side issue: never call repaint() from within a painting method or from code that is called from within a painting method.

java, when i use doublebuffering, painted image is expanded

when i use doublebuffering, painted image is expanded with white background.
Is there something wrong?
enter code here
private Image image_buffer;
private Graphics graphics_buffer
public void paint(Graphics g) {
super.paint(g);
buffering(img1, x1, 40, g);
}
public void buffering(Image img, int x, int y, Graphics g){
image_buffer = createImage(100,100);
graphics_buffer = image_buffer.getGraphics();
buffer.drawImage(img, x, y, this);
g.drawImage(image_buffer, x, y, this);
}
Why not replace your code with just:-
public void paint(Graphics g) {
super.paint(g);
g.drawImage(img1, x1, 40, this);
}
The reason you have a white background is because you're creating a 100x100 "canvas", and drawing on that.

Drawing multiple ovals in java

I am presently planning to write some code for collision detection. However, I came across a problem. I want to draw multiple spheres on the JFrame window but the following code isn't working... Kindly help me out...
This is my code :-
import javax.swing.*;
import java.awt.*;
class Draw extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i=0;i<20;i++)
drawing(g,new Sphere());
}
public void drawing(Graphics g,Sphere s)
{
g.setColor(s.color);
g.fillOval(s.x,s.y,s.radius*2,s.radius*2);
}
public static void main(String args[])
{
JFrame jf = new JFrame("Renderer");
jf.getContentPane().add(new Draw(),BorderLayout.CENTER);
jf.setBounds(100,100,400,300);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
class Sphere
{
int x;
int y;
int radius;
Color color;
public Sphere()
{
this.x = (int)Math.random()*100;
this.y = (int)Math.random()*100;
this.radius = (int)Math.random()*20;
this.color = new Color((int)(Math.random()*255),
(int)(Math.random()*255),(int)(Math.random()*255));
}
}
You cast the random value to int so that it is 0 and then multiply it.
Your Sphere Constructor should look like
public Sphere() {
this.x = (int) (Math.random() * 100); // cast the result to int not the random
this.y = (int) (Math.random() * 100);
this.radius = (int) (Math.random() * 20);
this.color = new Color((int) ((Math.random() * 255)), (int) (Math.random() * 255), (int) (Math.random() * 255));
}
for(int i=0;i<20;i++)
drawing(g,new Sphere());
A painting method is for painting only.
You should NOT be creating Sphere objects in the paintComponent() method. You can't control when Swing repaints the panel.
Instead, in the constructor of your Draw class you need to create an ArrayList of Sphere objects and you add the 20 objects to the list.
Then you need to add a paint(...) method to your Sphere class so the Sphere object knows how to paint itself. Something like:
public void paint(Graphics g)
{
g.setColor( color );
g.fillOval(x, y, width, height) //
}
Then in the paintComponent(...) method your Draw class you need to iterate through the ArrayList and paint each Sphere:
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (each sphere in the ArrayList)
sphere.paint(g);
}

Class is not abstract and does not override abstract method

So I've been working on a homework on abstraction for my programming class and fell into a problem. The goal for me right now is to be able to use abstraction, then later be able to draw with rectangles and ovals a simple city, like a rectangular building or a oval light on a light post.
The error I am receiving when I compile is: MyTestApp.Rectangle is not abstract and does not override abstract method drawEllipse(java.awt.Graphics) in MyTestApp.Shape. This Error shows up on the line "class Rectangle extends Shape{" right below the class Shape.
My question is what am I doing wrong with my abstraction? I've been messing with the constructors and draw() methods in classes Rectangle and Ellipse for a while now and still to no luck happen to find a solution.
Code is below:
import java.awt.*;
import javax.swing.*;
public class MyTestApp extends JPanel {
Rectangle rect;
Ellipse oval;
public static void main(String [] args) {
MyTestApp myTestApp = new MyTestApp ();
myTestApp.test();
}
public MyTestApp () { //creates the jframe
JFrame frame = new JFrame("MyClass Driver");
setBackground(new Color(200, 250, 200));
setPreferredSize(new Dimension(500, 400));
frame.add(this);
frame.pack();
frame.setVisible(true);
}
public void delay(int msecs) {
try {
Thread.sleep(msecs);
} catch (InterruptedException e) {
}
}
public void paint(Graphics g) {//paints the rectangle and ellipse
super.paint(g);
if (rect != null)
rect.drawRectangle(g);
if (oval != null)
oval.drawEllipse(g);
}
public void test() {//gives the x/y position, width/height, and fill/outline color for the rectangle and oval
delay(1000);
rect = new Rectangle(20, 30, 23, 75, Color.GREEN, Color.BLUE);
oval = new Ellipse(10, 10, 10 , 34, Color.RED, Color.MAGENTA);
repaint();
}
public abstract class Shape{//abstract class Shape that sets the x/y, width/height, and colors for the shapes
private int x, y, width, height;
private Color fillColor;
private Color outlineColor;
public Shape(int x, int y, int width, int height, Color fillColor, Color outlineColor) {
setXY(x, y);
setSize(width, height);
setFillColor(fillColor);
setOutlineColor(outlineColor);
}
public boolean setXY(int x, int y) {
this.x = x;
this.y = y;
return true;
}
public void setSize(int width, int height) {
if (width > 0)
this.width = width;
if (height > 0)
this.height = height;
}
public boolean setFillColor(Color fillColor){
if (fillColor == null) return false;
this.fillColor = fillColor;
return true;
}
public boolean setOutlineColor(Color outlineColor){
if (outlineColor == null) return false;
this.outlineColor = outlineColor;
return true;
}
public Color getFillColor() {
return fillColor;
}
public Color getOutlineColor() {
return outlineColor;
}
public abstract void drawRectangle(Graphics g);//do i need two?
public abstract void drawEllipse(Graphics g);//do i need both?
}
class Rectangle extends Shape{//!!!!!!!!!! where the error shows
public Rectangle(int x, int y, int width, int height, Color fillColor, Color outlineColor) {
super(x, y, width, height, fillColor, outlineColor);
}
public void drawRectangle(Graphics g){//draws the retangle
g.setColor(fillColor);
g.fillRect(x, y, width, height);
g.setColor(outlineColor);
g.drawRect(x, y, width, height);
}
}
class Ellipse extends Shape{
public Ellipse(int x, int y, int width, int height, Color fillColor, Color outlineColor) {
super(x, y, width, height, fillColor, outlineColor);
}
public void drawEllipse(Graphics g){//draws the ellipse
g.setColor(fillColor);
g.fillOval(x, y, width, height);
g.setColor(outlineColor);
g.drawOval(x, y, width, height);
}
}
}
Thanks for reading and helping!
Both classes Rectangle and Ellipse need to override both of the abstract methods.
To work around this, you have 3 options:
Add the two methods
Make each class that extends Shape abstract
Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:
abstract class Shape {
// ...
void draw(Graphics g);
}
And
class Rectangle extends Shape {
void draw(Graphics g) {
// ...
}
}
Finally
class Ellipse extends Shape {
void draw(Graphics g) {
// ...
}
}
And you can switch in between them, like so:
Shape shape = new Ellipse();
shape.draw(/* ... */);
shape = new Rectangle();
shape.draw(/* ... */);
Again, just an example.
If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.
In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

How to draw part of a large BufferedImage?

I have a 10000x10000 BufferedImage and I'm looking to draw only part of it to a Canvas, is there a way to do this using args such as:
x, y, width, height ?
So for example, drawImage(img, x, y, width, height) would draw a rectangle from the image starting at (x, y) and having (width, height) as the dimensions?
EDIT:
I'm going to re- word this question:
I have a 10000x10000 image and I only want to display a portion of it on the screen, the problem with just offsetting it by x and y is that this still causes lag as the entire image is being rendered, just most of it off canvas. How can I basically make it so that the entire image is rendered but I can scroll around it without causing the canvas to lag?
I have a 10000x10000 BufferedImage and I'm looking to draw only part
of it to a Canvas, is there a way to do this using args such as:
Don't use canvas for custom painting in java. use JComponent or JPanel instead. It has a nice function paintComponent(Graphics g), override it and paint your image inside with g.drawImage(x, y, width, height, observer);
Swing graphics has Graphics.clipRect(int x, int y, int width, int height) to bound the area rectangle to which you wish to draw prior to drawing the image.
Edit (In response to your edited question):
First approach is to use BufferedImage..getSubimage(x, y, width, height) to get a sub image with specified rectangle region. It is faster.
BufferedImage img = ImageIO.read(new File("file"));
img = img.getSubimage(50, 50, 500, 500); // 500 x 500
This function will give you a new image cropped with the rectangle(x, y, width, height) of your original image you specified. Use the returned image to draw on your component.
Tutorial resource: Clipping the Drawing Region
Demo: Demonstrating clipping Image with Animation:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.logging.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.Timer;
class MyCanvas extends JPanel implements ActionListener
{
public BufferedImage buffImg;
public Rectangle rectangle;
Random random;
long lastTimeChanged;
int dirX = 1, dirY = 1;
volatile static boolean imageLoading = true;
public MyCanvas() {
random = new Random();
rectangle = new Rectangle(50, 50, 250, 250);
lastTimeChanged = System.currentTimeMillis();
setBackground(Color.WHITE);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(imageLoading)
{
showWaitForLoading(g);
return;
}
g.clipRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
g.drawImage(buffImg, 0, 0, getWidth(), getHeight(), this);
}
public void showWaitForLoading(Graphics g)
{
Graphics2D g2d = (Graphics2D)g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.DARK_GRAY);
g2d.fillRoundRect(getWidth()/2-100, getHeight()/2-15, 200, 30, 30, 30);
g2d.setColor(Color.WHITE);
g2d.drawString("Loading image...", getWidth()/2 - 45, getHeight()/2 + 3 );
g2d.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
long endTime = System.currentTimeMillis();
if(endTime - lastTimeChanged > 500)
{
dirX = random.nextInt(2) == 0 ? -1 : 1;
dirY = random.nextInt(2) == 0 ? -1 : 1;
lastTimeChanged = endTime;
}
if(rectangle.x < 0)dirX = 1;
else if(rectangle.x + rectangle.width > getWidth())dirX = -1;
if(rectangle.y < 0)dirY = 1;
else if(rectangle.y + rectangle.height > getHeight())dirY = -1;
rectangle.x = rectangle.x + dirX * 10;
rectangle.y = rectangle.y + dirY * 10;;
repaint();
}
}
public class CustomPainting {
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final MyCanvas canvas = new MyCanvas();
JFrame frame = new JFrame();
frame.setSize(new Dimension(500, 500));
frame.add(canvas);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer timer = new Timer(200, canvas);
timer.start();
new Thread()
{
public void run()
{
try {
canvas.buffImg = ImageIO.read(new URL("http://images6.fanpop.com/image/photos/33400000/Cute-Panda-beautiful-pictures-33434826-500-500.jpg"));
MyCanvas.imageLoading = false;
} catch (IOException ex) {
Logger.getLogger(CustomPainting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
});
}
}
You can scale or draw a part of an image using Graphics.drawImage as mentioned another answer and according to Java documentation, ImageObserver argument is not needed for BufferedImage so you can just pass null.
http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html
However, my choice would be the clipping drawing region of image instead.
Here is an example you can try:
Graphics2D g = BufferedImage.getGraphics;
g.setClip(x, y, width, height);
g.drawImage(sx, sy, x - sx, y - sy, null );
Yes there is: drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)

Categories