|
Two examples illustrating the usage of JFrame and JPanel classes |
|
|
This Java tip differantiates between the functionalities of JFrame and JPanel
classes with the help of two examples. A JFrame object is the physical window
that you'll be working with in the Swing API. Developers may know that there is a
need to add a JPanel to the JFrame's contentpane before adding components to
the JFrame.
import java.awt.*;
import javax.swing.*;
public class CustomPanel extends JPanel {
public final static int CIRCLE = 1, SQUARE = 2;
private int shape;
public void paintComponent( Graphics g )
{
super.paintComponent( g );
if ( shape == CIRCLE )
g.fillOval( 50, 10, 60, 60 );
else if ( shape == SQUARE )
g.fillRect( 50, 10, 60, 60 );
}
public void draw( int s )
{
shape = s;
repaint();
}
}
// Using a customized Panel object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CustomPanelTest extends JFrame {
private JPanel buttonPanel;
private CustomPanel myPanel;
private JButton circle, square;
public CustomPanelTest()
{
super( "CustomPanel Test" );
myPanel = new CustomPanel(); // instantiate canvas
myPanel.setBackground( Color.green );
square = new JButton( "Square" );
square.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
myPanel.draw( CustomPanel.SQUARE );
}
}
);
circle = new JButton( "Circle" );
circle.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
myPanel.draw( CustomPanel.CIRCLE );
}
}
);
buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout( 1, 2 ) );
buttonPanel.add( circle );
buttonPanel.add( square );
Container c = getContentPane();
c.add( myPanel, BorderLayout.CENTER );
c.add( buttonPanel, BorderLayout.SOUTH );
setSize( 300, 150 );
show();
}
public static void main( String args[] )
{
CustomPanelTest app = new CustomPanelTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.