- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Painting in Swing
Swing's painting system is able to render vector graphics, images, and outline font-based text. Painting is needed in applications when we want to change or enhance an existing widget, or if we are creating a custom widget from scratch To do the painting, we use the painting API provided by the Swing toolkit.
The painting is done within the paintComponent()
method. In the painting process, we use the Graphics2D
object.
2D Vector Graphics
There are two different computer graphics. Vector and raster graphics. Raster graphics represents images as a collection of pixels. Vector graphics is the use of geometrical primitives such as points, lines, curves or polygons to represent images. These primitives are created using mathematical equations.
Both types of computer graphics have advantages and disadvantages. The advantages of vector graphics over raster are:
- smaller size
- ability to zoom indefinitely
- moving, scaling, filling or rotating does not degrade the quality of an image
Types of primitives
- points
- lines
- polylines
- polygons
- circles
- ellipses
- Splines
Points
The most simple graphics primitive is point. It is a single dot on the window. There is no method to draw a point in Swing. To draw a point, we use the drawLine()
method. We use one point twice.
package com.zetcode; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; class DrawPanel extends JPanel { private void doDrawing(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.blue); for (int i = 0; i <= 1000; i++) { Dimension size = getSize(); Insets insets = getInsets(); int w = size.width - insets.left - insets.right; int h = size.height - insets.top - insets.bottom; Random r = new Random(); int x = Math.abs(r.nextInt()) % w; int y = Math.abs(r.nextInt()) % h; g2d.drawLine(x, y, x, y); } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } } public class PointsExample extends JFrame { public PointsExample() { initUI(); } public final void initUI() { DrawPanel dpnl = new DrawPanel(); add(dpnl); setSize(250, 200); setTitle("Points"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { PointsExample ex = new PointsExample(); ex.setVisible(true); } }); } }
One point is difficult to observe. Therefore, we will randomly draw 1000 points on the panel surface.
class DrawPanel extends JPanel {
We are drawing on a custom drawing panel, which is a JPanel
component. The drawing panel will later be added to a JFrame
component.
@Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); }
Custom painting is performed inside the paintComponent()
method, which we override. The super.paintComponent()
method calls the method of the parent class. It does some necessary work to prepare component for drawing. Actual drawing is delegated to the doDrawing()
method.
Graphics2D g2d = (Graphics2D) g;
Painting in Swing is done on the Graphics2D
object.
g2d.setColor(Color.blue);
We will paint our points in blue colour.
Dimension size = getSize(); Insets insets = getInsets();
The size of the window includes borders and titlebar. We do not paint there.
int w = size.width - insets.left - insets.right; int h = size.height - insets.top - insets.bottom;
Here we calculate the area, where we will effectively paint our points.
Random r = new Random(); int x = Math.abs(r.nextInt()) % w; int y = Math.abs(r.nextInt()) % h;
We get a random number in range of the size of area that we computed above.
g2d.drawLine(x, y, x, y);
Here we draw the point. As we already said, we use a drawLine()
method. We specify the same point twice.

Lines
A line is a simple graphics primitive. It is drawn using two points.
package com.zetcode; import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; class DrawPanel extends JPanel { private void doDrawing(Graphics g) { Graphics2D g2d = (Graphics2D) g; float[] dash1 = {2f, 0f, 2f}; float[] dash2 = {1f, 1f, 1f}; float[] dash3 = {4f, 0f, 2f}; float[] dash4 = {4f, 4f, 1f}; g2d.drawLine(20, 40, 250, 40); BasicStroke bs1 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash1, 2f); BasicStroke bs2 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash2, 2f); BasicStroke bs3 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash3, 2f); BasicStroke bs4 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash4, 2f); g2d.setStroke(bs1); g2d.drawLine(20, 80, 250, 80); g2d.setStroke(bs2); g2d.drawLine(20, 120, 250, 120); g2d.setStroke(bs3); g2d.drawLine(20, 160, 250, 160); g2d.setStroke(bs4); g2d.drawLine(20, 200, 250, 200); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } } public class LinesExample extends JFrame { public LinesExample() { initUI(); } public final void initUI() { DrawPanel dpnl = new DrawPanel(); add(dpnl); setSize(280, 270); setTitle("Lines"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { LinesExample ex = new LinesExample(); ex.setVisible(true); } }); } }
In the example, we draw five lines. The first line is drawn using the default values. Other will have a different stroke. The stroke is created using the BasicStroke
class. It defines a basic set of rendering attributes for the outlines of graphics primitives.
float[] dash1 = { 2f, 0f, 2f };
Here we create a dash that we use in the stroke object.
BasicStroke bs1 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash1, 2f )
This code creates a stroke. The stroke defines the line width, end caps, line joins, miter limit, dash and the dash phase.

