Drawing a graph with Graphics2D using WindowBuilder - java

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.

Related

How to make a JFrame one colour?

I'm trying to add some polish to a small game I made and, every time a round finishes, I'd like the whole JFrame to flash white and quickly lose opacity until you can see the game again. How would I do this?
Note: I'm thinking about hiding all the components and adding a JPanel on top that loses opacity quickly but this doesn't seem right (and I'd like to be able to see the components behind the white flash as it goes from opaque to transparent).
You could probably use the JLayer class. Take a look at the section from the Swing tutorial on How to Decorate Components with the JLayer Class.
The tutorial has examples that:
paint translucent layers
do animation
Put the examples together and you should have a solution.
You can use fading out image to achieve the same. AlphaComposite is used for fading effect.
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
Refer Fade Out Image to access the sample code.

Drawing Line, Arc etc. Anywhere in the Code 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.

Why is attaching a JPanel better?

I've just started coding video games and I've heard that doing all your drawing on a JPanel and attaching that panel onto a JFrame is better than simply drawing onto the JFrame. I was just wondering why is this better?
It is better for various reasons, including:
In most Swing components, custom painting is achieved by overriding the paintComponent(Graphics) method. Top-level Swing containers (e.g. JFrame, JApplet, JWindow) have only paint(Graphics). As a result of the common method for painting, people who answer often forget about this difference between common and top-level components, and therefore suggest silly advice. ;)
A JComponent can be added to a JFrame, or a JApplet, or a JDialog, or a constraint of a layout in a JPanel, or a JInternalFrame, or a.. Just when you think your GUI is complete, the client says "Hey, wouldn't it be great to throw in a tool-bar & offer it as an applet as well?" The JComponent approach adapts easily to that.
As explained (complete with code!) by Richante, it is easier to calculate the co-ordinates required for painting the custom component, and if it has a preferred size, to size the JFrame to be 'exactly the right size' to contain the GUI (using pack()). That is especially the case when other components are added as well.
Now, two minor disagreements with the advice offered.
If the entire component is custom painted, it might be better to simply put a BufferedImage inside an ImageIcon/JLabel combo. Here is an example of painting to an image. When it comes time to update it:
Call getGraphics() for a Graphics or createGraphics() for a Graphics2D
Draw the custom painting to that graphics instance
Dispose of the graphics instance
Call repaint() on the label.
It is an easy way to do Double Buffering.
Let me elaborate a bit. In video games, to avoid the flicker caused by redrawing and display smoother graphics, people usually use double buffering. They create an offscreen surface, draw everything on that and then display the entire off-screen surface on the screen in one go.
In Java2D and Swing, the easiest way to do this, is to simply do your game sprite drawing on a JPanel, and then add the JPanel to a JFrame.
Secondly, by drawing things on a JPanel, you allow more GUI widgets and other graphical objects to be displayed on the JFrame without having to paint them manually in the game loop. For example buttons, menus, other panels, even other rendering JPanels.
Thirdly, it allows you to use automatically translated co-ordinates for your game. You can draw everything from the top-left to the bottom-right without having to worry about the window manager specific things like window border-widths, task panes, titles etc.!
Moreover, this is not just a convention only used by Game Programmers in Java. Creating a separate Game Board, Render Panel or Graphics Widget is quite popular when programming games using a library with an internal mainloop such as a GUI Toolkit. You can use a User Form in Windows Forms and a Drawing Board in GTK+.
The JFrame includes things like the menu, title bar and border. Therefore, when you refer to coordinates you have to account for these. You might also decide to add a menu bar, or some other components, to the frame. If your painting is all in a JPanel, then this won't change how you need to refer to coordinates.
For example, try:
public class Test extends JFrame {
public Test() {
super();
setVisible(true);
setBounds(100, 100, 200, 100);
}
#Override
public void paint(Graphics g) {
g.fillRect(0, 0, 50, 50);
}
public static void main(String[] args) {
new Test();
}
}
and you will see that the black square is not square! Because (0, 0) is the top left corner of the entire frame, not the corner of the visible area.

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

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