JAVA GUI

profilebhihu45
example_pizza.pdf

Sample Solution to Programming Exercise Lecture 12I

// This code defines a panel for radio buttons & check boxes

import javax.swing.*;

import javax.swing.border.*;

import java.awt.*;

public class RadioButtonExercisePanel extends JPanel

{

private JRadioButton smallPizzaButton,

mediumPizzaButton,

largePizzaButton;

private JCheckBox plainCheckBox,

sausageCheckBox,

mushroomCheckBox,

pepperoniCheckBox;

public RadioButtonExercisePanel()

{

// Create buttons

smallPizzaButton = new JRadioButton( "Small" );

mediumPizzaButton = new JRadioButton( "Medium" );

largePizzaButton = new JRadioButton( "Large" );

// Create a button group & add buttons

ButtonGroup sizeGroup = new ButtonGroup();

sizeGroup.add( smallPizzaButton );

sizeGroup.add( mediumPizzaButton );

sizeGroup.add( largePizzaButton );

// Create a button border

Border buttonBorder = BorderFactory.createEtchedBorder();

buttonBorder = BorderFactory.createTitledBorder( buttonBorder,

"Pizza Size" );

// Create a button panel & add buttons

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout( new FlowLayout( FlowLayout.LEFT ) );

buttonPanel.add( smallPizzaButton );

buttonPanel.add( mediumPizzaButton );

buttonPanel.add( largePizzaButton );

buttonPanel.setBorder( buttonBorder );

// Create check boxes

plainCheckBox = new JCheckBox( "Plain" );

sausageCheckBox = new JCheckBox( "Sausage" );

mushroomCheckBox = new JCheckBox( "Mushroom" );

pepperoniCheckBox = new JCheckBox( "Pepperoni" );

// Create a border for toppings group

Border toppingBorder = BorderFactory.createEtchedBorder();

toppingBorder = BorderFactory.createTitledBorder( toppingBorder,

"Toppings" );

// Create a toppings panel & add toppings check boxes

JPanel toppingPanel = new JPanel();

toppingPanel.setLayout( new FlowLayout( FlowLayout.LEFT ) );

toppingPanel.add( plainCheckBox );

toppingPanel.add( sausageCheckBox );

toppingPanel.add( mushroomCheckBox );

toppingPanel.add( pepperoniCheckBox );

toppingPanel.setBorder( toppingBorder );

// Add panels to main panel

this.setLayout( new BorderLayout() );

this.add( buttonPanel, BorderLayout.NORTH );

this.add( toppingPanel, BorderLayout.CENTER );

}

}

// This code displays the panel in a frame

import javax.swing.*;

public class RadioButtonExerciseFrame extends JFrame

{

public RadioButtonExerciseFrame()

{

setTitle( "Radio Button Programming Exercise" );

setSize( 300, 220 );

setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

JPanel panel = new RadioButtonExercisePanel();

this.add( panel );

}

public static void main( String [] args )

{

JFrame frame = new RadioButtonExerciseFrame();

frame.setVisible( true );

}

}