Contents

  1. ./examples/ButtonPanel.java
  2. ./examples/CardLayoutDemo.java
  3. ./examples/CardLayoutExample.java
  4. ./examples/ColoredBackground2.java
  5. ./examples/ColoredBackground.java
  6. ./examples/ColoredBackgroundRefactored.java
  7. ./examples/ColoredBackgroundSelfListener.java
  8. ./examples/ColorJPanel.java
  9. ./examples/FlexibleLayout.java
  10. ./examples/ListFonts.java
  11. ./examples/MyFrame.java
  12. ./examples/OneButtonJFrame.java
  13. ./examples/PanelWithButtons.java
  14. ./examples/ThreeButtonsFrame.java

./examples/ButtonPanel.java 1/14

[
top][prev][next]
package examples;

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * Example of creating three buttons within a JFrame, which uses a BorderLayout
 * by default. Note what happens when you add the buttons to the frame.
 * 
 * @author CSCI209
 */
@SuppressWarnings("serial")
public class ButtonPanel extends JFrame {

	public ButtonPanel() {
		super();
		setTitle("My Buttons");
		
		JButton button1 = new JButton("one");
		JButton button2 = new JButton("two");
		JButton button3 = new JButton("three");

		getContentPane().add(button1);
		getContentPane().add(button2);
		getContentPane().add(button3);

		pack();
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ButtonPanel myframe = new ButtonPanel();
	}

}

./examples/CardLayoutDemo.java 2/14

[
top][prev][next]
/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package examples;

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

/**
 * Example of using CardLayout and using a non-default look-and-feel (Metal)
 * 
 * @author Oracle
 * @author Sara Sprenkle, updated code to Java 7, changed some names, added
 *         documentation
 * 
 */
public class CardLayoutDemo implements ItemListener {
	JPanel cards; // a panel that uses CardLayout
	final static String BUTTONPANEL = "Card with JButtons";
	final static String TEXTPANEL = "Card with JTextField";

	public void addComponentToPane(Container pane) {
		// Put the JComboBox in a JPanel to get a nicer look.
		JPanel comboBoxPane = new JPanel(); // use FlowLayout
		String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
		JComboBox<String> cb = new JComboBox<>(comboBoxItems);
		cb.setEditable(false);
		cb.addItemListener(this);
		comboBoxPane.add(cb);

		// Create the "cards".
		JPanel card1 = new JPanel();
		card1.add(new JButton("Button 1"));
		card1.add(new JButton("Button 2"));
		card1.add(new JButton("Button 3"));

		JPanel card2 = new JPanel();
		card2.add(new JTextField("TextField", 20));

		// Create the panel that contains the "cards".
		cards = new JPanel(new CardLayout());
		cards.add(card1, BUTTONPANEL);
		cards.add(card2, TEXTPANEL);

		pane.add(comboBoxPane, BorderLayout.PAGE_START);
		pane.add(cards, BorderLayout.CENTER);
	}

	public void itemStateChanged(ItemEvent evt) {
		CardLayout cl = (CardLayout) (cards.getLayout());
		cl.show(cards, (String) evt.getItem());
	}

	/**
	 * 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("Card Layout Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Create and set up the content pane.
		CardLayoutDemo demo = new CardLayoutDemo();
		demo.addComponentToPane(frame.getContentPane());

		// Display the window.
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		/* Use an appropriate Look and Feel */
		try {
			UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
		} catch (UnsupportedLookAndFeelException ex) {
			ex.printStackTrace();
		} catch (IllegalAccessException ex) {
			ex.printStackTrace();
		} catch (InstantiationException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}
		// Turn off metal's use of bold fonts
		UIManager.put("swing.boldMetal", Boolean.FALSE);

		createAndShowGUI();

		// Alternatively: schedule a job for the event dispatch thread:
		// creating and showing this application's GUI.
		/*
		 * javax.swing.SwingUtilities.invokeLater(new Runnable() { public void
		 * run() { createAndShowGUI(); } });
		 */
	}
}