Rectangles
To draw rectangles, we use the drawRect()
method. To fill rectangles with the current color, we use the fillRect()
method.
package com.zetcode; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; class DrawPanel extends JPanel { private void doDrawing(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(new Color(212, 212, 212)); g2d.drawRect(10, 15, 90, 60); g2d.drawRect(130, 15, 90, 60); g2d.drawRect(250, 15, 90, 60); g2d.drawRect(10, 105, 90, 60); g2d.drawRect(130, 105, 90, 60); g2d.drawRect(250, 105, 90, 60); g2d.drawRect(10, 195, 90, 60); g2d.drawRect(130, 195, 90, 60); g2d.drawRect(250, 195, 90, 60); g2d.setColor(new Color(125, 167, 116)); g2d.fillRect(10, 15, 90, 60); g2d.setColor(new Color(42, 179, 231)); g2d.fillRect(130, 15, 90, 60); g2d.setColor(new Color(70, 67, 123)); g2d.fillRect(250, 15, 90, 60); g2d.setColor(new Color(130, 100, 84)); g2d.fillRect(10, 105, 90, 60); g2d.setColor(new Color(252, 211, 61)); g2d.fillRect(130, 105, 90, 60); g2d.setColor(new Color(241, 98, 69)); g2d.fillRect(250, 105, 90, 60); g2d.setColor(new Color(217, 146, 54)); g2d.fillRect(10, 195, 90, 60); g2d.setColor(new Color(63, 121, 186)); g2d.fillRect(130, 195, 90, 60); g2d.setColor(new Color(31, 21, 1)); g2d.fillRect(250, 195, 90, 60); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } } public class RectanglesExample extends JFrame { public RectanglesExample() { initUI(); } public final void initUI() { DrawPanel dpnl = new DrawPanel(); add(dpnl); setSize(360, 300); setTitle("Rectangles"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { RectanglesExample ex = new RectanglesExample(); ex.setVisible(true); } }); } }
In the example we draw nine coloured rectangles.
g2d.setColor(new Color(212, 212, 212)); g2d.drawRect(10, 15, 90, 60); ...
We set the colour of the outline of the rectangle to a soft gray colour, so that it does not interfere with the fill colour. To draw the outline of the rectangle, we use the drawRect()
method. The first two parameters are the x and y values. The third and fourth are width and height.
g2d.fillRect(10, 15, 90, 60);
To fill the rectangle with a colour, we use the fillRect()
method.

Textures
A texture is a bitmap image applied to a shape. To work with textures in Java 2D, we use the TexturePaint
class.
package com.zetcode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.TexturePaint; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; import java.io.IOException; import java.util.logging.Logger; import java.util.logging.Level; import javax.imageio.ImageIO; import javax.swing.SwingUtilities; class DrawPanel extends JPanel { BufferedImage slate; BufferedImage java; BufferedImage pane; TexturePaint slatetp; TexturePaint javatp; TexturePaint panetp; public DrawPanel() { loadImages(); } private void loadImages() { try { slate = ImageIO.read(this.getClass().getResource("slate.png")); java = ImageIO.read(this.getClass().getResource("java.png")); pane = ImageIO.read(this.getClass().getResource("pane.png")); } catch (IOException ex) { Logger.getLogger(Textures.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } private void doDrawing(Graphics g) { Graphics2D g2d = (Graphics2D) g; slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60)); javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60)); panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60)); g2d.setPaint(slatetp); g2d.fillRect(10, 15, 90, 60); g2d.setPaint(javatp); g2d.fillRect(130, 15, 90, 60); g2d.setPaint(panetp); g2d.fillRect(250, 15, 90, 60); } } public class Textures extends JFrame { public Textures() { initUI(); } public final void initUI() { DrawPanel dpnl = new DrawPanel(); add(dpnl); setSize(360, 120); setTitle("Textures"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Textures ex = new Textures(); ex.setVisible(true); } }); } }
In the code example, we fill three rectangles with three different textures.
slate = ImageIO.read(this.getClass().getResource("slate.png"));
Here we read the image into the buffered image.
slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
We create a TexturePaint
class out of the buffered image.
g2d.setPaint(slatetp); g2d.fillRect(10, 15, 90, 60);
We fill a rectangle with a texture.

