Yes. For example, if you double the resolution of the monitor in terms of the number of pixels it displays horizontally and vertically, the rectangle will be half the previous size.
JPanel
Here is a program that creates a JFrame
, creates a JPanel
, and adds the panel to the frame.
Everytime the frame is painted a diagonal line is drawn on the panel.
The frame is painted whenever the monitor screen needs to be updated,
for instance, when the frame is moved or resized with the mouse.
import javax.swing.*; import java.awt.* ; class DemoPanel extends JPanel { public DemoPanel() { setPreferredSize( new Dimension(400, 300) ); 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 TestPanel { public static void main ( String[] args ) { JFrame frame = new JFrame( "Test Panel" ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.getContentPane().add( new DemoPanel() ); frame.pack(); frame.setVisible( true ); } }
This line from main()
:
frame.getContentPane().add( new DemoPanel() );
constructs a new DemoPanel
(which is a subclass of JPanel
) and adds it to the content pane of the window.
The content pane is the part of a JFrame
that holds the visible components.
The add()
method adds components to it.
The pack()
method makes the frame the right size to hold its contents at or above their preferred sizes.
In our program, the frame holds just one component so the frame will be sized to hold it snuggly.
The frame will be big enough to hold the JPanel
and the buttons and borders of the frame.
Examine the code. Does DemoPanel
have a constructor?