Fill It Game Without Java

  1. Play thousands of free online games: arcade games, puzzle games, funny games, sports games, shooting games, and more. New free games every day at AddictingGames.
  2. You'll probably learn something from the code I've written, for I'm also making my own Tetris game. I could see improvements that could be added like adding a 'Game Over' feature, but your coding cleanliness is exceptional, and I even tried to implement the 'well array' idea to my own app.
  1. Fill It Game Without Javascript
  2. Fill It Game Java

This Minecraft tutorial explains how to use the /fill command with screenshots and step-by-step instructions.

Shockwave is the third of the plugins that some games use. To play Shockwave games in your browser, follow the video and instructions below (Windows 7/8.1/10 only): Download Adobe Shockwave Player 12.3.4.205, the last version of Shockwave. Download and install the Pale Moon browser (32-bit). (Where does the Shockwave installer come from? Unlike many other computer languages, Java provides built-in support for multithreading. Multithreading in Java contains two or more parts that can run concurrently. A Java thread is actually a. It enables you to create a generic class without specifying a type between angle brackets. It is a special type of class that is associated with one or more non-specified Java type. It is a subclass of List. It is an interface in the java.util package that is used to define a group of objects. (.) Correct Correct 8.

You can fill an area or outline with a particular block using the /fill command in Minecraft. Let's explore how to use this cheat (game command).

Supported Platforms

The /fill command is available in the following versions of Minecraft:

PlatformSupported (Version*)
Java Edition (PC/Mac)Yes (1.8)
Pocket Edition (PE)Yes (0.16.0)
Xbox 360No
Xbox OneYes (1.2)
PS3No
PS4Yes (1.14.0)
Wii UNo
Nintendo SwitchYes (1.5.0)
Windows 10 EditionYes (0.16.0)
Education EditionYes

* The version that it was added or removed, if applicable.
NOTE: Pocket Edition (PE), Xbox One, PS4, Nintendo Switch, and Windows 10 Edition are now called Bedrock Edition. We will continue to show them individually for version history.

Requirements

To run game commands in Minecraft, you have to turn cheats on in your world.

Fill Command

  • Java
  • PE
  • Xbox
  • PS
  • Nintendo
  • Win10
  • Edu

Fill Command in Minecraft Java Edition (PC/Mac)

In Minecraft Java Edition (PC/Mac) 1.13, 1.14, 1.15 and 1.16, there are 2 syntaxes for the /fill command.

To fill a region with a type of block:

To replace one type of block in a region with another type of block:


Java

In Minecraft Java Edition (PC/Mac) 1.8, 1.9, 1.10, 1.11 and 1.12, there are 2 syntaxes for the /fill command.

To fill a region with a type of block:

To replace one type of block in a region with another type of block:

Definitions

  • from or x1 y1 z1 is the starting coordinate for the fill region (ie: first corner block).
  • to or x2 y2 z2 is the ending coordinate for the fill region (ie: opposite corner block).
  • block is name of the block to fill the region. (See Minecraft Item Names)
  • dataValue is optional. It is the variation of the block if more than one type exists for that block.
  • oldBlockHandling is optional. It tells the command how to fill in the region. The default behavior is replace. It can be one of the following values:
    • replace - Replaces all blocks in the fill region, including air.
    • outline - Replaces blocks on the outer edge of the fill region, but does not replace the inner blocks.
    • hollow - Replaces blocks on the outer edge of the fill region, and replaces inner blocks with air.
    • keep - Replaces only air blocks in the fill region.
    • destroy - Replaces all blocks in the fill region, including air. Replaced blocks will be dropped and can then be collected as if they were mined with a pickaxe or shovel.
  • dataTag is the data tag for the fill block.
  • newTileName is the name of the block that will be replaced. (See Minecraft Item Names)
  • newDataValue is optional. It is the variation of the block to be replaced if more than one type exists for that newTileName.

Fill Command in Minecraft Pocket Edition (PE)

In Minecraft Pocket Edition (PE), there are 2 syntaxes for the /fill command.

To fill a region with a type of block:

To replace one type of block in a region with another type of block:

Definitions

  • from is the starting x y z coordinate for the fill region (ie: first corner block).
  • to is the ending x y z coordinate for the fill region (ie: opposite corner block).
  • tileName is name of the block to fill the region. (See Minecraft Item Names)
  • tileData is optional. It is the data type or variation of the block if more than one type exists for that tileName.
  • replace will replace all blocks in the fill region, including air.
  • outline is optional. It will replace blocks on the outer edge of the fill region, but does not replace the inner blocks.
  • hollow is optional. It will replace blocks on the outer edge of the fill region, and replaces inner blocks with air.
  • keep is optional. It will replace only air blocks in the fill region.
  • destroy is optional. It will replace all blocks in the fill region, including air. Replaced blocks will be dropped and can then be collected as if they were mined with a pickaxe or shovel.
  • replaceTileName is the name of the block that will be replaced. (See Minecraft Item Names)
  • replaceDataValue is the variation of the block to be replaced if more than one type exists for that replaceTileName.

Fill Command in Minecraft Xbox One Edition

In Minecraft Xbox One Edition, there are 2 syntaxes for the /fill command.

To fill a region with a type of block:

To replace one type of block in a region with another type of block:

Definitions

  • from is the starting x y z coordinate for the fill region (ie: first corner block).
  • to is the ending x y z coordinate for the fill region (ie: opposite corner block).
  • tileName is name of the block to fill the region. (See Minecraft Item Names)
  • tileData is optional. It is the data type or variation of the block if more than one type exists for that tileName.
  • replace will replace all blocks in the fill region, including air.
  • outline is optional. It will replace blocks on the outer edge of the fill region, but does not replace the inner blocks.
  • hollow is optional. It will replace blocks on the outer edge of the fill region, and replaces inner blocks with air.
  • keep is optional. It will replace only air blocks in the fill region.
  • destroy is optional. It will replace all blocks in the fill region, including air. Replaced blocks will be dropped and can then be collected as if they were mined with a pickaxe or shovel.
  • replaceTileName is the name of the block that will be replaced. (See Minecraft Item Names)
  • replaceDataValue is the variation of the block to be replaced if more than one type exists for that replaceTileName.

Fill Command in Minecraft PS4 Edition

In Minecraft PS4 Edition, there are 2 syntaxes for the /fill command.

To fill a region with a type of block:

To replace one type of block in a region with another type of block:

Definitions

  • from is the starting x y z coordinate for the fill region (ie: first corner block).
  • to is the ending x y z coordinate for the fill region (ie: opposite corner block).
  • tileName is name of the block to fill the region. (See Minecraft Item Names)
  • tileData is optional. It is the data type or variation of the block if more than one type exists for that tileName.
  • replace will replace all blocks in the fill region, including air.
  • outline is optional. It will replace blocks on the outer edge of the fill region, but does not replace the inner blocks.
  • hollow is optional. It will replace blocks on the outer edge of the fill region, and replaces inner blocks with air.
  • keep is optional. It will replace only air blocks in the fill region.
  • destroy is optional. It will replace all blocks in the fill region, including air. Replaced blocks will be dropped and can then be collected as if they were mined with a pickaxe or shovel.
  • replaceTileName is the name of the block that will be replaced. (See Minecraft Item Names)
  • replaceDataValue is the variation of the block to be replaced if more than one type exists for that replaceTileName.

Fill Command in Minecraft Nintendo Switch Edition

In Minecraft Nintendo Switch Edition, there are 2 syntaxes for the /fill command.

To fill a region with a type of block:

To replace one type of block in a region with another type of block:

Definitions

  • from is the starting x y z coordinate for the fill region (ie: first corner block).
  • to is the ending x y z coordinate for the fill region (ie: opposite corner block).
  • tileName is name of the block to fill the region. (See Minecraft Item Names)
  • tileData is optional. It is the data type or variation of the block if more than one type exists for that tileName.
  • replace will replace all blocks in the fill region, including air.
  • outline is optional. It will replace blocks on the outer edge of the fill region, but does not replace the inner blocks.
  • hollow is optional. It will replace blocks on the outer edge of the fill region, and replaces inner blocks with air.
  • keep is optional. It will replace only air blocks in the fill region.
  • destroy is optional. It will replace all blocks in the fill region, including air. Replaced blocks will be dropped and can then be collected as if they were mined with a pickaxe or shovel.
  • replaceTileName is the name of the block that will be replaced. (See Minecraft Item Names)
  • replaceDataValue is the variation of the block to be replaced if more than one type exists for that replaceTileName.

Fill Command in Minecraft Windows 10 Edition

In Minecraft Windows 10 Edition, there are 2 syntaxes for the /fill command.

To fill a region with a type of block:

To replace one type of block in a region with another type of block:

Definitions

  • from is the starting x y z coordinate for the fill region (ie: first corner block).
  • to is the ending x y z coordinate for the fill region (ie: opposite corner block).
  • tileName is name of the block to fill the region. (See Minecraft Item Names)
  • tileData is optional. It is the data type or variation of the block if more than one type exists for that tileName.
  • replace will replace all blocks in the fill region, including air.
  • outline is optional. It will replace blocks on the outer edge of the fill region, but does not replace the inner blocks.
  • hollow is optional. It will replace blocks on the outer edge of the fill region, and replaces inner blocks with air.
  • keep is optional. It will replace only air blocks in the fill region.
  • destroy is optional. It will replace all blocks in the fill region, including air. Replaced blocks will be dropped and can then be collected as if they were mined with a pickaxe or shovel.
  • replaceTileName is the name of the block that will be replaced. (See Minecraft Item Names)
  • replaceDataValue is the variation of the block to be replaced if more than one type exists for that replaceTileName.

Fill Command in Minecraft Education Edition

In Minecraft Education Edition, there are 2 syntaxes for the /fill command.

To fill a region with a type of block:

To replace one type of block in a region with another type of block:

Definitions

  • from is the starting x y z coordinate for the fill region (ie: first corner block).
  • to is the ending x y z coordinate for the fill region (ie: opposite corner block).
  • tileName is name of the block to fill the region. (See Minecraft Item Names)
  • tileData is optional. It is the data type or variation of the block if more than one type exists for that tileName.
  • replace will replace all blocks in the fill region, including air.
  • outline is optional. It will replace blocks on the outer edge of the fill region, but does not replace the inner blocks.
  • hollow is optional. It will replace blocks on the outer edge of the fill region, and replaces inner blocks with air.
  • keep is optional. It will replace only air blocks in the fill region.
  • destroy is optional. It will replace all blocks in the fill region, including air. Replaced blocks will be dropped and can then be collected as if they were mined with a pickaxe or shovel.
  • replaceTileName is the name of the block that will be replaced. (See Minecraft Item Names)
  • replaceDataValue is the variation of the block to be replaced if more than one type exists for that replaceTileName.
TIP: Read our tutorial called Understanding the Coordinate System to learn about the XYZ coordinates in Minecraft and how to find your current coordinates.

Volume Calculation

You can use the following calculation to determine how many blocks will be included in the fill region.

The formula for volume is:

Greater is the larger of the 2 corresponding coordinate values and lesser is the smaller of the 2 corresponding coordinate values.

Let's calculate the volume for the following command:

In this example:

So our volume calculation would be:

Examples

  • Java
  • PE
  • Xbox
  • PS
  • Nintendo
  • Win10
  • Edu

Example in Java Edition (PC/Mac) 1.13, 1.14, 1.15 and 1.16

To fill a 11x1x11 area (directly below you) with quartz block in Minecraft 1.13, 1.14, 1.15 and 1.16:

To build a solid structure (next to you) out of dark oak wood planks:

To build a large hollow cobblestone structure (next to you):

To mine a region, by replacing all blocks in the area with cobblestone starting 10 blocks deep (-10) up to ground level (-1), that is 5 blocks away from you in all horizontal directions:

To replace all water with air in the fill region with a starting coordinate of ~10 ~0 ~40 and an ending coordinate of ~-40 ~-3 ~-40:

Example in Java Edition (PC/Mac) 1.11 and 1.12

To build a solid structure (next to you) out of dark oak wood planks in Minecraft 1.11 and 1.12:

To build a large hollow cobblestone structure (next to you):

Example in Pocket Edition (PE)

To fill a 7x1x7 area (directly below you) with cyan wool in Minecraft PE:

To build a solid structure (next to you) out of smooth sandstone:

To build a large hollow prismarine bricks structure (next to you):

To mine a region, by replacing all blocks in the area with dirt starting 8 blocks deep (-8) up to ground level (-1), that is 3 blocks away from you in all horizontal directions:

To replace all grass blocks with gold blocks in the fill region with a starting coordinate of ~10 ~ ~20 and an ending coordinate of ~-20 ~-1 ~-20:

Example in Xbox One Edition

To fill a 13x1x7 area (directly below you) with obsidian in Minecraft Xbox One Edition:

To build a solid structure (next to you) out of red concrete:

To build a large hollow bedrock structure (next to you):

To mine a region, by replacing all blocks in the area with cobblestone starting 5 blocks deep (-5) up to ground level (-1), that is 4 blocks away from you in all horizontal directions:

To replace all grass blocks with coal blocks in the fill region with a starting coordinate of ~10 ~ ~20 and an ending coordinate of ~-20 ~-1 ~-20:

Example in PS4 Edition

To fill a 8x1x8 area (directly below you) with bedrock in Minecraft PS4 Edition:

To build a solid structure (next to you) out of polished granite:

To build a large hollow dark prismarine structure (next to you):

To mine a region, by replacing all blocks in the area with sand starting 7 blocks deep (-7) up to ground level (-1), that is 3 blocks away from you in all horizontal directions:

To replace all grass blocks with diamond blocks in the fill region with a starting coordinate of ~5 ~ ~8 and an ending coordinate of ~-20 ~-1 ~-20:

Example in Nintendo Switch Edition

Without

To fill a 7x1x7 area (directly below you) with diamond blocks in Minecraft Nintendo Switch Edition:

To build a solid structure (next to you) out of chiseled sandstone:

To build a large hollow prismarine bricks structure (next to you):

To mine a region, by replacing all blocks in the area with dirt starting 8 blocks deep (-8) up to ground level (-1), that is 3 blocks away from you in all horizontal directions:

To replace all grass blocks with diamond blocks in the fill region with a starting coordinate of ~8 ~ ~15 and an ending coordinate of ~-12 ~-1 ~-22:

Example in Windows 10 Edition

To fill a 9x1x9 area (directly below you) with chiseled red sandstone in Minecraft Windows 10 Edition:

To build a solid structure (next to you) out of purpur pillars:

To build a large hollow coal blocks structure (next to you):

To mine a region, by replacing all blocks in the area with stone starting 8 blocks deep (-8) up to ground level (-1), that is 3 blocks away from you in all horizontal directions:

To replace all grass blocks with lapis lazuli blocks in the fill region with a starting coordinate of ~5 ~ ~10 and an ending coordinate of ~-25 ~-1 ~-25:

Example in Education Edition

To fill a 5x1x5 area (directly below you) with diorite in Minecraft Education Edition:

To build a solid structure (next to you) out of chiseled sandstone:

To build a large hollow polished andesite structure (next to you):

To mine a region, by replacing all blocks in the area with dirt starting 8 blocks deep (-8) up to ground level (-1), that is 4 blocks away from you in all horizontal directions:

To replace all grass blocks with gold blocks in the fill region with a starting coordinate of ~8 ~ ~12 and an ending coordinate of ~-25 ~-1 ~-20:

How to Enter the Command

1. Open the Chat Window

The easiest way to run a command in Minecraft is within the chat window. The game control to open the chat window depends on the version of Minecraft:

  • For Java Edition (PC/Mac), press the T key to open the chat window.
  • For Pocket Edition (PE), tap on the chat button at the top of the screen.
  • For Xbox One, press the D-Pad (right) on the controller.
  • For PS4, press the D-Pad (right) on the controller.
  • For Nintendo Switch, press the right arrow button on the controller.
  • For Windows 10 Edition, press the T key to open the chat window.
  • For Education Edition, press the T key to open the chat window.

2. Type the Command

We will cover examples of how to use the /fill command to cover the ground under you, build a solid structure, build a hollow structure, and mine a large area instantly.

Cover the Ground under You

Let's start by showing how to replace a region of blocks that are beneath where you are standing. For example, let's cover the ground below us in a 11x1x11 area with quartz block with the following command:

Type the command in the chat window. As you are typing, you will see the command appear in the lower left corner of the game window. Press the Enter key to run the command.

This /fill command would replace 121 blocks beneath you with blocks of quartz.

You will see the message '121 blocks filled' appear in the lower left corner of the game window to indicate that the fill command has completed.

Build a Solid Structure

Next, let's look at how to build a solid rectangular structure. Since we are filling a solid structure, we want to make sure that the region is not where we are standing, otherwise we will be stuck inside the fill region.

If we avoid combining negative and positive coordinates (and only use positive values for the X and Z coordinates), the structure should be constructed next to us.

For example, let's fill a region next to us with blocks of redstone with the following command:

Type the command in the chat window and press the Enter key to run the command.

This /fill command would fill a solid structure of 1100 blocks of redstone right beside us.

You will see the message '1100 blocks filled' appear in the lower left corner of the game window to indicate that the fill command has completed.

This is a very fast way to build a tower or other large solid structure.

Build a Hollow Structure

One of the most powerful uses of the /fill command is to build a hollow structure. This is a quick and easy way to build the frame of a house or shelter.

Fill It Game Without Javascript

Fill

For example, let's build a large hollow cobblestone structure with the following command:

Type the command in the chat window and press the Enter key to run the command.

This /fill command would build a hollow structure where the outer block is made of cobblestone and the inside of the structure is filled with air.

You will see the message '380 blocks filled' appear in the lower left corner of the game window to indicate that the fill command has completed.

Now if you break the outer layer of the structure, you can see that it is empty and hollowed out on the inside. You can then use this as the frame of your house!!

TIP: If you wanted to do this with oak wood planks, just change the Minecraft ID to planks:

A hollow oak wood plank structure would be a great frame for a house!

Mine a Large Area Instantly

One interesting feature of the /fill command is that you can use this command to quickly mine a large area as big as you want and as deep as you want.

For example, let's mine starting 10 blocks deep (-10) up to ground level (-1), that is 5 blocks away from us in all horizontal directions with the following command:

Type the command in the chat window and press the Enter key to run the command.

This /fill command would replace all blocks in the fill region, including air. The replaced blocks will be dropped and can then be collected as if they were mined with a pickaxe or shovel.

You will see the message '1210 blocks filled' appear in the lower left corner of the game window to indicate that the fill command has completed. All of the mined items would start popping up above the fill region. You can run over and pick up all of these items to add them to your inventory.

This is a great way to quickly mine diamonds, iron ore, gold ore, redstone and other valuable items!!

Fill It Game Java

The /fill command is very powerful and can be used to quickly create so many structures. Give it a try and see what you can create!

Congratulations, you have learned how to use the /fill command in Minecraft.

Other Fill Cheats

You can use other fill commands in Minecraft such as:

Other Game Commands

You can use other commands and cheats in Minecraft such as:

This chapter shows you how you can paint your own custom drawing (such as graphs, charts, drawings and, in particular, computer game avatars) because you cannot find standard GUI components that meets your requirements. I shall stress that you should try to reuse the standard GUI components as far as possible and leave custom graphics as the last resort. Nonetheless, custom graphics is crucial in game programming.

Read 'Swing Tutorial' trail 'Performing Custom Painting'.

The java.awt.Graphics Class: Graphics Context and Custom Painting

A graphics context provides the capabilities of drawing on the screen. The graphics context maintains states such as the color and font used in drawing, as well as interacting with the underlying operating system to perform the drawing. In Java, custom painting is done via the java.awt.Graphics class, which manages a graphics context, and provides a set of device-independent methods for drawing texts, figures and images on the screen on different platforms.

The java.awt.Graphics is an abstract class, as the actual act of drawing is system-dependent and device-dependent. Each operating platform will provide a subclass of Graphics to perform the actual drawing under the platform, but conform to the specification defined in Graphics.

Add This Game To Your MyArcade Page: You must be logged in to add games to your MyArcade page. If you don't have one, get one! Here's Why You Should Have a MyArcade Account: It's your own place on FreeArcade where you can be the boss. Keep a personalized page with your favorite games. Add your own description to the games you want. Fill entire 2D Array (Tetris board) with Tetris pieces, no spaces left over (Java) Ask Question Asked 6 years. What is the best way to fill the entire array with random shapes and no spaces left over. I have the game working, I'm just trying to adapt it to something different while still using the Tetris gameplay. Java arrays 2d fill.

Graphics Class' Drawing Methods

The Graphics class provides methods for drawing three types of graphical objects:

  1. Text strings: via the drawString() method. Take note that System.out.println() prints to the system console, not to the graphics screen.
  2. Vector-graphic primitives and shapes: via methods drawXxx() and fillXxx(), where Xxx could be Line, Rect, Oval, Arc, PolyLine, RoundRect, or 3DRect.
  3. Bitmap images: via the drawImage() method.

These drawing methods is illustrated below. The drawXxx() methods draw the outlines; while fillXxx() methods fill the internal. Shapes with negative width and height will not be painted. The drawImage() will be discussed later.

Graphics Class' Methods for Maintaining the Graphics Context

Fill it game without java edition

The graphic context maintains states (or attributes) such as the current painting color, the current font for drawing text strings, and the current painting rectangular area (called clip). You can use the methods getColor(), setColor(), getFont(), setFont(), getClipBounds(), setClip() to get or set the color, font, and clip area. Any painting outside the clip area is ignored.

Graphics Class' Other Methods

Graphics Coordinate System

In Java Windowing Subsystem (like most of the 2D Graphics systems), the origin (0,0) is located at the top-left corner.

EACH component/container has its own coordinate system, ranging for (0,0) to (width-1, height-1) as illustrated.

You can use method getWidth() and getHeight() to retrieve the width and height of a component/container. You can use getX() or getY() to get the top-left corner (x,y) of this component's origin relative to its parent.

Custom Painting Template

Under Swing, custom painting is usually performed by extending (i.e., subclassing) a JPanel as the drawing canvas and override the paintComponent(Graphics g) method to perform your own drawing with the drawing methods provided by the Graphics class. The Java Windowing Subsystem invokes (calls back) paintComponent(g) to render the JPanel by providing the current graphics context g, which can be used to invoke the drawing methods. The extended JPanel is often programmed as an inner class of a JFrame application to facilitate access of private variables/methods. Although we typically draw on the JPanel, you can in fact draw on any JComponent (such as JLabel, JButton).

The custom painting code template is as follows:

Dissecting the Program
  • Custom painting is performed by extending a JPanel (called DrawCanvas) and overrides the paintComponent(Graphics g) method to do your own drawing with the drawing methods provided by the Graphics class.
  • DrawCanvas is designed as an inner class of this JFrame application, so as to facilitate access of the private variables/methods.
  • Java Windowing Subsystem invokes (calls back) paintComponent(g) to render the JPanel, with the current graphics context in g, whenever there is a need to refresh the display (e.g., during the initial launch, restore, resize, etc). You can use the drawing methods (g.drawXxx() and g.fillXxx()) on the current graphics context g to perform custom painting on the JPanel.
  • The size of the JPanel is set via the setPreferredSize(). The JFrame does not set its size, but packs the components contained via pack().
  • In the main(), the constructor is called in the event-dispatch thread via static method javax.swing.SwingUtilities.invokeLater() (instead of running in the main thread), to ensure thread-safety and avoid deadlock, as recommended by the Swing developers.
(Advanced) Anonymous Inner Class for Drawing Canvas

Instead of a named-inner class called DrawCanvas in the previous example, you can also use an anonymous inner class for the drawing canvas, if the painting code is short. For example,

(Advanced) Getting the Graphics Context

You can retrieve the Graphics context of a JComponent via the getGraphics() method. This is, however, not commonly used. For example,

Custom Painting in AWT (Obsolete)

Under AWT, you can perform custom painting by extending java.awt.Canvas, and override the paint(Graphics g) method, in a java.awt.Frame application. Similarly, you can explicitly invoke repaint() to update the graphics.

Refreshing the Display via repaint()

At times, we need to explicitly refresh the display (e.g., in game and animation). We shall NOT invoke paintComponent(Graphics) directly. Instead, we invoke the JComponent's repaint() method. The Windowing Subsystem will in turn call back the paintComponent() with the current Graphics context and execute it in the event-dispatching thread for thread safety. You can repaint() a particular JComponent (such as a JPanel) or the entire JFrame. The children contained within the JComponent will also be repainted.

Colors and Fonts

java.awt.Color

The class java.awt.Color provides 13 standard colors as named-constants. They are: Color.RED, GREEN, BLUE, MAGENTA, CYAN, YELLOW, BLACK, WHITE, GRAY, DARK_GRAY, LIGHT_GRAY, ORANGE, and PINK. (In JDK 1.1, these constant names are in lowercase, e.g., red. This violates the Java naming convention for constants. In JDK 1.2, the uppercase names are added. The lowercase names were not removed for backward compatibility.)

You can use the toString() to print the RGB values of these color (e.g., System.out.println(Color.RED)):

You can also use the RGB values or RGBA value (A for alpha to specify transparency/opaque) to construct your own color via constructors:

For example:

To retrieve the individual components, you can use getRed(), getGreen(), getBlue(), getAlpha(), etc.

To set the background and foreground (text) color of a component/container, you can invoke:

To set the color of the Graphics context g (for drawing lines, shapes, and texts), use g.setColor(color):

(Advanced) JColorChooser Example

Fill It Game Without Java

This example uses the javax.swing.JColorChooser to set the background color of the JPanel.

java.awt.Font

The class java.awt.Font represents a specific font face, which can be used for rendering texts. You can use the following constructor to construct a Font instance:

You can use the setFont() method to set the current font for the Graphics context g for rendering texts. For example,

Font's Family Name vs. Font Name

A font could have many faces (or style), e.g., plain, bold or italic. All these faces have similar typographic design. The font face name, or font name for short, is the name of a particular font face, like 'Arial', 'Arial Bold', 'Arial Italic', 'Arial Bold Italic'. The font family name is the name of the font family that determines the typographic design across several faces, like 'Arial'. For example,

Logical Font vs. Physical Font

JDK supports these logical font family names: 'Dialog', 'DialogInput', 'Monospaced', 'Serif', or 'SansSerif'. JDK 1.6 provides these String constants: Font.DIALOG, Font.DIALOG_INPUT, Font.MONOSPACED, Font.SERIF, Font.SANS_SERIF.

Physical font names are actual font libraries such as 'Arial', 'Times New Roman' in the system.

GraphicsEnvironment's getAvailableFontFamilyNames() and getAllFonts()

You can use GraphicsEnvironment's getAvailableFontFamilyNames() to list all the font famiy names; and getAllFonts() to construct all Font instances (with font size of 1 pt). For example,

Font's deriveFont()

You can use Font's deriveFont() to derive a new Font instance from this Font with varying size, style and others.

For example,

(Advanced) java.awt.FontMetrics

The java.awt.FontMetrics class can be used to measure the exact width and height of the string for a particular font face, so that you can position the string as you desire (such as at the center of the screen).

To create a FontMetrics, use getFontMetrics() methods of the Graphics class, as follows:

The most commonly-used function for FontMetrics is to measure the width of a given String displayed in a certain font.

To centralize a string on the drawing canvas (e.g., JPanel):

Custom Graphics Examples

Example 1: Moving an Object via Key/Button Action

This example illustrates how to re-paint the screen in response to a KeyEvent or ActionEvent.

The display consists of two JPanel in a JFrame, arranged in BorderLayout. The top panel is used for custom painting; the bottom panel holds two JButton arranged in FlowLayout. Clicking the 'Move Right' or 'Move Left' buttons moves the line. The JFrame listens to the 'Left-arrow' and 'Right-arrow' keys, and responses by moving the line left or right.

Dissecting the Program
  • To do custom painting, you have to decide which superclass to use. It is recommended that you use a JPanel (or a more specialized Swing component such as JButton or JLabel). In this example, we extend the JPanel to do our custom painting, in an inner class, as follows:
  • The paintComponent() method is overridden to provide the custom drawing codes. We use the drawLine() method to draw a line from (x1,y1) to (x2, y2).
  • The paintComponent() method cannot be called directly from your code, because it requires a Graphics object as argument.
  • paintComponent() is a so-called 'call-back' method. The Windowing subsystem invokes this method and provides a pre-configured Graphics object to represent its state (e.g., current color, font, clip area and etc). There are two kinds of painting: system-triggered painting and application-triggered painting. In a system-trigger painting, the system request a component to render its content when the component is first made visible on the screen, or the component is resized, or the component is damaged that needs to be repaint. In an application-triggered painting, the application invokes a repaint() request. Under both cases, the Windowing subsystem will call-back the paintComponent() to render the contents of the component with a proper Graphics object as argument.
  • In this example, the application requests for a repaint() in the KeyEvent and MouseEvent handlers, which triggers the paintComponent() with an appropriate Graphics object as the argument.
  • To be precise, when you invoke the repaint() method to repaint a JComponent, the Windowing subsystem calls-backpaint() method. The paint() method then calls-back three methods: paintComponent(), paintBorder() and paintChilden().
  • In the overridden paintComponent() method, we call super.paintComponent() to paint the background of the JComponent. If this call is omitted, you must either paint the background yourself (via a fillRect() call) or use setOpaque(false) to make the JComponent transparent. This will inform Swing system to paint those JComponents behind the transparent component.
  • We choose the JFrame as the source of the KeyEvent. JFrame shall be 'in focus' when the key is pressed. The requestFocus() method (of 'this' JFrame) is invoked to request for the keyboard focus.

[TODO]: may need to revise.

Try

Modifying the program to move a ball in response to up/down/left/right buttons, as well as the 4 arrow and 'wasd' keys , as shown:

Example 2: Moving Sprites

In game programming, we have moving game objects called sprites. Each sprite is usually modeled in its own class, with its own properties, and it can paint itself.

Sprite.java

This class models a sprite, with its own properties, and it can paint itself via the paint() method provided given a Graphics context. A rectangle is used here.

MoveASprite.java

Instead of repainting the entire display, we only repaint the affected areas (clips), for efficiency, via the repaint(x, y, width, height) method. In moveLeft() and moveRight(), we save the states, move the object, repaint the saved clip-area with the background color, and repaint the new clip-area occupied by the sprite. Repainting is done by asking the sprite to paint itself at the new location, and erase from the old location.

Example 3: Paint

MyPaint.java
PolyLine.java
Dissecting the Program

[TODO]

Drawing Images

javax.swing.ImageIcon

The javax.swing.ImageIcon class represents an icon, which is a fixed-size picture, typically small-size and used to decorate components. To create an ImageIcon:

Graphics Class' drawImage()

ImageIcon is fixed-in-sized and cannot be resized in display. You can use Graphics's drawImage() to resize a source image in display.

The java.awt.Graphics class declares 6 overloaded versions of abstract method drawImage().

The coordinates involved is shown in the above diagram. The ImageObserver receives notification about the Image as it is loaded. In most purposes, you can set it to null or this.

The drawImage() method requires an Image instance, which can be obtained via ImageIcon's getImage() method; or via static method ImageIO.read() (read 'Reading Images into your program'). For example,

Example

Images:

This example places absolute numbers in the draw methods, which is hard to maintain and reuse. You should define name-constants such as CELL_WIDTH, BORDER_WIDTH, etc, and compute the numbers based on these constants.

Animation

Animation using javax.swing.Timer

Creating an animation (such as a bouncing ball) requires repeatedly running an updating task at a regular interval. Swing provides a javax.swing.Timer class which can be used to fire ActionEvent to its registered ActionListeners at regular interval.

The Timer class has one constructor:

You are required to override the actionPerformed() method of the ActionListener to specify your task's behavior. The Timer fires an ActionEvent to the ActionListener after the (initial) delay, and then at regular interval after delay.

You can start and stop the Timer via the Timer's start() and stop() methods. For example,

You can use method setRepeats(false) to set the Timer to fire only once, after the delay. You can set the initial delay via setInitialDelay() and regular delay via setDelay().

A Timer can fire the ActionEvent to more than one ActionListeners. You can register more ActionListeners via the addActionListener() method.

The actionPerformed() runs on the event-dispatching thread, just like all the event handlers. You can be relieved of the multi-threading issues.

JDK 1.3 introduced another timer class called java.util.Timer, which is more general, but javax.swing.Timer is sufficient (and easier) to run animation in Swing application.

Example: A Bouncing Ball

javax.swing.Timer does not provide very accurate timing due to the overhead of event-handling. It probaly cannot be used for real-time application such as displaying a clock.

[TODO] Stop the Timer after x steps

(Advanced) Animation using a new Thread

Animation usually involves multi-threading, so that the GUI refreshing operations does not interfere with the programming logic. Multi-threading is an advanced topics. Read 'Multithreading & Concurrent Programming'

In the previous example, we use javax.swing.Timer, which run the updating task at regular interval on the event-dispatching thread. In this example, we shall create a new thread to run the update.

To create a new thread, define a (anonymous and inner) subclass of Thread and override the run() method to specify the behavior of the task. Create an instance and start the instance via the start() method, which calls back the run() defined earlier.

To ensure the new thread does not starve the other threads, in particular the event-dispatching thread, the thread shall yield control via the sleep(mills) method, which also provides the necessary delay.

  • To update the display regularly, we explicitly invoke the repaint() method of the JFrame, which will callback the paintComponent(g) of all the components contained in this JFrame.
  • The display refreshing code is run in its own thread, so as to avoid the infamous unresponsive user interface problem. It is programmed as an anonymous inner class, extends class Thread, by overriding the run() method to provide the programmed operations (i.e., repaint()). The start() method is use to start the thread, which will callback the run().
  • Inside the overridden run(), the repaint() is programmed inside an infinite loop, followed by a Thread.sleep(milliseconds) method, which suspends the thread for the given milliseconds. This operation provides the necessary delay and also yield control to other thread to perform their intended operations.

[TODO] Stopping the thread after x steps

(Advanced) A Closer Look at repaint()

Reference: 'Painting in AWT and Swing' @ http://www.oracle.com/technetwork/java/painting-140037.html. I summarize some of the important points here.

Heavyweight AWT Components vs. Lightweight Swing Components

The original AWT components are heavyweight components. 'Heavyweight' means that the component has it's own opaque native window. Heavyweight components, such as java.awt.Button, are mapped to the platform-specific components. It relies on the windowing subsystem in each native platform to take care of details such as damage detection, clip calculation, and z-ordering. On the other hand, the newer Swing JComponents (such as javax.swing.JButton) are lightweight components. A 'lightweight' component does not own its screen resources but reuses the native window of its closest heavyweight ancestor. Swing JComponents do not rely on the native platform and are written purely in Java, . The top-level containers, such as JFrame, JApplet and JDialog, which are not subclass of JComponent, remain heavyweight. It is because the lightweight Swing JComponents need to attach to a heavyweight ancestor.

Painting Mechanism

Painting is carried out via a 'call-back' mechanism. A program shall put its painting codes in a overridden method (paint() for AWT components or paintComponent() for Swing component), and the windowing subsystem will call back this method when it's time to paint.

System-triggered vs. Application-triggered Painting Requests

There are two types of paint (or repaint) requests:

  1. System-triggered: e.g., the component is first made visible, the componet is resized, etc. The windowing subsystem will schedule paint() or paintComponent() on the event-dispatching thread.
  2. Application-triggered: application has modified the appearance of the component and requested to repaint the component. However, Application shall not invoke paint() or paintComponent() directly. Instead, it shall invoke a special method called repaint(), which will in turn invoke paint() or paintComponent(). Multiple repaint() requests may be collapsed into a single paint() call.

Instead of issuing repaint()No pg hba.conf entry for host. to paint the entire component, for efficiency, you can selectively repaint a rectangular clip area. You can also specify a maximum time limit for painting to take place.

Painting the Lightweight Swing Components

A lightweight needs a heavyweight somewhere up the containment hierarchy in order to have a place to paint, as only heavyweight components have their own opaque window. When this heavyweight ancestor is asked to paint its window, it must also paint all of its lightweight descendants. This is handled by java.awt.Container's paint() method, which calls paint() on any of its visible, lightweight children which intersect with the rectangle to be painted. Hence, it is crucial for all Container subclasses (lightweight or heavyweight) that override paint() to place a super.paint() call in the paint() method. This super.paint() call invoke Container's (super) paint() method, which in turn invoke paint() on all its descendants. If the super.paint() call is missing, some of the lightweight descendants will be shown up.

Opaque and Transparent

Lightweight components does not own its opaque window and 'borrow' the screen real estate of its heavyweight ancestor. As a result, they could be made transparent, by leaving their background pixels unpainted to allow the underlying component to show through.

To improve performance of opaque components, Swing adds a property called opaque to all JComponents. If opaque is set to true, the component agrees to paint all of the pixels contained within its rectangular bounds. In order words, the windowing subsystem does not have to do anything within these bounds such as painting its ancestors. It opaque is set to false, the component makes no guarantees about painting all the bits within its rectangular bounds, and the windowing subsystem has more work to do.

Swing further factor the paint() method into three methods, which are invoked in the following order:

Swing programs should override paintComponent() instead of paint().

Most of the standard Swing components (in particular, JPanel) have their look and feel implemented by separate look-and-feel objects (called 'UI delegates') for Swing's Pluggable look and feel feature. This means that most or all of the painting for the standard components is delegated to the UI delegate and this occurs in the following way:

  1. paint() invokes paintComponent().
  2. If the ui property is non-null, paintComponent() invokes ui.update().
  3. If the component's opaque property is true, ui.udpate() fills the component's background with the background color and invokes ui.paint().
  4. ui.paint() renders the content of the component.

This means that subclasses of Swing components which have a UI delegate (such as JPanel), should invoke super.paintComponent() within their overridden paintComponent(), so that ui.update() fills the background (of the superclass such as JPanel) provided opaque is true.

Try removing the super.paintComponent() from a Swing program that does animation (e.g., bouncing ball). The background will not be painted, and the previous screen may not be cleared. You can also paint the background yourself by filling a Rectangle with background color.

Furthermore, if you set the opaque to false (via setOpaque(false)) for the subclass of JPanel, the super.paintComponent(g) does not fill the background.

REFERENCES & RESOURCES

  • 'The Swing Tutorial' @ http://docs.oracle.com/javase/tutorial/uiswing/, in particular, the section on 'Performing Custom Graphics'.
  • 'Painting in AWT and Swing' @ http://www.oracle.com/technetwork/java/painting-140037.html.