Graphics in Java
We will now learn how to draw vectorial graphics and images in Java GUI components. You will spend most of your time in the java.awt.graphics package.
First example
We start with the javax.swing.JPanel component, which is an empty object on which we will draw.
import java.awt.*; import javax.swing.*; public class Example extends JFrame { public Example() { initGUI(); } public void initGUI(){ setTitle("Simple example"); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); drawingPanel.setBounds(0,0,300,200); getContentPane().add(drawingPanel); } public static void main(String[] args) { Example ex = new Example(); ex.setVisible(true); } DrawingPanel drawingPanel = new DrawingPanel(); } class DrawingPanel extends JPanel{ public DrawingPanel(){ } public void paint(Graphics g){ g.drawString("Un texte!",30,30); } }
Here, we defined a new class derived from JPanel. So a DrawingPanel object is in particular a JPanel, and it can be manipulated as such. Thus, we set its bounds (with setBounds), and we added it to the content pane of the JFrame object.
Now, the paint method is where the drawing of an object takes place. So if you looked at the source code of, say, JButton, you would see the drawing of a rectangle with a string inside this method. The method only gives us a Graphics object, which provides a great number of drawing methods.
Check out the Java API to draw a pie chart (un camembert).
Extend your pie chart so that when mouse clicks on a slice, it displays in a new dialog the name of that slice.