Java Graphics trying to draw rectangle - java

My goal is to make a class that contains rectangle and then use it and change it in other classes.
I tried to write this code and make an object Rect rect = new Rect(); but when i start the program the rectangle doesn't show up.
I also tried to add it with window.add(rect); but had same problem i'm sure im doing something wrong but i don't really know what.
One more thing that i tried was calling method from other class Rect.drawRect(g); but then it asks for "Argument" and if i add Argument g like i had in method drawRect it says "g cannot be resolved to a variable"
I hope someone can explain and tell me what did i do wrong, also would be great to know how to make rectangle or a circle and later use it in other classes and maybe change its color and size, I only found how to do it in one class.
import javax.swing.JFrame;
public class Main extends Rect{
public static void main(String[] args ) {
JFrame window = new JFrame("test");
window.setSize(1000, 800);
window.setVisible(true);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Rect rect = new Rect();
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Rect extends JPanel{
public void drawRect(Graphics g){
g.setColor(Color.RED);
g.fillRect(100, 100, 200, 200);
}
}

The most important thing is that you need to write some code to do the painting. This is done by overriding the paintComponent method inside your Rect class a bit like this:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(100, 100, 200, 200);
}
Your second issue is that you want to be able to change the colour and size of your rectangle from other classes. For a simple example, this can easily be done by adding some static values inside your Rect class:
public static Color myColor = Color.RED;
public static int myX = 100;
public static int myY = 100;
public static int myWidth = 200;
public static int myHeight = 200;
Now update your paint method to use the static values:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(myColor);
g.fillRect(myX, myY, myWidth, myHeight);
}
Now, whenever or wherever you use the Rect panel it will now show the rectangle according to the static values.
For example, below is a simple and working program, note how it uses the following:
//create Rect
Rect rect = new Rect();
//set the size of the new panel
rect.setPreferredSize(new Dimension(800, 600));
//add the rect to your JFrame
window.add(rect);
//now you can change the color for all Rect instances
//Note how I use Rect instead of rect, however, both will work.
Rect.myColor = Color.BLUE;
//And dont forget to repaint it if you want to see the changes immediatly
rect.repaint();
Full example, main class:
import javax.swing.JFrame;
import java.awt.Color;
public class Main{
//Note how we don't need to extend the Rect class (It just adds confusion)
public static void main(String[] args ) {
JFrame window = new JFrame("test");
window.setSize(1000, 800);
window.setVisible(true);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create Rect
Rect rect = new Rect();
//set the size of the new panel
rect.setPreferredSize(new Dimension(800, 600));
//add the rect to your JFrame
window.add(rect);
//now you can change the color for all Rect instances
//Note how I use Rect instead of rect, however both will work.
Rect.myColor = Color.BLUE;
//And dont forget to update it
rect.repaint();
}
}
And the Rect class:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Rect extends JPanel{
public static Color myColor = Color.RED;
public static int myX = 10;
public static int myY = 10;
public static int myWidth = 200;
public static int myHeight = 200;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(myColor);
g.fillRect(myX, myY, myWidth, myHeight);
}
}
Note, if you don't want to call Rect.repaint() every time you make a color/size change then just make a new method that changes each value and include repaint(), for example:
public void changeWidth(int width){
myWidth = width;
repaint();
}

UDP: You need override void paintComponent(Graphics g) instead void drawRect(Graphics g)and call super.paintComponent(g) inside method. Then you can use window.add(rect);.
Thanks #FredK for correction

Related

How to display a graphic from another class

