Create Methods to Draw Rectangle and Circle in JFrame? - java

I was assigned this problem without any teaching on how to do it and I can't figure it out on my own. I've started, but I can't figure out what methods to add.
Below is the main method of a program which paints a circle and a square at the given coordinates. Your job is to write the rest of the code, BUT THE MAIN METHOD CANNOT BE ALTERED!!! You can add methods to the main driver class but you CANNOT add anything to the main method below.
public static void main (String[] args){
JFrame picture = new JFrame("Circle and Square");
picture.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
picture.getContentPane().add(new Drawing(200, 50,100, 150));
picture.pack();
picture.setVisible(true);
}
The first two numbers are the height and width where the rectange should start and the second two numbers are the height and width where the circle should start.
//The following is my failure attempt, so at least you know I tried
to figure something out.
import javax.swing.*;
import java.awt.*;
public class Drawing extends JFrame
{
int a, b, c, d;
public Drawing(int x, int y, int z, int yeah)
{
setSize(400, 400);
a = x;
b = y;
c = z;
d = yeah;
}
public void paint(Graphics g)
{
super.paint(g);
g.drawRect(a, b, c, d);
g.drawOval(c, d, a, b);
}
public getContentPane()
{
}
//Can't change following class:
public static void main (String[] args)
{
JFrame picture = new JFrame("Circle and Square");
picture.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
picture.getContentPane().add(new Drawing(200, 50, 100, 150));
picture.pack();
picture.setVisible(true);
}
}
I know I have to create something called a panel, but I don't even really understand how to do that. I'm sure I could reverse engineer any code anyone here shows me on how to solve my assignment. Thanks.

getContentPane is a method of JFrame, you won't need to implement it.
Drawing doesn't need to extend from JFrame, it should extend from JPanel.
Don't call setSize it will do nothing. You need to override getPreferredSize and return the preferred size you want to use.
Don't override paint, you should be using paintComponent, points for calling super.paint though. But when you move the custom painting to paintComponent, call super.paintComponent instead.
Take a look at:
- Creating a GUI With JFC/Swing
- Performing Custom Painting
- 2D Graphics
Make notes in your documentation or code that the main method is wrong and should taking into consideration Initial Threads

Related

How to add points on the x/y grid with button