./examples/CardLayoutExample.java 3/14

[
top][prev][next]
package examples;

/*
 * These classes demonstrate a variety of GUI components/ideas
 */

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/**
 * This class that will act as the base for other panels for the CardLayout.
 * 
 * Revised by Sara Sprenkle to demonstrate additional functionality and made
 * minor comments and naming changes.
 * 
 * @see http
 *      ://stackoverflow.com/questions/9424642/java-swing-card-layout-change-
 *      the-displayed-panel
 */
public class CardLayoutExample {
	private static final String CARD_JBUTTON = "Card JButton";
	private static final String CARD_JTEXTFIELD = "Card JTextField";
	private static final String CARD_JRADIOBUTTON = "Card JRadioButton";

	private static void createAndShowGUI() {
		JFrame frame = new JFrame("Card Layout Example");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLocationRelativeTo(null);

		// This JPanel is the base for CardLayout for other JPanels.
		final JPanel contentPane = new JPanel();
		contentPane.setLayout(new CardLayout(20, 20));

		/*
		 * Here we be making objects of the Window Series classes so that, each
		 * one of them can be added to the JPanel having CardLayout.
		 */
		Window1 win1 = new Window1();
		contentPane.add(win1, CARD_JBUTTON);
		Window2 win2 = new Window2();
		contentPane.add(win2, CARD_JTEXTFIELD);
		Window3 win3 = new Window3();
		contentPane.add(win3, CARD_JRADIOBUTTON);

		/*
		 * We need two JButtons to go to the next Card or come back to the
		 * previous Card, as and when desired by the User.
		 */
		JPanel buttonPanel = new JPanel();
		final JButton previousButton = new JButton("PREVIOUS");
		previousButton.setOpaque(true);
		previousButton.setBackground(Color.PINK);
		previousButton.setForeground(Color.BLACK);
		final JButton nextButton = new JButton("NEXT");
		nextButton.setOpaque(true);
		nextButton.setBackground(Color.PINK);
		nextButton.setForeground(Color.BLACK);
		buttonPanel.add(previousButton);
		buttonPanel.add(nextButton);

		/*
		 * Adding the ActionListeners to the JButton, so that the user can see
		 * the next Card or come back to the previous Card, as desired.
		 */
		previousButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				CardLayout cardLayout = (CardLayout) contentPane.getLayout();
				cardLayout.previous(contentPane);
			}
		});
		nextButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				CardLayout cardLayout = (CardLayout) contentPane.getLayout();
				cardLayout.next(contentPane);
			}
		});

		// Adding the contentPane (JPanel) and buttonPanel to JFrame.
		frame.add(contentPane, BorderLayout.CENTER);
		frame.add(buttonPanel, BorderLayout.PAGE_END);

		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}
}

/**
 * Here this is our first Card of CardLayout, which will be added to the
 * contentPane object of JPanel, which has the LayoutManager set to CardLayout.
 * This card consists of two JButtons.
 */
@SuppressWarnings("serial")
class Window1 extends JPanel {

	private ActionListener action;

	public Window1() {
		init();
	}

	private void init() {
		final JButton clickButton = new JButton("CLICK ME");
		final JButton dontClickButton = new JButton("DON'T CLICK ME");

		action = new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				if (ae.getSource() == clickButton) {
					JOptionPane.showMessageDialog(null, "Hello there, dude!",
							"Right Button", JOptionPane.INFORMATION_MESSAGE);
				} else if (ae.getSource() == dontClickButton) {
					JOptionPane.showMessageDialog(null,
							"I told you not to click me!", "Wrong Button",
							JOptionPane.PLAIN_MESSAGE);
				}
			}
		};

		clickButton.addActionListener(action);
		dontClickButton.addActionListener(action);

		add(clickButton);
		add(dontClickButton);
	}
}

/**
 * Here this is our second Card of CardLayout, which will be added to the
 * contentPane object of JPanel, which has the LayoutManager set to CardLayout.
 * This card consists of a JLabel and a JTextField with GridLayout.
 */
