Drawing Line, Arc etc. Anywhere in the Code Java - java

I am kind of newbie in Java and in my program, I have to draw some lines, arcs etc. in a function different from paintComponent() in some cases in a class that extends JPanel.
I generally work with ActionScript for visual stuff and I can draw any geometric figure in any functions when I work with AS.
So, is there way to do the same thing in Java, and how?
Thank you!

Why not draw in paintComponent(...)? You state your new, and perhaps you might misunderstand how to do Swing graphics best, so knowing your requirements and the rationale behind them can help us help you.
You can draw on a BufferedImage at any time and in any code
Then that image can be displayed either in a JComponent's paintComponent(...) method
or in a JLabel's Icon via its setIcon(...) method.
Be sure to read the Graphics2D API which will have all the methods needed to do your drawings.
Be sure to read the Swing graphics tutorials because doing this type of work requires a paradigm shift.
Do not get your Graphics object by calling getGraphics() on a component such as a JPanel. Either get it via calling getGraphics() on a BufferedImage or from the paintComponent(Graphics g) parameter.

Related

Drawing a graph with Graphics2D using WindowBuilder

So I have a JPanel called displayPane and I want to make it a drawing area for a graph (I am making a graphing calculator). I am using WindowBuilder and this is the generated code for the JPanel:
JPanel displayPane = new JPanel();
displayPane.setBackground(Color.WHITE);
displayPane.setBounds(173, 33, 455, 432);
frame.getContentPane().add(displayPane);
After that I want to draw the axis of the graph but I have no idea how.
I've searched everywhere about it but everyone constructs a member class or something in the main class and adds the paintComponent(Graphics g) but that confuses me. What is that trying to accomplish ? Or just give me your way of doing it I don't really care as long as I understand it.
Any help is appreciated :)
Since this is homework, I'm going to give you general guidance without code, but first and foremost, please read this link on performing custom painting with Swing. Next you should put the Window Builder software to the side and work on creating your own code from scratch, at least do this til you're comfortable coding with Swing.
Next suggestions:
Have your DrawingPanel extend JPanel
Override paintComponent(Graphics g)
Call the super's method in your override, super.paintComponent(g) as this will refresh the graphics and erase old "dirty" pixels.
Play with drawing lines using g.drawLine(...)`
keep doing this and you'll get the idea of what you'll need.
Custom painting is achieved by overriding the paintComponent method of a JComponent based class (like JPanel).
This gives you access to the drawing surface onto which content is drawing and eventually shown on screen
See Custom painting and Painting in AWT and Swing for more details.
The Graphics API (or more specifically, the Graphics2D API) is a power abstract toolkit which provides with the means to actually paint stuff to the screen.
At the basic level, this provides you with the ability to specify colors and draw basic shapes and text. At a more complex level, you can define you own shapes, perform more complex coloring effects, including gradient fills and transformations of the basic context
See the 2D Graphics Trail for more details.

Java backbuffer and animations

I'm creating a simple 2D game in java. I've only done this in C++ with the Windows API so far. In java, I'm getting a Graphics object by extending JFrame and calling this.getContentPane().getGraphics(). With this object, I'm drawing everything to the screen, every frame. This raises a few questions:
Backbuffer: I'm not getting any flickering effects, while I'm not using a backbuffer (I'm drawing directly on the Graphics object). Why is this? Does java has a built-in backbuffer or something?
Animations: I'm used to put all animation parts in a single sprite sheet, like in this example:
http://www.envygames.com/share/sample_animation.jpg
Now, someone has told me that you can just draw animated .gif's and java will draw these independent of the game loop. I've tried this out and it doesn't seem to work. Is this true or am I also supposed to use these sprite sheets in java?
Thanks
Yes, Java has a double buffer rendering strategy that can be switched on and off...
Java: how to do double-buffering in Swing?
About the animated gifs, I think it is right, but you may have to put them in the appropriate container (maybe as the icon of a JLabel?).
getting a Graphics object by extending JFrame and
calling this.getContentPane().getGraphics().
don't painting directly to the JFrame for Custom Painting you have to look for JLabel that allows painting everything, another choise will be extending JCompoments, or JPanel for that
for painting in the Swing you have to look for paintComponent(Graphics g), not paint(Graphics g), because this method are lots of time used in examples and ditributed on some of Java ExamplesDepots, that's wrong method with possible lacks

How to paint outside of paintComponent?

I have a canvas that is drawing everything in a paintComponent() method.
Is it possible to draw outside of paintComponent (without calling a method within paintComponent?)
If so how do you go about doing this?
It depends what you mean and why you need it. For example, it is possible to create a BufferedImage, get the Graphics2D object, Graphics.paint() everything that should be on the image, then drop the image into a JLabel.
But since I do not know what you are trying to achieve (as opposed to what you are trying to do) I cannot know if that answer solves the unstated problem.
I found out how to solve this issue.
What I did was make JPanel an inner class to my JFrame class.
In JPanels paintComponent I had it calling a method from the outer class which did some updating of the graphics, by passing paintComponents Graphics2D object.
This has allowed me to paint "outside" of paintComponent, just as I needed.

Cannot get image to move where I want it to (and update continuously)?

I'm Basically programming a simple game engine but I'm having problems with my sprites/images not appearing when they should... or at all!
I'll try and keep this as simple as possible. I have a Sprite, GameEngine and Display class. In the gameloop, I have a method that sets the new position of my Sprite (so it just sets the x and y variables). Next I call a transform method which does the following:
public void transform() {
affineTransform.setToIdentity();
affineTransform.translate(x, y);
}
Following that, I then call a draw method in the Sprite:
public void draw() {
graphics2D.drawImage(image, affineTransform, jFrame);
}
Finally, in my thread I then call repaint() on the JFrame (the Display class). My paint method for that class is as follows:
public void paint(Graphics g) {
g.drawImage(backbuffer, insets.left, insets.top, this);
}
But nothing is appearing, apart from a black screen!
I'm also getting confused between Graphics g, and Graphics2D and when to use either. (The overridden paint method uses Graphics g). For the record, I do have a Graphics2D variable in the class that is created by calling backbuffer.createGraphics();
Another thing that is confusing me is this AffineTransform... I've read the documentation but I'm still utterly confused on how and when to use it - and what exactly it seems to do. Is there any explanation in relatively simple terms?
Surely this should be working... am I missing something out here?
To answer part of your question:
From the Graphics2D JavaDoc
This Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout. This is the fundamental class for rendering 2-dimensional shapes, text and images on the Java(tm) platform.
Essentially, with Graphics2D you can do much more than you can with Graphics. And with a Sun JVM 1.5+, it should be safe to cast the Graphics object you get in paint() to Graphics2D
I just noticed this: For the record, I do have a Graphics2D variable in the class that is created by calling backbuffer.createGraphics();
You should make sure you're not drawing on a Graphics[2D] canvas (I'll use this term to refer to the drawable area that the Graphics[2D] object provides) that you later throw away. If you're drawing your image on a separate canvas, you should ensure that you then draw that image onto your actual display canvas.
I don't really have a good explanation of AffineTransform but maybe these will help?
http://www.javalobby.org/java/forums/t19387.html
https://secure.wikimedia.org/wikipedia/en/wiki/Affine_transformation
From Wikipedia - In general, an affine transformation is composed of linear transformations (rotation, scaling or shear) and a translation (or "shift"). Several linear transformations can be combined into a single one. Basically, you use this class to perform operations such as rotation, translation, zoom etc.

Simplest way to draw primitives in Java (not OpenGL)

Just started to getting familiar with graphics in Java.
What is the simplest way to draw primitives (lines, rectangles) in Java without OpenGL (JOGL)?
Looking for methods like putPixel, lineTo, etc.
UPD.
Where to paint? Canvas? Panel? Bitmap?
The built in interface is called "Graphics2D".
Here's a link to a Java Graphics2D Tutorial: http://java.sun.com/docs/books/tutorial/2d/index.html
You can get a Graphics/Graphics2D instance from any AWT/Swing component via the paint method. JPanel is probably best since it fits well with swing and is lightweight, meaning that only one native window is created - for the top level window. Swing components can also be double-buffered, meaning that the painting is done to an offscreen buffer first, before being transferred to the screen. This gives a smoother appearance and avoids flickering that can happen when painting directly to the screen, and is particularly important for smooth animation.
You can specifically draw to an offscreen buffer ("bitmap") that you can use afterwards, e.g. to draw an image for saving as a file later:
BufferedImage offImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Grapics2D g2 = offImg.createGraphics();
// .. optionally set attributes ..
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
My recent question about horizontal scrolling in Java includes a tiny little graphics example source code that you could use as a base to work from. There are both AWT and Swing implementations. The AWT doesn't support horizontal scrolling, so I'll be using swing.
Not recommending these as best practice or anything, they were a quick demonstration of my particular issue, but it might be enough to get you started.
Link is How to use my trackpad for horizontal mousewheel scrolling in a Java AWT ScrollPane
The original Java user interface classes are called AWT. These were "heavyweight" components, that sometimes acted differently on different systems (Windows, Mac, Unix). These components were difficult to use to make a GUI.
Sun developed Swing, which is a set of "lightweight" components that, to the maximum degree possible, work the same on different systems. These components made GUI development somewhat easier.
In order to have a canvas for graphics, you start with a javax.swing.JFrame. You add a child javax.swing.JPanel to the JFrame. You draw on the JPanel by overriding the paint method.
The JPanel paint method takes a java.awt.Graphics as input. You can cast Graphics to java.awt.Graphics2D. The methods of Graphics2D allow you to draw rectangles, images, text, lines, and arbitrary polygons.
You can find out more about Swing by reading Sun's Creating a GUI with JFC/Swing tutorial. You can find out more about 2D Graphics by reading Sun's 2D Graphics tutorial. More details on the Java classes I've mentioned can be found in the Javadoc.

Categories