Program Code
Program Code
GuiDemo.java
DrawPanel.java
GetTextDialog.java
IconSupport.java
mageItem.java
SimpleFileChooser.java
TextItem.java
TextMenu.java
Util.java
Source code for GuiDemo.java:
package guidemo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToolBar;
/**
* A frame that displays a multiline text, possibly with a background image and
* with added icon images, in a DrawPanel, along with a variety of controlls.
*/ public class GuiDemo extends JFrame {
/**
*The main program just creates a GuiDemo frame and makes it visible.
*/
public static void main(String[] args) {
JFrame frame = new GuiDemo(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);
}
/**
* The constructor creates the frame, sizes it, and centers it horizontally on
* the screen.
*/
public GuiDemo() {
super("Sayings"); // Specifies the string for the title bar of the window.
JPanel content = new JPanel(); // To hold the content of the window. content.setBackground(Color.green);
content.setLayout(new BorderLayout());
setContentPane(content);
// Create the DrawPanel that fills most of the window, and customize it.
// Create the menu bar and add it to the frame. The TextMenu is defined by
// a separate class. The other menus are created in this class.
// Create and customize the file chooser that is used for file operations.
/*
/**
* Create the "Background" menu, using objects of type ChooseBackgroundAction, a
* class that is defined later in this file.
*/
menu.add(new ChooseBackgroundAction("Custom..."));
menu.addSeparator();
menu.add(new ChooseBackgroundAction("Color..."));
menu.addSeparator();
menu.add(gradientOverlayCheckbox);
gradientOverlayCheckbox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (gradientOverlayCheckbox.isSelected())
drawPanel.setGradientOverlayColor(Color.WHITE);
else
drawPanel.setGradientOverlayColor(null);
}
});
return menu;
}
ChooseBackgroundAction(String text) {
super(text);
this.text = text;
if (!text.equals("Custom...") && !text.equals("Color...")) {
putValue(Action.SMALL_ICON,
Util.iconFromResource("resources/images/" + text.toLowerCase() + "_thumbnail.jpeg"));
}
if (text.equals("Color...")) {
putValue(Action.SHORT_DESCRIPTION,
"<html>Use a solid color for background<br>instead of an image.</html>");
BufferedImage colorSel = new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB);
Graphics g = colorSel.createGraphics();
g.setColor(Color.RED);
g.fillRect(0, 0, 10, 32);
g.setColor(Color.GREEN);
g.fillRect(11, 0, 11, 32);
g.setColor(Color.BLUE);
g.fillRect(22, 0, 10, 32);
g.dispose();
putValue(Action.SMALL_ICON, new ImageIcon(colorSel));
} else if (text.equals("Custom...")) {
putValue(Action.SHORT_DESCRIPTION, "<html>Select an image file<br>to use as the
background.</html>");
putValue(Action.SMALL_ICON, Util.iconFromResource("resources/action_icons/fileopen.png"));
} else {
putValue(Action.SHORT_DESCRIPTION, "Use this image as the background.");
}
}
package guidemo;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
private TextItem text = new TextItem(); // The TextItem displayed in this image.
// It can be retrieved with getTextItem but can't be set.
private Image backgroundImage = null; // Seven properties that have "get" and "set" methods.
private Color borderColor = Color.DARK_GRAY;
private int borderThickness = 3;
private Color gradientOverlayColor = Color.WHITE;
private boolean horizontalOverlay = false;
private BufferedImage currentDrawImage;
public DrawPanel() {
setPreferredSize(new Dimension(800, 600));
setBackground(Color.DARK_GRAY);
setBorder(BorderFactory.createLineBorder(borderColor, borderThickness));
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
addMouseListener(new MouseAdapter() {
AudioClip clink = Util.getSound("resources/sounds/clink.wav");
AudioClip lase = Util.getSound("resources/sounds/lase.wav");
}
public int getBorderThickness() {
return borderThickness;
}
/**
* Create and return a BufferedImage containing the same picture that is shown
* in this panel.
*/
public BufferedImage copyImage() {
BufferedImage copy = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = copy.createGraphics();
paintComponent(g);
g.dispose();
return copy;
}
/**
* Return this panel to its default state. (The text will be "Hello World", on a
* gray background.)
*/
public void clear() {
text = new TextItem();
backgroundImage = null;
setBackground(Color.DARK_GRAY);
gradientOverlayColor = Color.WHITE;
horizontalOverlay = false;
borderThickness = 3;
setBorderColor(Color.DARK_GRAY);
images.clear();
repaint();
}
}
package guidemo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextArea;
/**
* Defines a modal dialog for inputing multiline text.
*/
public class GetTextDialog extends JDialog {
/**
* Creates, but does not show, a dialog box.
*/
private GetTextDialog(Frame parent, String initialText) {
super(parent, "Input Your Text", true);
JPanel content = new JPanel();
setContentPane(content);
content.setBackground(Color.LIGHT_GRAY);
content.setLayout(new BorderLayout(3, 3));
text = new JTextArea(10, 50);
text.setMargin(new Insets(6, 6, 6, 6));
if (initialText != null)
text.setText(initialText);
content.add(text, BorderLayout.CENTER);
JPanel bottom = new JPanel();
content.add(bottom, BorderLayout.SOUTH);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
canceled = true;
dispose();
}
});
JButton ok = new JButton("OK");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
bottom.add(cancel);
bottom.add(ok);
pack();
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
}
}
Source code for IconSupport.java:
package guidemo;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JToolBar;
/**
* Return a menu.
*/
public JMenu createMenu() {
JMenu stamper = new JMenu("Stamper");
for (int i = 0; i < actions.size() - 1; i++) {
stamper.add(actions.get(i));
}
stamper.addSeparator();
stamper.add(actions.get(actions.size() - 1));
return stamper;
}
/**
* Return a toolbar containing buttons representing the images that can be added
* to the DrawPanel.
*
* @param horizontal a value of JToolBar.HORIZONTAL or JToolBar.VERTICAL tells
* whether the toolbar is meant to have horizontal or vertical
* orientation.
*/
public JToolBar createToolbar(boolean horizontal) {
JToolBar tbar = new JToolBar(horizontal ? JToolBar.HORIZONTAL : JToolBar.VERTICAL);
for (int i = 0; i < actions.size() - 1; i++)
tbar.add(actions.get(i));
tbar.addSeparator(new Dimension(15, 0));
tbar.add(actions.get(actions.size() - 1));
return tbar;
}
private class NoIconAction extends AbstractAction {
NoIconAction() {
super("Eraser");
BufferedImage del = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
Graphics g = del.createGraphics();
g.setColor(Color.WHITE);
/**
* Represents an image, drawn with its center at a specified point.
*/
public class ImageItem {
package guidemo;
import java.awt.Component;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
if (dialog == null)
dialog = new JFileChooser();
if (dialogTitle != null)
dialog.setDialogTitle(dialogTitle);
else
dialog.setDialogTitle("Select Output File");
if (defaultFile == null)
dialog.setSelectedFile(null);
else
dialog.setSelectedFile(new File(defaultFile));
while (true) {
int option = dialog.showSaveDialog(parent);
if (option != JFileChooser.APPROVE_OPTION)
return null; // User canceled or clicked the dialog's close box.
File selectedFile = dialog.getSelectedFile();
if (!selectedFile.exists())
return selectedFile;
else { // Ask the user whether to replace the file.
int response = JOptionPane.showConfirmDialog(parent,
"The file \"" + selectedFile.getName() + "\" already exists.\nDo you want to replace it?",
"Confirm Save", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.CANCEL_OPTION)
return null; // User does not want to select a file.
if (response == JOptionPane.YES_OPTION)
return selectedFile; // User wants to replace the file
// A "No" response will cause the file dialog to be shown again.
}
}
}
}
package guidemo;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Scanner;
public class TextItem {
public final static int CENTER = 0; // Constants for use with setJustify()
public final static int LEFT = 1;
public final static int RIGHT = 2;
private String text = "Hello\nWorld"; // the displayed text, with '\n' indicating line breaks.
private Color color = Color.BLACK;
private double lineHeightMultiplier = 1;
private boolean bold;
private boolean italic;
private int fontSize = 30;
private String[] lines = { "Hello", "World" }; // same as text, but broken into individual lines.
return fontName;
}
package guidemo;
import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
/**
* A menu full of commands that affect the text shown in a DrawPanel.
*/
public class TextMenu extends JMenu {
private final DrawPanel panel; // the panel whose text is controlled by this menu
private JCheckBoxMenuItem bold; // controls whether the text is bold or not.
private JCheckBoxMenuItem italic; // controls whether the text is italic or not.
/**
* Constructor creates all the menu commands and adds them to the menu.
*
* @param owner the panel whose text will be controlled by this menu.
*/
public TextMenu(DrawPanel owner) {
super("Text");
this.panel = owner;
final JMenuItem change = new JMenuItem("Change Text...");
change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String currentText = panel.getTextItem().getText();
String newText = GetTextDialog.showDialog(panel, currentText);
if (newText != null && newText.trim().length() > 0) {
panel.getTextItem().setText(newText);
panel.repaint();
}
}
});
final JMenuItem size = new JMenuItem("Set Size...");
size.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int currentSize = panel.getTextItem().getFontSize();
String s = JOptionPane.showInputDialog(panel, "What font size do you want to use?",
currentSize);
if (s != null && s.trim().length() > 0) {
try {
int newSize = Integer.parseInt(s.trim()); // can throw NumberFormatException
panel.getTextItem().setFontSize(newSize); // can throw IllegalArgumentException
panel.repaint();
} catch (Exception e) {
JOptionPane.showMessageDialog(panel,
s + " is not a legal text size.\n" + "Please enter a positive integer.");
}
}
}
});
final JMenuItem height = new JMenuItem("Set Height...");
height.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
double currentHeight = panel.getTextItem().getLineHeightMultiplier();
String s = JOptionPane.showInputDialog(panel, "What height do you want to use?",
currentHeight);
if (s != null && s.trim().length() > 0) {
try {
int newHeight = Integer.parseInt(s.trim()); // can throw NumberFormatException
panel.getTextItem().setLineHeightMultiplier(newHeight); // can throw IllegalArgumentException
panel.repaint();
} catch (Exception e) {
JOptionPane.showMessageDialog(panel,
s + " is not a legal text height.\n" + "Please enter a positive integer.");
}
}
}
});
final JMenuItem color = new JMenuItem("Set Color...");
color.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Color currentColor = panel.getTextItem().getColor();
Color newColor = JColorChooser.showDialog(panel, "Select Text Color", currentColor);
if (newColor != null) {
panel.getTextItem().setColor(newColor);
panel.repaint();
}
}
});
italic = new JCheckBoxMenuItem("Italic");
italic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.getTextItem().setItalic(italic.isSelected());
panel.repaint();
}
});
bold = new JCheckBoxMenuItem("Bold");
bold.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.getTextItem().setBold(bold.isSelected());
panel.repaint();
}
});
add(change);
addSeparator();
add(size);
add(height);
add(color);
add(italic);
add(bold);
addSeparator();
add(makeFontNameSubmenu());
add(makeJustifyMenu());
}
public void setDefaults() {
italic.setSelected(false);
bold.setSelected(false);
}
private JMenu makeFontNameSubmenu() {
ActionListener setFontAction = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.getTextItem().setFontName(evt.getActionCommand());
panel.repaint();
}
};
JMenu menu = new JMenu("Font Name");
String[] basic = { "Serif", "SansSerif", "Monospace" };
for (String f : basic) {
JMenuItem m = new JMenuItem(f + " Default");
m.setActionCommand(f);
m.addActionListener(setFontAction);
m.setFont(new Font(f, Font.PLAIN, 12));
menu.add(m);
}
menu.addSeparator();
String[] fonts =
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
if (fonts.length <= 20) {
for (String f : fonts) {
JMenuItem m = new JMenuItem(f);
m.addActionListener(setFontAction);
m.setFont(new Font(f, Font.PLAIN, 12));
menu.add(m);
}
} else { // Too many items for one menu; divide them into several sub-sub-menus.
char ch1 = 'A';
char ch2 = 'A';
JMenu m = new JMenu();
int i = 0;
while (i < fonts.length) {
while (i < fonts.length && (Character.toUpperCase(fonts[i].charAt(0)) <= ch2 || ch2 == 'Z')) {
JMenuItem item = new JMenuItem(fonts[i]);
item.addActionListener(setFontAction);
item.setFont(new Font(fonts[i], Font.PLAIN, 12));
m.add(item);
i++;
}
if (i == fonts.length || (m.getMenuComponentCount() >= 12 && i < fonts.length - 4)) {
if (ch1 == ch2)
m.setText("" + ch1);
else
m.setText(ch1 + " to " + ch2);
menu.add(m);
if (i < fonts.length)
m = new JMenu();
ch2++;
ch1 = ch2;
} else
ch2++;
}
}
return menu;
}
/**
* Create a menu containing a list of all available justifies.
*/
private JMenu makeJustifyMenu() {
ActionListener setJustifyActionLeft = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.getTextItem().setJustify(TextItem.LEFT);
panel.repaint();
}
};
ActionListener setJustifyActionCenter = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.getTextItem().setJustify(TextItem.CENTER);
panel.repaint();
}
};
ActionListener setJustifyActionRight = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.getTextItem().setJustify(TextItem.RIGHT);
panel.repaint();
}
};
JMenu menu = new JMenu("Justify");
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButtonMenuItem left = new JRadioButtonMenuItem("Left");
left.addActionListener(setJustifyActionLeft);
buttonGroup.add(left);
menu.add(left);
left.setSelected(true); // Set default justify
JRadioButtonMenuItem center = new JRadioButtonMenuItem("Center");
center.addActionListener(setJustifyActionCenter);
buttonGroup.add(center);
menu.add(center);
JRadioButtonMenuItem right = new JRadioButtonMenuItem("Right");
right.addActionListener(setJustifyActionRight);
buttonGroup.add(right);
menu.add(right);
return menu;
}
}
package guidemo;
import java.applet.AudioClip;
import java.awt.Cursor;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
/**
* Create an ImageIcon from an image that is stored as a resource.
*
* @param pathToResource the path to the resource.
* @return the ImageIcon, or null if the resource can't be located.
*/
public static ImageIcon iconFromResource(String pathToResource) {
Image img = getImageResource(pathToResource);
if (img == null)
return null;
else
return new ImageIcon(img);
}
else
return Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(hotSpotX, hotSpotY),
pathToResource);
}
Explanation:
The above provided code has been implemented in Java and appropriate comments has been
provided in the code.