I am trying to display a graphic from a separate class on a JPanel of my main class.
The main class is mytest and the separate class is Ball. Ball has a paint component method and simply draws a colored circle. In mytest, I instantiate a ball and add it to a JPanel (dp): dp.add(ball). Very simple, but all I get is the white panel background and no ball is drawn.
Here is the mytest code:
package myStuff;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class mytest {
private JFrame frame=new JFrame();
private JPanel dp = new JPanel();
public static void main(String[] args) {
mytest gui = new mytest();
gui.go();
}
public void go() {
frame.setTitle("Test");
frame.setSize(1000,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel dp=new JPanel();
dp.setBackground(Color.WHITE);
Ball ball = new Ball(dp.getWidth(),dp.getHeight());
dp.add(ball);
frame.add(dp);
frame.setVisible(true);
}
}
and here is the class Ball code:
package myStuff;
import java.awt.*;
import javax.swing.*;
public class Ball extends JComponent{
private int Width;
private int Height;
public Ball (int width, int height ) {
Width=width;
Height=height;
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.setColor(Color.RED);
g2d.fillOval(Width/2,Height/2,40,40);
System.out.println("Doing graphics....");
}
}
An red ball should show up on the dp panel. All I get is the panel background and no ball. I know it is trying since the "Doing graphics" prints out twice.
Here is a working example.
import java.awt.*;
import javax.swing.*;
public class Mytest {
private JFrame frame = new JFrame();
public static void main(String[] args) {
Mytest gui = new Mytest();
SwingUtilities.invokeLater(() -> gui.go());
}
public void go() {
frame.setTitle("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel dp = new JPanel();
dp.setPreferredSize(new Dimension(500, 500));
dp.setBackground(Color.WHITE);
Ball ball = new Ball(150, 150);
dp.add(ball);
frame.add(dp);
frame.pack(); // invokes layout and sizes components
frame.setLocationRelativeTo(null); // centers on screen
frame.setVisible(true);
}
}
class Ball extends JComponent {
private int width;
private int height;
// A ball should probably only have a "diameter"
public Ball(int width, int height) {
this.width = width;
this.height = height;
setPreferredSize(new Dimension(width, height));
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.setColor(Color.RED);
// smooths out the graphics
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(0, 0, width, height);
System.out.println("Doing graphics....");
}
}
The two biggest suggestions are to:
Ensure when you change a Swing component you do so on the Event Dispatch Thread.
And use the anti aliasing to make your drawing look smoother (note this is optional and it can add extra processing overhead.)
The reason no red ball was drawn (or only 1/4 of one) was because you changed the location of where to draw it within the Component window. You tried to draw it at width/2 and height/2 which was the center of the Component. It should have been at 0,0 for normal rendering.
Also read about painting in the The Java Tutorials 1
You are setting the size of the frame, but the panel has zero size. You should set the preferred size of the panel, not the size of the frame. Then get the preferred size of the panel to pass to the Ball constructor, and pack the frame before making it visible.
Set the panel size before the line,
Ball ball = new Ball(dp.getWidth(),dp.getHeight());
Then add this code
setPreferredSize(new Dimension(Width, Height));
at the end of the "Ball" Constructor.
See this stack question for more details.

Beginner Graphics2D Java : repaint()

I am trying to change the color of my Red Cirlces in the Action handler then repaint() and I couldn't figure out why it is not working.
Imports here
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;
My class here:
public class CirclePanel extends JPanel implements ActionListener {
static JFrame f;
static JButton run1, run2, reset, quit;
static JPanel btnPanel;
static CirclePanel circlePanel;
static final int NUM = 5;
static Color c;
static Graphics2D g2;
static Graphics2D g3;
public CirclePanel(){
f = new JFrame();
f.setTitle("Dining Philosophers");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
f.setSize(1000,1000);
f.setLayout(new BorderLayout());
btnPanel = new JPanel();
btnPanel.setPreferredSize(new Dimension(250, 100));
btnPanel.add(run1 = new JButton("Run 1"));
btnPanel.add(run2 = new JButton("Run 2"));
btnPanel.add(reset = new JButton("Reset"));
btnPanel.add(quit = new JButton("Quit"));
run1.setPreferredSize(new Dimension(180, 50));
run2.setPreferredSize(new Dimension(180, 50));
reset.setPreferredSize(new Dimension(180, 50));
quit.setPreferredSize(new Dimension(180, 50));
run1.addActionListener(this);
f.add(btnPanel, BorderLayout.SOUTH);
f.add(this, BorderLayout.CENTER);
f.setVisible(true);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g2 = (Graphics2D) g;
g3 = (Graphics2D) g;
g2.translate(470, 400);
c = Color.red;
for(int i = 0; i < NUM; ++i){
c = Color.red;
g2.setColor( c);
g2.fillOval(150, 0, 100, 100);
g3.setColor(Color.BLACK);
g3.fillOval(90, 0, 30, 30);
g2.rotate(2*Math.PI/ NUM);
}
}
As you can see when I push the button Run1 it does go into the action handler and executes the repaint method, but nothing changes.
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == run1) {
System.out.println("Entered Action Handler");
g2.setColor(Color.green);
repaint();
}
}
Here is my main:
public static void main(String[] args) {
new CirclePanel();
}
}
The Graphics objects are not long-lived, not stable, and you shouldn't be using them in this way. Instead of setting g2 or any other Graphics field, create a Color field, say called Color circleColor = ...;, and change this. Within the protected void paintComponent(Graphics g) method, call g.setColor(circleColor);, and this should work.
Delete these fields as they are dangerous:
// static Graphics2D g2;
// static Graphics2D g3;
Also your code shows gross over-use of the static modifier, and I would venture to recommend that none of your fields should be static except for the constant:
static final int NUM
The repaint() method will ultimately invoke the paintComponent() method of your panel. Swing will pass in the Graphics object to be used in the painting.
In the painting code you always hardcode the Color to be RED. Don't do this.
Instead you need to define a variable in your panel class. Lets say "circleColor" (ie, "circleColor" replaces your "c" variable because variable names should be more descriptive, not just a single character).
Then in your ActionListener code you do:
//g2.setColor(Color.green);
circleColor = Color.green;
This in the paintCompnent() method you do:
//c = Color.red;
g.setColor(circleColor);
Also:
static Graphics2D g2;
static Graphics2D g3;
There is no need for any of those variable. You always use the Graphics object that is passed to the painting method.
Read the section from the Swing tutorial on Custom Painting for more information and for better examples on how to structure your code. For example you should NOT be using static variables.
What's happening is:
You are changing g2 color in the action listener.
Then you call repaint(); so paintComponent(Graphics g) is called.
In the paintComponent(Graphics g) method you are setting the g2 color to c so you are overriding the changes you made in the action listener.
That's why the circles are not changing color in the end.
You should set c = Color.RED; in the constructor instead of in the for loop, then you can just change the value of c in the action listener c = Color.GREEN;.
Also you're setting c = Color.RED; both in the for loop and before it which is useless.
EDIT:
As suggested by #camickr your code is also badly structured.
You don't need g2 and g3 because you can draw multiple shapes
using the same Graphics g object.
In your case you don't even need to call g outside of the paintComponent method because you can simply change the Color c variable as i said above.
You also don't need all of those static variables. Just make them private and if you need to access them from outside the class you should create some getters and setters.
Here you'll find more on static variables and some examples.
Here you'll find more about getters, setters and encapsulation.
Example of how you could change your code:
public class CirclePanel extends JPanel implements ActionListener {
private JFrame f;
private JButton run1, run2, reset, quit;
private JPanel btnPanel;
private int NUM;
private Color c;
public CirclePanel(){
color1 = Color.red;
color2 = Color.black;
NUM = 5;
// Setup JFrame and stuff as you were doing.
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.translate(470, 400);
for(int i = 0; i < NUM; i++){
g.setColor(color1);
g.fillOval(150, 0, 100, 100);
g.setColor(color2);
g.fillOval(90, 0, 30, 30);
g.rotate(2*Math.PI/ NUM);
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == run1) {
System.out.println("Entered Action Handler");
color1 = Color.green;
repaint();
}
}
// GETTERS and SETTERS if needed
}

