setColor( Color.BLUE )
The method selects a color from many choices in class Color
. The color remains in effect until changed.
The above image shows a JFrame
that contains a JPanel
.
The panel has a white background (set in the constructor).
Here is the program:
import javax.swing.*; import java.awt.* ; import java.lang.Math ; class SnowFlakePanel extends JPanel { public SnowFlakePanel() { setPreferredSize( new Dimension(400, 400) ); setBackground( Color.WHITE ); } public void paintComponent ( Graphics gr ) { int width = getWidth(); int height = getHeight(); super.paintComponent( gr ); gr.setColor( Color.BLUE ); gr.drawLine( 0, 0, width-1, height-1 ); } } public class SnowFlakeClear { public static void main ( String[] args ) { JFrame frame = new JFrame( "Snowflake Clear" ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.getContentPane().add( new SnowFlakePanel() ); frame.pack(); frame.setVisible( true ); } }
Copy the program into a programming editor and save to a file SnowFlakeClear.java
.
If you compile and run it, you should get the above figure.
(Or, if you want, save each class to a separate file.)
Details: (Skip if you don't need a review.)
JFrame frame = new JFrame( "Snowflake Clear" );
This create a newJFrame
, which is the window which contains the graphics for the program. TheJFrame
has a title bar (as specified in the constructor) snd small buttons for minimizing, maximizing, and closing.
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
This says what to do when the small close button is clicked. In this case, the program will exit.
frame.getContentPane().add( new SnowFlakePanel() );
The content pane is the part of the frame that holds graphics.getContentPane()
returns a reference to it. Thenadd()
can add and object to it. The object added here is a subclass ofJPanel
defined in our code.
frame.pack();
This adjusts the size of the frame to fit the panel that is in it. If you forget this your code will run but you will see nothing.
frame.setVisible( true );
This asks for the frame and its contents to be displayed. Again, if you forget to include this, you will see nothing.
(Review: ) What is a subclass of a Java class?