@SuppressWarnings("serial")
class Window2 extends JPanel implements ActionListener {
	private JTextField textField;

	public Window2() {
		init();
	}

	private void init() {
		setLayout(new GridLayout(1, 2));
		JLabel userLabel = new JLabel("Your Name: ");
		textField = new JTextField();
		textField.addActionListener(this);

		add(userLabel);
		add(textField);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (textField.getDocument().getLength() > 0)
			JOptionPane.showMessageDialog(null,
					"Your Name is " + textField.getText(), "User's Name: ",
					JOptionPane.QUESTION_MESSAGE);
	}
}

/**
 * Here this is our third Card of CardLayout, which will be added to the
 * contentPane object of JPanel, which has the LayoutManager set to CardLayout.
 * This card consists of Two JLabels and two JCheckBox with GridLayout.
 */
@SuppressWarnings("serial")
class Window3 extends JPanel {

	public Window3() {
		init();
	}

	public void init() {
		setLayout(new GridLayout(2, 2));

		// ButtonGroup handles that only one radio button is selected at a time.
		final ButtonGroup genderButtonGroup = new ButtonGroup();

		JLabel maleLabel = new JLabel("MALE", JLabel.CENTER);
		final JRadioButton maleButton = new JRadioButton();
		JLabel femaleLabel = new JLabel("FEMALE", JLabel.CENTER);
		final JRadioButton femaleButton = new JRadioButton();

		genderButtonGroup.add(maleButton);
		genderButtonGroup.add(femaleButton);

		maleButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null,
						"Congrats, you are a male!", "Gender: ",
						JOptionPane.INFORMATION_MESSAGE);
			}

		});

		femaleButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ae) {
				JOptionPane.showMessageDialog(null,
						"Congrats, you are a female!", "Gender: ",
						JOptionPane.INFORMATION_MESSAGE);
			}
		});

		add(maleLabel);
		add(maleButton);
		add(femaleLabel);
		add(femaleButton);
	}
}

./examples/ColoredBackground2.java 4/14

[
top][prev][next]
package examples;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * When a button is pressed, it colors the background of the panel the
 * appropriate color.
 * 
 * Uses a separate class to update the background; passes in the frame as a parameter
 * 
 * @author sarasprenkle
 * 
 */
@SuppressWarnings("serial")
public class ColoredBackground2 extends JFrame {

	public ColoredBackground2() {
		setTitle("Colored Background - Separate class");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container cp = getContentPane();
		cp.setLayout(new FlowLayout());

		// create buttons and add to content pane
		JButton red = new JButton("Red");
		red.setForeground(Color.red);

		JButton green = new JButton("Green");
		green.setForeground(Color.GREEN);

		JButton blue = new JButton("Blue");
		blue.setForeground(Color.blue);

		ColorAction greenAction = new ColorAction(Color.green, this);
		ColorAction blueAction = new ColorAction(Color.blue, this);
		ColorAction redAction = new ColorAction(Color.red, this);

		green.addActionListener(greenAction);
		blue.addActionListener(blueAction);
		red.addActionListener(redAction);

		cp.add(green);
		cp.add(red);
		cp.add(blue);

		pack();
		setVisible(true);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ColoredBackground2 cb = new ColoredBackground2();
	}

}

/**
 * This class could (maybe *should*) go in its own file.
 * 
 */
class ColorAction implements ActionListener {
	private Color backgroundColor;
	private JFrame frame;

	public ColorAction(Color c, JFrame frame) {
		backgroundColor = c;
		this.frame = frame;
	}

	public void actionPerformed(ActionEvent evt1) {
		frame.getContentPane().setBackground(backgroundColor);
	}

}

./examples/ColoredBackground.java 5/14

[
top][prev][next]
package examples;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * When a button is pressed, it colors the background of the panel the
 * appropriate color.
 * 
 * Uses an inner class.
 * 
 * @author Sara Sprenkle
 * 
 */