I am having trouble implementing a mouse action listener in my GUI

I have created a simple GUI which contains a circle filled with a random colour. I am now trying to make it so that the colour of the circle changes when the mouse is clicked to another random colour. I have created a paint component method which initially paints the circle and a repaint method which will change the colour of the circle. I have then called upon this method in my mouse listener event class. The problem is that I am getting an error when I add my action listener to my pane. The error is as follows:
No enclosing instance of type taskTwo is accessible. Must qualify the allocation with an enclosing instance of type taskTwo (e.g. x.new A() where x is an instance of taskTwo).
I understand why I am getting this error but do not know how to fix it, I have tried moving the action listener class into a class of its own but then I cannot call upon my repaint method within the listener. Here is my code:
package weekThree;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class taskTwo extends JComponent {
static Random rand = new Random();
JPanel pane = new JPanel();
public static void main(String[] args) {
JFrame window = new JFrame("Task Two");
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout());
taskTwo t2 = new taskTwo();
window.setContentPane(t2);
t2.paint(null);
pane.addMouseListener(new MouseClick());
window.setBackground(Color.WHITE);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300,300);
window.setVisible(true);
}
public void paintComponent(Graphics g) {
float red = rand.nextFloat();
float green = rand.nextFloat();
float blue = rand.nextFloat();
Color randomColor = new Color(red, green, blue);
g.drawOval(300, 300, 200, 200);
g.setColor(randomColor);
g.fillOval(300, 300, 200, 200);
}
public void repaint(Graphics g) {
float red = rand.nextFloat();
float green = rand.nextFloat();
float blue = rand.nextFloat();
Color randomColor = new Color(red, green, blue);
g.drawOval(300, 300, 200, 200);
g.setColor(randomColor);
g.fillOval(300, 300, 200, 200);
}
class MouseClick implements MouseListener {
public void mouseClicked(MouseEvent e) {
repaint();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
}
Thanks, also an extension of this would be to make it so that the colour changes only when I click within the circle, any tips on how to do this would be appreciated.
I would add the MouseListener in the instance world, not in the static world, and that error will go away. I also recommend that you get rid of that strange repaint method as it looks too similar to Swing JComponent's own repaint method. You never call it and so it does you no good.
Also randomize your colors in the mouse listener, not in the paintComponent method (which should be protected). I also prefer to extend JPanel and not JComponent.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyTaskToo extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private Color circleColor = Color.RED;
private int circX = 10;
private int circY = circX;
private int circW = PREF_W - 2 * circX;
private int circH = PREF_H - 2 * circY;
public MyTaskToo() {
// add in constructor -- in the "instance realm" not in the static realm
addMouseListener(new MyMouse());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// to smooth out graphics
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(circleColor);
g2.fillOval(circX, circY, circW, circH);
g2.setColor(Color.BLACK);
g2.drawOval(circX, circY, circW, circH);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouse extends MouseAdapter {
Random rand = new Random();
#Override
public void mousePressed(MouseEvent e) {
float red = rand.nextFloat();
float green = rand.nextFloat();
float blue = rand.nextFloat();
circleColor = new Color(red, green, blue);
repaint();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("MyTaskToo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyTaskToo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
The problem is that your MouseClick class is not static but you are trying to instantiate it from a static context (the main method).
You have multiple solutions:
turn your class into static class MouseClick
create and add the MouseListener in the taskTwo() constructor (since MouseClick is an internal class of taskTwo)
create a specific taskTwo to provide the requested instance, eg new taskTwo.MouseClick(), but don't do it, since it makes no sense in this situation.
The problem is that you are accessing the MouseClick class from the public static void main function. Since, MouseClick is inside taskTwo he canĀ“t access it, you first need to create an instance of taskTwo.
Quick fix : Add constructor and erase that lane from the main function.
public taskTwo (){
this.addMouseListener(new MouseClick());
}

Transitioning to an abstract class

I am desperately trying to implement some things which I don't think I fully understand. I am attempting to set it up so the commented out actions can be taken (I will need to change syntax but I want to make sure I am on the right track first).
Am I going about this the right way? Where will my drawing actions go if not in the draw method? I get lots of errors when I move it there. Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics2D;
import java.awt.Graphics;
public class Test extends JPanel{
abstract class graphic {
public Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private int[] location = new int[] {screenSize.width/2,screenSize.height/2};
}
public class gladiator extends graphic {
void draw() {
//g2d.setColor(Color.green);
//g2d.fillArc(location[0], location[1], 100, 100, 45, 90);
//g2d.setColor(Color.black);
//g2d.fillArc((location[0]+50-10),(location[1]+50-10), 20, 20, 0, 360);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// setLocation((location[0]+1),location[1]);
repaint();
System.out.println("repainting");
}
}).start();
}
public void setLocation(int x, int y){
//this.location[0] = x;
//this.location[1] = y;
}
public static void main(String[] args){
JFrame jf=new JFrame();
jf.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
jf.setPreferredSize(Toolkit.getDefaultToolkit().getScreenSize());
jf.add(new Test());
jf.pack();
jf.setVisible(true);
}
}
My original code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JPanel{
private int[] location = new int[2];
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillArc(location[0], location[1], 100, 100, 45, 90);
g.setColor(Color.black);
g.fillArc((location[0]+50-10),(location[1]+50-10), 20, 20, 0, 360);
new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setLocation((location[0]+50),50);
repaint();
System.out.println("repainting");
}
}).start();
}
public void setLocation(int x, int y){
this.location[0] = x;
this.location[1] = y;
}
public static void main(String[] args){
JFrame jf=new JFrame();
jf.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
jf.setPreferredSize(new Dimension(300,500));
jf.setLocation(100,100);
jf.add(new Test());
jf.pack();
jf.setVisible(true);
}
}
Edit: Should have included this bit, first commenter was right.
The error is cannot find symbol, referring to g2d or g, whichever. I take it to mean that drawing can only happen inside of paint components and that I will have to find a way to include all the instructions for drawing there. I want to make sure I'm just doing something fundamentally wrong, though as this is my first brush with both abstract classes and 2d drawing in java. Also, I know the location[0] etc will not work as is. Lets ignore that.
The bottom code is what I am trying to accomplish (at least at first), but I am trying to use something similar to the top code to create multiple instances of it which can operate independently.
Move the timer out of paintcomponent.
You have declared an abstract class that has a draw method that needs a Graphics2D object to be able to draw, it has no access to it. It also makes little sense to declare a class just to hold two values (screensize and location) if that class also does stuff like drawing.
To fix the issues with 2, you can either let your gladiator extend JComponent, override its paintcomponent and place your draw() code in there and add gladiator to the panel as a component.
You can alternatively do active rendering, which means that you get the Graphic2D object of your canvas (the panel in this case) and take control of the rendering yourself instead of relying on swing.
Since you are working with swing I will give you a working example of what you probably intend to do. If you have more specific questions please do leave a comment.
public class Test extends JPanel {
public static abstract class graphic extends JComponent {
public Dimension dim = new Dimension(500, 500);
private int[] loc = new int[] { 250, 250 };
#Override
#Transient
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public int[] getLoc() {
return loc;
}
public Dimension getDim() {
return dim;
}
}
public static class gladiator extends graphic {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.green);
g2d.fillArc(getLoc()[0], getLoc()[1], 100, 100, 45, 90);
g2d.setColor(Color.black);
g2d.fillArc((getLoc()[0] + 50 - 10), (getLoc()[1] + 50 - 10), 20,
20, 0, 360);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Test canvas = new Test();
gladiator gladiator = new gladiator();
canvas.add(gladiator);
frame.getContentPane().add(canvas);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
This renders

Java: "non-static method drawRect" error

I am really new in Java. Thought I had figure some stuff out by now, but I have a problem that proves otherwise!
Ok! Here it is. I have this code (Edited - Not original):
import java.util.*;
import java.awt.*;
public class MyClass extends HisClass
{
public void drawRectangle(int width, int height)
{
int x1 = this.getXPos();
int y1 = this.getYPos();
java.awt.Graphics.drawRect(x1, y1, width, height);
}
public static void main(String[] args)
{
AnotherClass theOther = new AnotherClass();
MyClass mine = new MyClass(theOther);
mine.move();
}
}
The error it gives me is this:
MyClass.java:66: error: non-static method drawRect(int,int,int,int) cannot be referenced from a static context
Can you please provide me with a solution?
It would be very appreciated. Thanks.
java.awt.Graphics.drawRect(x1, y1, width, height);
drawRect method is not static.. You should get an instance of your Graphics class somehow to use it: -
(graphicsInstance).drawRect(x1, y1, width, height);
Since Graphics class is abstract, so you need to find appropriate way to instantiate your Graphics object, to get graphicsInstance
You can use GraphicsContext to draw whatever you want to.. GraphicsContext is an object belonging to Graphics class which you can use to drawRect()
See these post. Might be useful: -
How do I initialize a Graphics object in Java?
what is a graphics context (In Java)?
Here is some example code that draws a Rectangle using drawRect() onto the JPanel by overriding its paintComponent(Graphics g) method and adding it to the JFrame:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawRect extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//draw our rect
g.setColor(Color.blue);
g.drawRect(10, 10, 100, 50);
}
//or else we wont see the JPanel
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("DrawRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawRect());
frame.pack();
frame.setVisible(true);
}
}

Categories