Java Tutorials Code Sample – GlassPaneDemo.java

package components;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import javax.swing.event.MouseInputAdapter;
/** An application that requires no other files. */
public class GlassPaneDemo {
    static private MyGlassPane myGlassPane;
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("GlassPaneDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Start creating and adding components.
        JCheckBox changeButton =
                new JCheckBox("Glass pane \"visible\"");
        changeButton.setSelected(false);
        
        //Set up the content pane, where the "main GUI" lives.
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new FlowLayout());
        contentPane.add(changeButton);
        contentPane.add(new JButton("Button 1"));
        contentPane.add(new JButton("Button 2"));
        //Set up the menu bar, which appears above the content pane.
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("Menu");
        menu.add(new JMenuItem("Do nothing"));
        menuBar.add(menu);
        frame.setJMenuBar(menuBar);
        //Set up the glass pane, which appears over both menu bar
        //and content pane and is an item listener on the change
        //button.
        myGlassPane = new MyGlassPane(changeButton, menuBar,
                                      frame.getContentPane());
        changeButton.addItemListener(myGlassPane);
        frame.setGlassPane(myGlassPane);
        //Show the window.
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
/**
 * We have to provide our own glass pane so that it can paint.
 */
class MyGlassPane extends JComponent
                  implements ItemListener {
    Point point;
    //React to change button clicks.
    public void itemStateChanged(ItemEvent e) {
        setVisible(e.getStateChange() == ItemEvent.SELECTED);
    }
    protected void paintComponent(Graphics g) {
        if (point != null) {
            g.setColor(Color.red);
            g.fillOval(point.x - 10, point.y - 10, 20, 20);
        }
    }
    public void setPoint(Point p) {
        point = p;
    }
    public MyGlassPane(AbstractButton aButton,
                       JMenuBar menuBar,
                       Container contentPane) {
        CBListener listener = new CBListener(aButton, menuBar,
                                             this, contentPane);
        addMouseListener(listener);
        addMouseMotionListener(listener);
    }
}
/**
 * Listen for all events that our check box is likely to be
 * interested in.  Redispatch them to the check box.
 */
class CBListener extends MouseInputAdapter {
    Toolkit toolkit;
    Component liveButton;
    JMenuBar menuBar;
    MyGlassPane glassPane;
    Container contentPane;
    public CBListener(Component liveButton, JMenuBar menuBar,
                      MyGlassPane glassPane, Container contentPane) {
        toolkit = Toolkit.getDefaultToolkit();
        this.liveButton = liveButton;
        this.menuBar = menuBar;
        this.glassPane = glassPane;
        this.contentPane = contentPane;
    }
    public void mouseMoved(MouseEvent e) {
        redispatchMouseEvent(e, false);
    }
    public void mouseDragged(MouseEvent e) {
        redispatchMouseEvent(e, false);
    }
    public void mouseClicked(MouseEvent e) {
        redispatchMouseEvent(e, false);
    }
    public void mouseEntered(MouseEvent e) {
        redispatchMouseEvent(e, false);
    }
    public void mouseExited(MouseEvent e) {
        redispatchMouseEvent(e, false);
    }
    public void mousePressed(MouseEvent e) {
        redispatchMouseEvent(e, false);
    }
    public void mouseReleased(MouseEvent e) {
        redispatchMouseEvent(e, true);
    }
    //A basic implementation of redispatching events.
    private void redispatchMouseEvent(MouseEvent e,
                                      boolean repaint) {
        Point glassPanePoint = e.getPoint();
        Container container = contentPane;
        Point containerPoint = SwingUtilities.convertPoint(
                                        glassPane,
                                        glassPanePoint,
                                        contentPane);
        if (containerPoint.y < 0) { //we're not in the content pane
            if (containerPoint.y + menuBar.getHeight() >= 0) {
                //The mouse event is over the menu bar.
                //Could handle specially.
            } else {
                //The mouse event is over non-system window
                //decorations, such as the ones provided by
                //the Java look and feel.
                //Could handle specially.
            }
        } else {
            //The mouse event is probably over the content pane.
            //Find out exactly which component it's over. 
            Component component =
                SwingUtilities.getDeepestComponentAt(
                                        container,
                                        containerPoint.x,
                                        containerPoint.y);
                            
            if ((component != null)
                && (component.equals(liveButton))) {
                //Forward events over the check box.
                Point componentPoint = SwingUtilities.convertPoint(
                                            glassPane,
                                            glassPanePoint,
                                            component);
                component.dispatchEvent(new MouseEvent(component,
                                                     e.getID(),
                                                     e.getWhen(),
                                                     e.getModifiers(),
                                                     componentPoint.x,
                                                     componentPoint.y,
                                                     e.getClickCount(),
                                                     e.isPopupTrigger()));
            }
        }
        
        //Update the glass pane if requested.
        if (repaint) {
            glassPane.setPoint(glassPanePoint);
            glassPane.repaint();
        }
    }
}
Advertisements

Java Tutorials Code Sample – FormatterFactoryDemo.java

package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.text.*;
/**
 * FormatterFactoryDemo.java requires no other files.
 */
public class FormatterFactoryDemo extends JPanel
                                  implements PropertyChangeListener {
    //Values for the text fields
    private double amount = 100000;
    private double rate = .075//7.5 %
    private int numPeriods = 30;
    //Labels to identify the fields
    private JLabel amountLabel;
    private JLabel rateLabel;
    private JLabel numPeriodsLabel;
    private JLabel paymentLabel;
    //Strings for the labels
    private static String amountString = "Loan Amount: ";
    private static String rateString = "APR (%): ";
    private static String numPeriodsString = "Years: ";
    private static String paymentString = "Monthly Payment: ";
    //Fields for data entry
    private JFormattedTextField amountField;
    private JFormattedTextField rateField;
    private JFormattedTextField numPeriodsField;
    private JFormattedTextField paymentField;
    //Formats to format and parse numbers
    private NumberFormat amountDisplayFormat;
    private NumberFormat amountEditFormat;
    private NumberFormat percentDisplayFormat;
    private NumberFormat percentEditFormat;
    private NumberFormat paymentFormat;
    public FormatterFactoryDemo() {
        super(new BorderLayout());
        setUpFormats();
        double payment = computePayment(amount,
                                        rate,
                                        numPeriods);
        //Create the labels.
        amountLabel = new JLabel(amountString);
        rateLabel = new JLabel(rateString);
        numPeriodsLabel = new JLabel(numPeriodsString);
        paymentLabel = new JLabel(paymentString);
        //Create the text fields and set them up.
        amountField = new JFormattedTextField(
                            new DefaultFormatterFactory(
                                new NumberFormatter(amountDisplayFormat),
                                new NumberFormatter(amountDisplayFormat),
                                new NumberFormatter(amountEditFormat)));
        amountField.setValue(new Double(amount));
        amountField.setColumns(10);
        amountField.addPropertyChangeListener("value", this);
        NumberFormatter percentEditFormatter =
                new NumberFormatter(percentEditFormat) {
            public String valueToString(Object o)
                  throws ParseException {
                Number number = (Number)o;
                if (number != null) {
                    double d = number.doubleValue() * 100.0;
                    number = new Double(d);
                }
                return super.valueToString(number);
            }
            public Object stringToValue(String s)
                   throws ParseException {
                Number number = (Number)super.stringToValue(s);
                if (number != null) {
                    double d = number.doubleValue() / 100.0;
                    number = new Double(d);
                }
                return number;
            }
        };
        rateField = new JFormattedTextField(
                             new DefaultFormatterFactory(
                                new NumberFormatter(percentDisplayFormat),
                                new NumberFormatter(percentDisplayFormat),
                                percentEditFormatter));
        rateField.setValue(new Double(rate));
        rateField.setColumns(10);
        rateField.addPropertyChangeListener("value", this);
        numPeriodsField = new JFormattedTextField();
        numPeriodsField.setValue(new Integer(numPeriods));
        numPeriodsField.setColumns(10);
        numPeriodsField.addPropertyChangeListener("value", this);
        paymentField = new JFormattedTextField(paymentFormat);
        paymentField.setValue(new Double(payment));
        paymentField.setColumns(10);
        paymentField.setEditable(false);
        paymentField.setForeground(Color.red);
        //Tell accessibility tools about label/textfield pairs.
        amountLabel.setLabelFor(amountField);
        rateLabel.setLabelFor(rateField);
        numPeriodsLabel.setLabelFor(numPeriodsField);
        paymentLabel.setLabelFor(paymentField);
        //Lay out the labels in a panel.
        JPanel labelPane = new JPanel(new GridLayout(0,1));
        labelPane.add(amountLabel);
        labelPane.add(rateLabel);
        labelPane.add(numPeriodsLabel);
        labelPane.add(paymentLabel);
        //Layout the text fields in a panel.
        JPanel fieldPane = new JPanel(new GridLayout(0,1));
        fieldPane.add(amountField);
        fieldPane.add(rateField);
        fieldPane.add(numPeriodsField);
        fieldPane.add(paymentField);
        //Put the panels in this panel, labels on left,
        //text fields on right.
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        add(labelPane, BorderLayout.CENTER);
        add(fieldPane, BorderLayout.LINE_END);
    }
    /** Called when a field's "value" property changes. */
    public void propertyChange(PropertyChangeEvent e) {
        Object source = e.getSource();
        if (source == amountField) {
            amount = ((Number)amountField.getValue()).doubleValue();
        } else if (source == rateField) {
            rate = ((Number)rateField.getValue()).doubleValue();
        } else if (source == numPeriodsField) {
            numPeriods = ((Number)numPeriodsField.getValue()).intValue();
        }
        double payment = computePayment(amount, rate, numPeriods);
        paymentField.setValue(new Double(payment));
    }
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("FormatterFactoryDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Add contents to the window.
        frame.add(new FormatterFactoryDemo());
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
            UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
    //Compute the monthly payment based on the loan amount,
    //APR, and length of loan.
    double computePayment(double loanAmt, double rate, int numPeriods) {
        double I, partial1, denominator, answer;
        numPeriods *= 12;        //get number of months
        if (rate > 0.001) {
            I = rate / 12.0;         //get monthly rate from annual
            partial1 = Math.pow((1 + I), (0.0 - numPeriods));
            denominator = (1 - partial1) / I;
        } else { //rate ~= 0
            denominator = numPeriods;
        }
        answer = (-1 * loanAmt) / denominator;
        return answer;
    }
    //Create and set up number formats. These objects also
    //parse numbers input by user.
    private void setUpFormats() {
        amountDisplayFormat = NumberFormat.getCurrencyInstance();
        amountDisplayFormat.setMinimumFractionDigits(0);
        amountEditFormat = NumberFormat.getNumberInstance();
        percentDisplayFormat = NumberFormat.getPercentInstance();
        percentDisplayFormat.setMinimumFractionDigits(2);
        percentEditFormat = NumberFormat.getNumberInstance();
        percentEditFormat.setMinimumFractionDigits(2);
        paymentFormat = NumberFormat.getCurrencyInstance();
    }
}

Java Tutorials Code Sample – ColorChooserDemo2.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
/*
 * ColorChooserDemo2.java requires these files:
 *   CrayonPanel.java
 *   images/red.gif
 *   images/yellow.gif
 *   images/green.gif
 *   images/blue.gif
 */
public class ColorChooserDemo2 extends JPanel
                               implements ActionListener,
                                          ChangeListener {
    public JLabel banner;
    public JColorChooser tcc;
    public ColorChooserDemo2() {
        super(new BorderLayout());
        //Set up banner to use as custom preview panel
        banner = new JLabel("Welcome to the Tutorial Zone!",
                            JLabel.CENTER);
        banner.setForeground(Color.yellow);
        banner.setBackground(Color.blue);
        banner.setOpaque(true);
        banner.setFont(new Font("SansSerif", Font.BOLD, 24));
        banner.setPreferredSize(new Dimension(100, 65));
        JPanel bannerPanel = new JPanel(new BorderLayout());
        bannerPanel.add(banner, BorderLayout.CENTER);
        bannerPanel.setBorder(BorderFactory.createTitledBorder("Banner"));
        //Set up color chooser for setting background color
        JPanel panel = new JPanel(); //use FlowLayout
        JButton bcc = new JButton("Show Color Chooser...");
        bcc.addActionListener(this);
        panel.add(bcc);
        panel.setBorder(BorderFactory.createTitledBorder(
                                "Choose Background Color"));
        //Set up color chooser for setting text color
        tcc = new JColorChooser();
        tcc.getSelectionModel().addChangeListener(this);
        tcc.setBorder(BorderFactory.createTitledBorder("Choose Text Color"));
        //Remove the preview panel
        tcc.setPreviewPanel(new JPanel());
        //Override the chooser panels with our own
        AbstractColorChooserPanel panels[] = { new CrayonPanel() };
        tcc.setChooserPanels(panels);
        tcc.setColor(banner.getForeground());
        add(bannerPanel, BorderLayout.PAGE_START);
        add(panel, BorderLayout.CENTER);
        add(tcc, BorderLayout.PAGE_END);
    }
    public void actionPerformed(ActionEvent e) {
        Color newColor = JColorChooser.showDialog(
                                       ColorChooserDemo2.this,
                                       "Choose Background Color",
                                       banner.getBackground());
        if (newColor != null) {
            banner.setBackground(newColor);
        }
    }
    public void stateChanged(ChangeEvent e) {
        Color newColor = tcc.getColor();
        banner.setForeground(newColor);
    }
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ColorChooserDemo2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        JComponent newContentPane = new ColorChooserDemo2();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Java Tutorials Code Sample – Converter.java

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Converter {
    ConversionPanel metricPanel, usaPanel;
    Unit[] metricDistances = new Unit[3];
    Unit[] usaDistances = new Unit[4];
    final static boolean MULTICOLORED = false;
    //Specify the look and feel to use.  Valid values:
    //null (use the default), "Metal", "System", "Motif", "GTK+"
    final static String LOOKANDFEEL = null;
    ConverterRangeModel dataModel = new ConverterRangeModel();
    JPanel mainPane;
    /**
     * Create the ConversionPanels (one for metric, another for U.S.).
     * I used "U.S." because although Imperial and U.S. distance
     * measurements are the same, this program could be extended to
     * include volume measurements, which aren't the same.
     */
    public Converter() {
        //Create Unit objects for metric distances, and then
        //instantiate a ConversionPanel with these Units.
        metricDistances[0] = new Unit("Centimeters", 0.01);
        metricDistances[1] = new Unit("Meters", 1.0);
        metricDistances[2] = new Unit("Kilometers", 1000.0);
        metricPanel = new ConversionPanel(this, "Metric System",
                                          metricDistances,
                                          dataModel);
        //Create Unit objects for U.S. distances, and then
        //instantiate a ConversionPanel with these Units.
        usaDistances[0] = new Unit("Inches", 0.0254);
        usaDistances[1] = new Unit("Feet", 0.305);
        usaDistances[2] = new Unit("Yards", 0.914);
        usaDistances[3] = new Unit("Miles", 1613.0);
        usaPanel = new ConversionPanel(this, "U.S. System",
                                       usaDistances,
                                       new FollowerRangeModel(dataModel));
        //Create a JPanel, and add the ConversionPanels to it.
        mainPane = new JPanel();
        mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.PAGE_AXIS));
        if (MULTICOLORED) {
            mainPane.setOpaque(true);
            mainPane.setBackground(new Color(255, 0, 0));
        }
        mainPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
        mainPane.add(metricPanel);
        mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
        mainPane.add(usaPanel);
        mainPane.add(Box.createGlue());
        resetMaxValues(true);
    }
    public void resetMaxValues(boolean resetCurrentValues) {
        double metricMultiplier = metricPanel.getMultiplier();
        double usaMultiplier = usaPanel.getMultiplier();
        int maximum = ConversionPanel.MAX;
        if (metricMultiplier > usaMultiplier) {
            maximum = (int)(ConversionPanel.MAX *
                      (usaMultiplier/metricMultiplier));
        }
        dataModel.setMaximum(maximum);
        if (resetCurrentValues) {
            dataModel.setDoubleValue(maximum);
        }
    }
    private static void initLookAndFeel() {
        String lookAndFeel = null;
        if (LOOKANDFEEL != null) {
            if (LOOKANDFEEL.equals("Metal")) {
                lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
            } else if (LOOKANDFEEL.equals("System")) {
                lookAndFeel = UIManager.getSystemLookAndFeelClassName();
            } else if (LOOKANDFEEL.equals("Motif")) {
                lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
            } else if (LOOKANDFEEL.equals("GTK+")) { //new in 1.4.2
                lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
            } else {
                System.err.println("Unexpected value of LOOKANDFEEL specified: "
                                   + LOOKANDFEEL);
                lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
            }
            try {
                UIManager.setLookAndFeel(lookAndFeel);
            } catch (ClassNotFoundException e) {
                System.err.println("Couldn't find class for specified look and feel:"
                                   + lookAndFeel);
                System.err.println("Did you include the L&F library in the class path?");
                System.err.println("Using the default look and feel.");
            } catch (UnsupportedLookAndFeelException e) {
                System.err.println("Can't use the specified look and feel ("
                                   + lookAndFeel
                                   + ") on this platform.");
                System.err.println("Using the default look and feel.");
            } catch (Exception e) {
                System.err.println("Couldn't get specified look and feel ("
                                   + lookAndFeel
                                   + "), for some reason.");
                System.err.println("Using the default look and feel.");
                e.printStackTrace();
            }
        }
    }
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Set the look and feel.
        initLookAndFeel();
        //Create and set up the window.
        JFrame frame = new JFrame("Converter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        Converter converter = new Converter();
        converter.mainPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(converter.mainPane);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Swing layouts

A Visual Guide to Swing Components (Java Look and Feel)

This page shows Swing components in the Java look and feel. The following page shows the same components in the windows look and feel

Basic Controls

Simple components that are used primarily to get input from the user; they may also show simple state.

Button image

JButton

CheckBox image

JCheckBox

Combo box image

JComboBox

List image

JList

Menu image

JMenu

Radio Button image

JRadioButton

Slider image

JSlider

Spinner image

JSpinner

Text field image

JTextField

Password field image

JPasswordField

Interactive Displays of Highly Formatted Information

These components display highly formatted information that (if you choose) can be modified by the user.

Color Chooser Image

JColorChooser

Text pane Image

JEditorPane

File Chooser Image

JFileChooser

Table Image

JTable

Text Image

JTextArea

Tree Image

JTree

Uneditable Information Displays

These components exist solely to give the user information.

Label image

JLabel

Progress bar image

JProgressBar

Separator image

JSeparator

Tool tip image

JToolTip

Top-Level Containers

At least one of these components must be present in any Swing application.

Applet image

JApplet

Dialog image

JDialog

Frame image

JFrame

General-Purpose Containers

These general-purpose containers are used in most Swing applications.

Panel image

JPanel

Scroll pane image

JScrollPane

Split pane image

JSplitPane

Tabbed pane image

JTabbedPane

ToolBar image

JToolBar

Special-Purpose Containers

These special-purpose containers play specific roles in the UI.

Internal frame image

JInternalFrame

Layered pane image

JLayeredPane

Root pane image

Lists and Combo Boxes

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Lister {
public static void main(String[] args) {
JFrame f = new JFrame(“Lister v1.0”);
f.setSize(200, 200);
f.setLocation(200, 200);
f.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent we) { System.exit(0); }
});

// create a combo box
// Made By Ajinkya Choube
String [] items = { “uno”, “due”, “tre”, “quattro”, “cinque”,
“sei”, “sette”, “otto”, “nove”, “deici”,
“undici”, “dodici” };
JComboBox comboBox = new JComboBox(items);
comboBox.setEditable(true);

// create a list with the same data model
final JList list = new JList(comboBox.getModel( ));

// create a button; when it’s pressed, print out
// the selection in the list
JButton button = new JButton(“Per favore”);
button.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ae) {
Object[] selection = list.getSelectedValues( );
System.out.println(“—–“);
for (int i = 0; i < selection.length; i++)
System.out.println(selection[i]);
}
});