@SuppressWarnings("serial")
public class ColoredBackground extends JFrame {

	public ColoredBackground() {
		setTitle("Colored Background - Inner Class");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container cp = getContentPane();
		cp.setLayout(new FlowLayout());
		setBackground(Color.BLACK);

		// create buttons and add to content pane
		JButton red = new JButton("Red");
		red.setForeground(Color.red);

		JButton green = new JButton("Green");
		green.setForeground(Color.GREEN);

		JButton blue = new JButton("Blue");
		blue.setForeground(Color.blue);

		ColorAction greenAction = new ColorAction(Color.green);
		ColorAction blueAction = new ColorAction(Color.blue);
		ColorAction redAction = new ColorAction(Color.red);

		green.addActionListener(greenAction);
		blue.addActionListener(blueAction);
		red.addActionListener(redAction);

		cp.add(green);
		cp.add(red);
		cp.add(blue);

		pack();
		setVisible(true);
	}

	/**
	 * Example of inner class that does event handling
	 * 
	 */
	private class ColorAction implements ActionListener {
		private Color backgroundColor;

		public ColorAction(Color c) {
			backgroundColor = c;
		}

		public void actionPerformed(ActionEvent evt1) {
			// ColorAction does not have a getContentPane() method
			// but ColorBackground/JFrame does
			getContentPane().setBackground(backgroundColor);
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ColoredBackground cb = new ColoredBackground();
	}

}

./examples/ColoredBackgroundRefactored.java 6/14

[
top][prev][next]
package examples;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * When a button is pressed, it colors the background of the panel the
 * appropriate color.
 * <p>
 * Demonstrates using an anonymous inner class
 * 
 * @author Sara Sprenkle
 * 
 */
@SuppressWarnings("serial")
public class ColoredBackgroundRefactored extends JFrame {

	public ColoredBackgroundRefactored() {
		setTitle("Colored Background - Anonymous Inner Class");
		setBackground(Color.white);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		Container cp = getContentPane();
		cp.setLayout(new FlowLayout());

		// create buttons and add to content pane
		makeButton("Green", Color.green);
		makeButton("Blue", Color.blue);
		makeButton("Red", Color.red);

		pack();
		setVisible(true);
	}

	/**
	 * Make a button with the given label. Pressing the button will make the
	 * panel background the given background color.
	 * 
	 * @param label
	 * @param backgroundColor
	 */
	private void makeButton(String label, final Color backgroundColor) {
		JButton button = new JButton(label);
		button.setForeground(backgroundColor);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				getContentPane().setBackground(backgroundColor);
			}
		});
		getContentPane().add(button);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ColoredBackgroundRefactored cb = new ColoredBackgroundRefactored();
	}

}

./examples/ColoredBackgroundSelfListener.java 7/14

[
top][prev][next]
package examples;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * When a button is pressed, it colors the background of the panel the
 * appropriate color.
 * 
 * The JFrame listens to its button's actions
 * 
 * @author Sara Sprenkle
 * 
 */
