What I want to achieve is something like this:
public void paint(Graphics g) {
Graphics2D ga = (Graphics2D) g;
MyShape c = new MyShape();
ga.draw(c);
}
I want that MyShape class to contain the info required to draw a circle with a number inside it.
So, I guess I need to create some kind of container/component, and drew what I need (the circle and the number) inside it, and then pass it further to the method I've pasted above.
The problem is I don't know what class to extend ... and the rest of the story.
A Shape is just that: a shape. A circle is a shape. A rectangle is a shape. But a circle with a number inside it is not a shape. My guess is that you in fact want something like this:
public class CircleWithNumberInside extends JComponent {
#Override
protected void paintComponent(Graphics g) {
// TODO draw a circle, and draw a number inside it.
}
}
You can certainly implement the Shape interface yourself, but there's no need when you can use an existing subclass, such as Ellipse2D. Just construct it with the same value for width and height. There's an example here that shows how to center an arbitrary glyph in an Ellipse2D.Double.
You have to extend the class Shape, which inside you would have to override the paintComponent so that the Graphics2D object knows what to draw.
Related
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();
I'm trying to make a map editor that supports rectangles in different angles (so it draws rectangles using polygons). I want to catch a polygon by their location on the frame without using mathematical calculations.
Is there a command supports such thing?
I tried to catch polygons by their visual representations:
public void mousePressed(MouseEvent e){
Component component = getComponentAt(e.getX(), e.getY());
if(component instanceof wall){
but it doesn't work.
(If i was simply drawing rectangles i would use JPanel and use setbounds command to draw a rectangle, but i dont think i can make polygon-shaped JPanels)
You first need to create a List containing all the Polygons you want to paint:
Shape circle = new Ellipse2D.Double(0, 0, 30, 30);
List<Shape> shapes = new ArrayList<Shape>();
shapes.add( circle );
Then in your paintComponent() method you iterate through all the shapes in the List:
Graphics2D g2d = (Graphics2D)g.create();
for (Shape shape : shapes)
{
g2d.draw( shape );
}
g2d.dispose();
Then in the MouseListener you iterate through the List to see which Shape was clicked:
public void mousePressed(MouseEvent e)
{
for (Shape shape : shapes)
{
if (shape.contains(e.getPoint())
// do something
}
}
If i was simply drawing rectangles i would use JPanel and use setbounds command to draw a rectangle, but i dont think i can make polygon-shaped JPanels
For an alternative approach that does use a component check out Playing With Shapes. The classes there allow you to create a ShapeComponent by using any Shape.
You wouldn't use individual JPanels to draw each Polygon. You would use a single class that extends JPanel, then overrides the paintComponent() method to draw the Polygons. More info here.
Once you've drawn your Polygons to the JPanel, you can use the Polygon.contains() method to test whether the mouse was inside a JPanel. More info on that in the API.
Is it possible to re-paint an applet without losing its previous contents? I was just trying to make a program which allows users to draw lines, Rectangle etc. using mouse. I have used the repaint method but it does not keep the previously drawn lines/rectangles etc.
Here is the snippet:
public void mousePressed(MouseEvent e){x1=e.getX();y1=e.getY();}
public void mouseDragged(MouseEvent e)
{
x2=e.getX();
y2=e.getY();
repaint();
showStatus("Start Point: "+x1+", "+y1+" End Point: "+x2+", "+y2);
}
public void paint(Graphics g)
{
//g.drawLine(x1,y1,x2,y2);
g.drawRect(x1, y1, x2-x1, y2-y1);
}
Two possible solutions:
Draw to a BufferedImage using the Graphics object obtained from it via getGraphics(), and then draw the BufferedImage in your JPanel's paintComponent(Graphics g) method. Or
Create an ArrayList<Point> place your mouse points into the List, and then in the JPanel's paintComponent(Graphics g) method, iterate through the List with a for loop, drawing all the points, or sometimes better -- lines that connect the contiguous points.
Other important suggestions:
Be sure that you're using the Swing library (JApplet, JPanel), not AWT (Applet, Panel, Canvas).
You're better off avoiding applets if at all possible.
Don't draw in a paint method but rather a JPanel's paintComponent(Graphics g) method.
Don't forget to call the super's method first thing in your paintComponent(Graphics g) method override.
You need to keep track of everything that has been painted and then repaint everything again.
See Custom Painting Approaches for the two common ways to do this:
Use a ArrayList to keep track of objects painted
Use a BufferedImage
here is an exemple of code you can use :
ArrayList<Point> points = new ArrayList<Point>();
private void draw(Graphics g){
for (Point p: this.points){
g.fillOval(1, 2, 2, 2);
}
}
//after defining this function you add this to your paint function :
draw(g)
g.drawRect(x1, y1, x2-x1, y2-y1);
points.add(new Point(x1, y1, x2-x1, y2-y1))
// PS : point is a class I created to refer to a point, but you can use whatever
I create an object called "City"
City city = new City (name, rec, g);
The object's constructor looks like this:
public City (String name, Rectangle r, Graphics g){
this.name = name;
this.r = r;
this.g = g;
}
By creating this object i also draw an oval on an uploaded picture, and set it's colour to BLUE. Here's how I draw the object:
g = (Graphics2D) window.lblNewLabel.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(mouseX, mouseY, 15, 15);
I would like to be able to change that colour later, after clicking on the oval itself.
I try to call this function, but it doesn't work:
public void isClicked(){
clicked = true;
this.color = Color.RED;
this.g.setColor(Color.PINK);
}
How to change a colour of an existing object?
Using getGraphics() on a component causes a transient graphics Object to be used on the component itself. Any subsequent calls to repaint will erase the painting done using that object.
Change the color by overriding the paintComponent method. Save the Color variable as a class member variable and use it to determine the oval color in the method.
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(savedColor);
g.fillOval(mouseX, mouseY, 15, 15);
}
Don't use getGraphics() to do painting, that painting is only temporary and will be lost the next time Swing determines a components needs to be repainted.
Check out Playing With Shapes for other ideas on doing painting.
You could use a ShapeIcon which allows you to change the color of the icon. The icon could be painted in the paintComponent() method of your label.
Or you could use ShapeComponent which uses a ShapeIcon. Then you can just add the component to the label like any other component.
I would like to be able to change that colour later, after clicking on the oval itself
The ShapeIcon would be added to a JLabel. Then you can just add a MouseListener to the label of the ShapeComponent to change the color of the icon.
When you have drawn objects with a Graphics object, they are then rendered on the screen. You can't change the color of them directly, instead you will have to repaint your graphics any time when you want to change them. If you want to keep track of the colors for the objects, you will have to store the data in some kind of variable and use it when drawing.
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.