// put the controls the content pane
Container c = f.getContentPane( );
JPanel comboPanel = new JPanel( );
comboPanel.add(comboBox);
c.add(comboPanel, BorderLayout.NORTH);
c.add(new JScrollPane(list), BorderLayout.CENTER);
c.add(button, BorderLayout.SOUTH);

f.setVisible(true);
}
}

Checkboxes and Radio Buttons

//Made By Ajinkya Choube
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class DriveThrough {
public static void main(String[] args) {
JFrame f = new JFrame(“Lister v1.0”);
f.setSize(300, 150);
f.setLocation(200, 200);
f.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent we) { System.exit(0); }
});

JPanel entreePanel = new JPanel( );
final ButtonGroup entreeGroup = new ButtonGroup( );
JRadioButton radioButton;
entreePanel.add(radioButton = new JRadioButton(“Beef”));
radioButton.setActionCommand(“Beef”);
entreeGroup.add(radioButton);
entreePanel.add(radioButton = new JRadioButton(“Chicken”));
radioButton.setActionCommand(“Chicken”);
entreeGroup.add(radioButton);
entreePanel.add(radioButton = new JRadioButton(“Veggie”, true));
radioButton.setActionCommand(“Veggie”);
entreeGroup.add(radioButton);

final JPanel condimentsPanel = new JPanel( );
condimentsPanel.add(new JCheckBox(“Ketchup”));
condimentsPanel.add(new JCheckBox(“Mustard”));
condimentsPanel.add(new JCheckBox(“Pickles”));