Gradients
In computer graphics, gradient is a smooth blending of shades from light to dark or from one colour to another. In 2D drawing programs and paint programs, gradients are used to create colourful backgrounds and special effects as well as to simulate lights and shadows. (answers.com)
package com.zetcode; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; class DrawPanel extends JPanel { private void doDrawing(Graphics g) { Graphics2D g2d = (Graphics2D) g; GradientPaint gp1 = new GradientPaint(5, 5, Color.red, 20, 20, Color.black, true); g2d.setPaint(gp1); g2d.fillRect(20, 20, 300, 40); GradientPaint gp2 = new GradientPaint(5, 25, Color.yellow, 20, 2, Color.black, true); g2d.setPaint(gp2); g2d.fillRect(20, 80, 300, 40); GradientPaint gp3 = new GradientPaint(5, 25, Color.green, 2, 2, Color.black, true); g2d.setPaint(gp3); g2d.fillRect(20, 140, 300, 40); GradientPaint gp4 = new GradientPaint(25, 25, Color.blue, 15, 25, Color.black, true); g2d.setPaint(gp4); g2d.fillRect(20, 200, 300, 40); GradientPaint gp5 = new GradientPaint(0, 0, Color.orange, 0, 20, Color.black, true); g2d.setPaint(gp5); g2d.fillRect(20, 260, 300, 40); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } } public class GradientsExample extends JFrame { public GradientsExample() { initUI(); } public final void initUI() { DrawPanel dpnl = new DrawPanel(); add(dpnl); setSize(350, 350); setTitle("Gradients"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GradientsExample ex = new GradientsExample(); ex.setVisible(true); } }); } }
Our code example presents five rectangles with gradients.
GradientPaint gp4 = new GradientPaint(25, 25, Color.blue, 15, 25, Color.black, true);
To work with gradients, we use Java Swing's GradientPaint
class. By manipulating the colour values and the starting end ending points, we can get different results.
g2d.setPaint(gp5);
The gradient is activated calling the setPaint()
method.

Drawing text
Drawing is done with the drawString()
method. We specify the string we want to draw and the position of the text on the window area.
package com.zetcode; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; class DrawPanel extends JPanel { private void doDrawing(Graphics g) { Graphics2D g2d = (Graphics2D) g; RenderingHints rh = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh); Font font = new Font("URW Chancery L", Font.BOLD, 21); g2d.setFont(font); g2d.drawString("Not marble, nor the gilded monuments", 20, 30); g2d.drawString("Of princes, shall outlive this powerful rhyme;", 20, 60); g2d.drawString("But you shall shine more bright in these contents", 20, 90); g2d.drawString("Than unswept stone, besmear'd with sluttish time.", 20, 120); g2d.drawString("When wasteful war shall statues overturn,", 20, 150); g2d.drawString("And broils root out the work of masonry,", 20, 180); g2d.drawString("Nor Mars his sword, nor war's quick " + "fire shall burn", 20, 210); g2d.drawString("The living record of your memory.", 20, 240); g2d.drawString("'Gainst death, and all oblivious enmity", 20, 270); g2d.drawString("Shall you pace forth; your praise shall still " + "find room", 20, 300); g2d.drawString("Even in the eyes of all posterity", 20, 330); g2d.drawString("That wear this world out to the ending doom.", 20, 360); g2d.drawString("So, till the judgment that yourself arise,", 20, 390); g2d.drawString("You live in this, and dwell in lovers' eyes.", 20, 420); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } } public class DrawingText extends JFrame { public DrawingText() { initUI(); } public final void initUI() { DrawPanel dpnl = new DrawPanel(); add(dpnl); setSize(500, 470); setTitle("Sonnet55"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { DrawingText ex = new DrawingText(); ex.setVisible(true); } }); } }
In our example, we draw a sonnet on the panel component.
RenderingHints rh = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh);
This code is to make our text look better. We apply a technique called antialiasing.
Font font = new Font("URW Chancery L", Font.BOLD, 21); g2d.setFont(font);
We choose a specific font for our text.
g2d.drawString("Not marble, nor the gilded monuments", 20, 30);
This is the code that draws the text.
Images
On of the most important capabililies of a toolkit is the ability to display images. An image is an array of pixels. Each pixel represents a colour at a given position. We can use components like JLabel
to display an image, or we can draw it using the Java 2D API.
package com.zetcode; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; class DrawPanel extends JPanel { Image img; public DrawPanel() { loadImage(); Dimension dm = new Dimension(img.getWidth(null), img.getHeight(null)); setPreferredSize(dm); } private void loadImage() { img = new ImageIcon("slanec.png").getImage(); } private void doDrawing(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.drawImage(img, 0, 0, null); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } } public class ImageExample extends JFrame { public ImageExample() { initUI(); } public final void initUI() { DrawPanel dpnl = new DrawPanel(); add(dpnl); setTitle("Image"); pack(); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ImageExample ex = new ImageExample(); ex.setVisible(true); } }); } }
This example will draw an image on the panel. The image will fit the JFrame
window.
public DrawPanel() { loadImage(); Dimension dm = new Dimension(img.getWidth(null), img.getHeight(null)); setPreferredSize(dm); }
In the constructor of the DrawPanel
class, we call the loadImage()
method. We determine the image dimensions and set the preffered size of the panel component. This will together with the pack()
method display the image to fit exactly the window.
private void loadImage() { img = new ImageIcon("slanec.png").getImage(); }
The method loads an image from the disk. We use the ImageIcon
class. This class simplyfies the work with the images in Java Swing.
g2d.drawImage(this.img, 0, 0, null);
The image is drawn using the drawImage()
method.
In this chapter, we did some painting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论