Java Reference
In-Depth Information
(good), from creating huge event listeners in inner classes (bad) to separating them into separate classes
and even into background tasks (good), from trying to make UIs as hierarchically flat as possible and
fighting with layout managers (bad) to accepting the fact that you might want to create another JPanel ,
or perhaps a separate custom class extending JPanel and nesting this in a reusable manner (good).
Writing GUIs in Java is by no means easy. It is oftentimes cumbersome, boring even. You want to focus
on the core concepts of your program, and that involves a lot of boilerplate code. However, architectural
decisions you make at the beginning might end up saving you a lot of time and headache later.
let's draw: defining custom draw Behavior
It's already been stated that Swing components handle all drawing behavior by themselves, which is
why they can look similar on each platform they're run on. You saw before how to work with differ-
ent look and feels inside Swing, but you might also be interested in knowing whether you can over-
ride or extend rendering behavior of components.
The answer is that indeed, you can. All Swing components ( JComponent ) come with the following
built‐in methods:
public void paint(Graphics g) : Paints the component, its border, and its children by
calling these methods:
protected void paintComponent(Graphics g)
protected void paintBorder(Graphics g)
protected void paintChildren(Graphics g)
The Graphics object that's passed along can be regarded as a general surface area on which Java
can draw, representing the geometric area of the component that will need to be painted.
To show this off, the following Try It Out will lead you through a simple painting application,
which is also a good opportunity to show off a mouse listener and show another helpful component,
the JFileChooser .
Making a paint application with Custom-painted Components
try it out
In this Try It Out, you create a simple painting application by overriding the default painting behavior
of a component.
1.
As always, feel free to create a new project in Eclipse when you want to. Create a class called
SimplePaint with the following content as a bare bones starting point:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SimplePaint extends JFrame {
public SimplePaint() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Simple Paint");
pack();
 
Search WWH ::




Custom Search