@SuppressWarnings("serial")
public class ColoredBackgroundSelfListener extends JFrame implements
		ActionListener {

	private JButton blue;
	private JButton green;
	private JButton red;

	public ColoredBackgroundSelfListener() {
		setTitle("Colored Background - Self-Listener");
		setBackground(Color.white);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container cp = getContentPane();
		cp.setLayout(new FlowLayout());

		// create buttons and add to content pane
		red = new JButton("Red");
		red.setForeground(Color.red);
		red.addActionListener(this);

		green = new JButton("Green");
		green.setForeground(Color.GREEN);
		green.addActionListener(this);

		blue = new JButton("Blue");
		blue.setForeground(Color.blue);
		blue.addActionListener(this);

		cp.add(red);
		cp.add(green);
		cp.add(blue);

		pack();
		setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		// needs to determine source
		Object source = event.getSource();
		if (source == blue) {
			getContentPane().setBackground(Color.blue);
		} else if (source == red) {
			getContentPane().setBackground(Color.red);
		} else if (source == green) {
			getContentPane().setBackground(Color.green);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ColoredBackgroundSelfListener cb = new ColoredBackgroundSelfListener();
	}

}

./examples/ColorJPanel.java 8/14

[
top][prev][next]
package examples;

import java.awt.Graphics;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * Demonstrates use of colors and drawing on a panel.
 * 
 */
@SuppressWarnings("serial")
public class ColorJPanel extends JPanel {

	public void paintComponent(Graphics g) {
		// draw rectangles and Strings in different colors

		super.paintComponent(g); // call superclass's paintComponent

		this.setBackground(Color.WHITE);

		// set new drawing color using integers
		g.setColor(new Color(255, 0, 0)); // would be better to extract the
											// color as a local variable: easier
											// to understand code.
		g.fillRect(15, 25, 100, 20);
		g.drawString("Current RGB: " + g.getColor(), 130, 40);

		// set new drawing color using floats
		g.setColor(new Color(0.50f, 0.75f, 0.0f));
		g.fillRect(15, 50, 100, 20);
		g.drawString("Current RGB: " + g.getColor(), 130, 65);

		// set new drawing color using static Color objects
		g.setColor(Color.BLUE);
		g.fillRect(15, 75, 100, 20);
		g.drawString("Current RGB: " + g.getColor(), 130, 90);

		// display individual RGB values
		Color color = Color.MAGENTA;
		g.setColor(color);
		g.fillRect(15, 100, 100, 20);
		g.drawString("RGB values: " + color.getRed() + ", " +

		color.getGreen() + ", " + color.getBlue(), 130, 115);

	}

	public static void main(String args[]) {
		// create frame for ColorJPanel
		JFrame frame = new JFrame("Using colors");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		ColorJPanel colorJPanel = new ColorJPanel(); // create ColorJPanel
		frame.add(colorJPanel); // add colorJPanel to frame
		frame.setSize(500, 180); // set frame size
		frame.setVisible(true); // display frame

	}

}

/*******************************************************************************
 * 
 * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and Pearson Education,
 * Inc. All Rights Reserved. Modified by SES for CSCI209
 ******************************************************************************/


./examples/FlexibleLayout.java 9/14

[
top][prev][next]
package examples;

import javax.swing.*;

import java.awt.*;

/**
 * Demonstrates how to create a flexible of layout
 * 
 * @author Sara Sprenkle
 */
public class FlexibleLayout {

	public static void main(String args[]) {
		JFrame frame = new JFrame();
		frame.setTitle("Demonstrate Layout Flexibility");

		Container contentPane = frame.getContentPane();

		// create labels for each of the parts of the pane;
		// set the background colors so you can see how much space the label
		// takes up.

		JLabel north = new JLabel("North", JLabel.CENTER);
		north.setOpaque(true);
		north.setBackground(Color.ORANGE);

		JLabel west = new JLabel("West", JLabel.CENTER);
		west.setOpaque(true);
		west.setBackground(Color.CYAN);

		JLabel east = new JLabel("East", JLabel.CENTER);
		east.setOpaque(true);
		east.setBackground(Color.MAGENTA);

		contentPane.add(north, BorderLayout.NORTH);
		contentPane.add(west, BorderLayout.WEST);
		contentPane.add(east, BorderLayout.EAST);

		// create buttons and add to button panel
		Button b1 = new Button("One!");
		Button b2 = new Button("a-Two!");
		Button b3 = new Button("a-Three!");

		JPanel buttonPanel = new JPanel();

		// add the buttons to the new JPanel
		// this will use the default flow layout manager
		buttonPanel.add(b1);
		buttonPanel.add(b2);
		buttonPanel.add(b3);

		// add the panel to the South part of the JFrame content pane
		contentPane.add(buttonPanel, BorderLayout.SOUTH);

		frame.pack();
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}

./examples/ListFonts.java 10/14

[
top][prev][next]
package examples;
import java.awt.*;

/**
 * List all the available fonts on the system
 * @author Sara Sprenkle
 *
 */
public class ListFonts {

	public static void main(String[] args) {
		String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment()
				.getAvailableFontFamilyNames();
		for (int i = 0; i < fontNames.length; i++)
			System.out.println(fontNames[i]);
	}
}

./examples/MyFrame.java 11/14

[
top][prev][next]
package examples;

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;

/**
 * An example of a frame in Java. It's not fancy.
 * 
 * @author Sara Sprenkle
 * 
 */
@SuppressWarnings("serial")
public class MyFrame extends JFrame {

	public MyFrame() {
		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize();
		int screenHeight = screenSize.height;
		int screenWidth = screenSize.width;

		setSize(screenWidth / 2, screenHeight / 2);
		setLocation(screenWidth / 4, screenHeight / 4);

		setTitle("My Frame Title");
		setVisible(true);
		// otherwise, just closes the window, doesn't quit
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	public static void main(String args[]) {
		MyFrame frame = new MyFrame();
		// would add more interaction in here.
	}
}

./examples/OneButtonJFrame.java 12/14

[
top][prev][next]
package examples;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * Example of creating a JFrame that only has one button on it.
 * 
 * @author Sara Sprenkle
 *
 */
public class OneButtonJFrame {

	public static void main(String[] args) {
		// create the components
		JFrame f = new JFrame("title");
		f.setBounds(0, 0, 100, 100);
		JButton b = new JButton("press me");

		// add button to the JFrame's content pane
		f.add(b);
		
		// show the frame
		f.setVisible(true);
	}

}

./examples/PanelWithButtons.java 13/14

[
top][prev][next]
package examples;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;

import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * Demonstrates using buttons on a border layout
 * 
 * @author Sara Sprenkle
 * 
 */
@SuppressWarnings("serial")
public class PanelWithButtons extends JFrame {

	public PanelWithButtons() {
		init();
		setVisible(true);
	}

	private void init() {

		this.setSize(200, 200);
		// otherwise, just closes the window, doesn't quit
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		Container pane = getContentPane();
		// The following code is used if you want to change the default layout
		// pane.setLayout(new FlowLayout());

		JButton red = new JButton("Red");
		red.setForeground(Color.red);

		JButton yellow = new JButton("Yellow");
		yellow.setOpaque(true);
		yellow.setBackground(Color.YELLOW);

		JButton blue = new JButton("Blue");
		blue.setForeground(Color.blue);

		pane.add(red, BorderLayout.NORTH);
		pane.add(yellow, BorderLayout.SOUTH);
		pane.add(blue, BorderLayout.CENTER);

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PanelWithButtons ex = new PanelWithButtons();
	}

}

./examples/ThreeButtonsFrame.java 14/14

[
top][prev][next]
package examples;

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * Example of creating three buttons within a JFrame, which uses a BorderLayout
 * by default. We need to make the layout be a flowlayout instead.
 * 
 * @author Sara Sprenkle
 */
@SuppressWarnings("serial")
public class ThreeButtonsFrame extends JFrame {

	/**
	 */
	public ThreeButtonsFrame() {
		super();
		setTitle("My Buttons");

		Container pane = this.getContentPane();
		pane.setLayout(new FlowLayout());

		// create the button
		JButton button1 = new JButton("button 1");
		// configure
		button1.setForeground(Color.CYAN);
		// add it into the container
		pane.add(button1);

		// create the button
		JButton button2 = new JButton("button 2");
		// configure
		button2.setOpaque(true);
		button2.setBackground(Color.pink);
		button2.setForeground(Color.GREEN);
		// add it into the container
		pane.add(button2);

		// create the button
		JButton button3 = new JButton("button 3");
		// configure
		button3.setForeground(Color.BLUE);
		// add it into the container
		pane.add(button3);

		pack();
		setVisible(true);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ThreeButtonsFrame myframe = new ThreeButtonsFrame();
		myframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

}

Generated by GNU Enscript 1.6.6.