I'm new to Java Swing and I'm writting a program, into which user types few X's and Y's and then the program shows on x/y grid those points. I drew the grid with Graphics2D, but now the problem is with drawing those points. I'm adding every X and Y to separate ArrayList and then after clicking the button 'Draw' it should draw all of them, but I don't really know how. I've searched few topics and tutorials, but still can't get into it.
Here is the code of my DrawPoints class
import javax.swing.*;
import java.awt.*;
public class DrawPoints extends JPanel {
private int x;
private int y;
public DrawPoints(int x, int y) {
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(x*20, y*20, 5, 5); //20 is the difference between every point on my grid
}
}
And here is part of my actionListener function
if (event.getActionCommand().equals("Draw")) { //Button is called 'Draw'
for (int i = 0; i < dataX.size(); i++) { //dataX is an arrayList with all X's
DrawPoints drawPoints = new DrawPoints(dataX.get(i), dataY.get(i)); //dataY is an arrayList with all Y's
points.add(drawPoints); //points is a JPanel added in the main frame
}
}
I'm adding every X and Y to separate ArrayList and then after clicking the button 'Draw' it should draw all of them,
That approach is wrong.
All the data needed to paint the points should be part of the DrawPoints class:
The `ArrayList should be an instance variable of the class.
You would create a method like addPoint(...) in the DrawPoints class. This method would simply take the point and add it to the ArrayList and then invoke repaint() to make sure the point is painted on the panel.
The paintComponent(…) method would then be changed to iterate through all the pointes in the ArrayList and then paint each point.
I'm writting a program, into which user types few X's and Y's
So as the user type the x/y points you would invoke the addPoint(…) method of your DrawPoints class.
You will also need to override the getPreferredSize() method of your DrawPaoints class to give your panel a size so a layout manager can be used.
Check out the Draw On Component example found in Custom Painting Approaches for a working example that uses this approach. The code presented there is more complicated then you will need because it allows the user to use the mouse to create the rectangles to be painted.

Java, create and edit a Graphics Object for Panel?

I have the following task for my school in Java:
Create a GUI window with your own graphic. This graphic should be created in a separate JPanel class and drawn using the draw and fill methods of the java.awt.Graphics class (e.g. a house with a garden, a car, ...). The graphic should contain at least 5 different types of graphics (rectangle, oval, ...), at least one polygon (draw or fillPolygon (polygon p) method) and an arc (draw or fillArc method (int x, int y, int width, int height, int startAngle, int arcAngle)). The graphic should also contain at least 10 drawing elements and consist of at least 4 different colors.
But I don´t know how to use the class Graphics, so I don´t know how to create a Grahpics object and edit it. Does anyone know how to solve this? Thank you
You can use graphics with a JPanel;
class exampleclass extends JPanel {
exampleClass() {
...
}
#Override
public void paintComponent(Graphics g) {
...your code here...
}
}
For more information, look at; https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html
You can call paint method with, repaint();

Trying to draw a circle in Java using variable in parameters

I am having trouble doing a rather simple task of taking in the diameter of a circle and then drawing it. Here is my code so far.
import javax.swing.*;
import java.awt.Graphics;
public class Shapes extends JFrame
{
double diameter;
public Shapes()
{
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void getDiameter()
{
String input = JOptionPane.showInputDialog("What is the diameter of the circle?");
diameter = Double.parseDouble(input);
Shapes gui = new Shapes();
gui.setVisible(true);
}
public static void main(String[] args)
{
Shapes app = new Shapes();
app.getDiameter();
}
public void paint(Graphics canvas)
{
canvas.drawOval(50, 50, (int)diameter, (int)diameter);
}
}
When I run it, it brings up the Jframe window, but nothing is drawn, so I'm guessing the value of diameter is never passed to the paint method. Can someone help me get this to work? Thanks.
Your program is creating two Shapes objects actually, one of which has the diameter field set correctly but is not being displayed, and the other, which retains diameter's default value of 0 and which is displayed.
Suggestions:
Don't draw directly in a JFrame, but rather in the paintComponent(Graphics g) method override of a JPanel that is held by and displayed in the JFrame. There are many reasons for this, but for one, since the paint(...) method is not only responsible for painting a component but also its borders and children, this will prevent you from causing problems when paint(...) tries to paint a GUI's children and borders. It also will help your animations (which surely you will be doing soon) to be smooth given Swing component's default use of double buffering.
Always call the super.paintComponent(g) method within your JPanel's paintComponent override. This will allow Swing to erase images that need to be erased.
Don't create two Shapes objects, but rather only one. This will simplify things greatly and will allow you to set the diameter value of the one and only object of importance.
After changing the diameter field's value, call repaint on your GUI so that the displayed JPanel's paintComponent will be called.

How to create graphic instances in a java applet

We've just learned how to create our own class, and this particular assignment we had to work with graphics. We had to draw a crayon, and then create a test program where there are 5 crayons lined up next to one another (so we just change the color and x,y of each one). I know how to change the color and x,y coords, but my question is...
how do I 'print' each crayon? Yes, it's an applet and yes I know I need a .html file. But what exactly goes in the test program in order for the crayon to show up when I run the .html file? I've run non-applets before in test programs using System.out.println, but never any graphics. Would it just be System.out.println(Crayon); ?
Also, how do I get multiple crayons? I'm assuming it's Crayon crayons = new Crayon;, and then the next one might be 'Crayon crayons2 = new Crayons;`? I'm not sure.
The x,y coordinates need to be modified w/each crayon, but the UML for the assignment told me not to make them instance variables but instead to put it in 'public void paint (Graphics g, int x, int y)'. What I have so far for the test program (may or may not be correct):
import javax.swing.JApplet;
import java.awt.*;
public class BoxOfCrayons extends JApplet {
Crayon first = new Crayon (Color.red, 50, 250)
Start by having a read through 2D Graphics.
Basically, you will need to create some kind of list of Cryons. This can either be a Collection or array, depending on what you know. I would personally use a ArrayList as it's flexible and easy to use, but doesn't suffer from the same constraints as an array.
Next, create you're self a custom component (ie BoxOfCryons) which extends from JPanel. Override this classes paintComponent method. Within this method, run through the list of Cryons and paint each one, incrementing the x offset by the width of the last Cryon.
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int x = 0;
int y = 0;
for (Crayon crayon : cryons) {
crayon.paint(g2d, x, y);
x += crayon.getWidth();
}
g2d.dispose();
}
Create yourself a new class that extends from JApplet. In it's init method, set the applets layout manager to BorderLayout and add an instance of the BoxOfCryons class to it.

Moving a rectangle in Swing JPanel: original stays

I'm trying to make a tower of hanoi solver which simply solves the hanoi without any mouse events. The problem is when I move the rectangle the original remains, even after I repaint. I've searched the net and tried changing the code around but nonthing worked. I am using a JFrame with a JPanel inside of it if that changes anything.
I have my disk class here which is just a rectangle with colour.
class Disk extends Rectangle {
Color diskColour;
public Disk(int a, int b, int c, int d, Color colour) {
x = a;
y = b;
width = c;
height = d;
diskColour = colour;
}
public Color getColour() {
return diskColour;
}
public void paintSquare(Graphics g) {
repaint();
g.setColor(diskColour);
g.fillRect(x, y, width, height);
repaint();
}
}
Here is my code where I actually call the paintSquare method:
public void simpleMoveDisk(Disk[] disks, int n, Graphics g) {
disks[n].setLocation(30,25);
disks[n].paintSquare(g);
repaint();
}
The paintSquare method paints the disk, while the setLocation method changes its coordinates.
When this runs the rectangle occurs in the new location, however the old one still remains. Any help is appreciated, thanks in advance.
You are calling repaint() in several places and you shouldn't be.
Have your the top level class that is doing the painting, call the paintSquare method and any other method that is needed. Those methods should not be calling repaint().
Also your simple move disk is really strange in the fact that it passes an array of Disks, an index, and a graphics object. Instead make it just take in a Disk. Just pass it the one out of the array that is needed to be updated. Then let whatever class that calls simpleMoveDisk, separately make a call to repaint instead of trying to paint and update the model in the same method.

Categories

Resources