JPanel orderPanel = new JPanel( );
JButton orderButton = new JButton(“Place Order”);
orderPanel.add(orderButton);

Container content = f.getContentPane( );
content.setLayout(new GridLayout(3, 1));
content.add(entreePanel);
content.add(condimentsPanel);
content.add(orderPanel);

orderButton.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ae) {
String entree =
entreeGroup.getSelection().getActionCommand( );
System.out.println(entree + ” sandwich”);
Component[] components = condimentsPanel.getComponents( );
for (int i = 0; i < components.length; i++) {
JCheckBox cb = (JCheckBox)components[i];
if (cb.isSelected( ))
System.out.println("With " + cb.getText( ));
}
}
});

f.setVisible(true);
}
}

Picture Button

//*Made By: Ajinkya Choube*//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PictureButton extends JFrame {

public PictureButton( ) {
super(“PictureButton v1.0”);
setSize(200, 200);
setLocation(200, 200);

Icon icon = new ImageIcon(“rhino.gif”);
JButton button = new JButton(icon);
button.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ae) {
System.out.println(“Urp!”);
}
});

Container content = getContentPane( );
content.setLayout(new FlowLayout( ));
content.add(button);
}

public static void main(String[] args) {
JFrame f = new PictureButton( );
f.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent we) { System.exit(0); }
});
f.setVisible(true);
}
}

The example creates an ImageIcon from the rhino.gif file. Then a JButton is created from the ImageIcon. The whole thing is displayed in a JFrame. This example also shows the idiom of using an anonymous inner class as an ActionListener.

RangeFilter.java

public class RangeFilter {
public static void main(String[] args) {

// read in two command-line arguments
int lo = Integer.parseInt(args[0]);
int hi = Integer.parseInt(args[1]);

// repeat as long as there’s more input to read in
while (!StdIn.isEmpty()) {

// read in the next integer
int t = StdIn.readInt();

// print out the given integer if it’s between lo and hi
if (t >= lo && t <= hi) {
StdOut.print(t + " ");
}
}
StdOut.println();
}
}