Program Code
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Source code for [Link]:
package guidemo;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
* 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(); [Link](JFrame.EXIT_ON_CLOSE); [Link](true);
}
private DrawPanel drawPanel;
private SimpleFileChooser fileChooser;
private TextMenu textMenu;
private JCheckBoxMenuItem gradientOverlayCheckbox = new JCheckBoxMenuItem("Gradient
Overlay", 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. [Link]([Link]);
[Link](new BorderLayout());
setContentPane(content);
// Create the DrawPanel that fills most of the window, and customize it.
drawPanel = new DrawPanel();
[Link]().setText("Name: John Smith!\n" + " Institution: University, U.S.A.!\n" + " Course: Computer Science!\n" + "Instructor: Jane Smith!\n"); [Link]().setFontSize(36);
[Link]().setJustify([Link]); [Link]([Link]("resources/images/[Link]")); [Link](drawPanel, [Link]);
// Add an icon toolbar to the SOUTH position of the layout
IconSupport iconSupport = new IconSupport(drawPanel); [Link]([Link](true), [Link]);
// Add a toolbar to the NORTH position of the layout
[Link](makeToolbar(), [Link]);
// 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.
JMenuBar menuBar = new JMenuBar();
[Link](makeFileMenu()); textMenu = new TextMenu(drawPanel); [Link](textMenu);
[Link](makeBackgroundMenu());
[Link]([Link]());
setJMenuBar(menuBar);
// Set the size of the window and its position.
pack(); // Size the window to fit its content.
Dimension screenSize = [Link]().getScreenSize(); setLocation(([Link] - getWidth()) / 2, 50);
// Create and customize the file chooser that is used for file operations.
fileChooser = new SimpleFileChooser();
try { // I'd like to use the Desktop folder as the initial folder in the file chooser.
String userDir = [Link]("[Link]");
if (userDir != null) {
File desktop = new File(userDir, "Desktop");
if ([Link]())
[Link](desktop);
}
} catch (Exception e) { } } // end constructor
/**
* Create the "File" menu from actions that are defined later in this class.
*/
private JMenu makeFileMenu() {
JMenu menu = new JMenu("File");
[Link](newPictureAction);
[Link](saveImageAction);
[Link]();
[Link](quitAction); return menu;
}
/*
* Create tool bar for background
*/
private JToolBar makeToolbar() {
JToolBar tbar = new JToolBar("Background");
JButton newPict = [Link](newPictureAction);
[Link]("Clear Image, return to default");
JButton saveImg = [Link](saveImageAction);
[Link]("Save Image");
[Link](new Dimension(15, 0));
[Link](new ChooseBackgroundAction("Mandelbrot"));
[Link](new ChooseBackgroundAction("Earthrise"));
[Link](new ChooseBackgroundAction("Sunset"));
[Link](new ChooseBackgroundAction("Cloud"));
[Link](new ChooseBackgroundAction("Eagle_nebula"));
[Link](new Dimension(15, 0)); [Link](newChooseBackgroundAction("Custom..."));
[Link](new ChooseBackgroundAction("Color..."));
return tbar;
/**
* Create the "Background" menu, using objects of type ChooseBackgroundAction, a
* class that is defined later in this file.
*/
private JMenu makeBackgroundMenu() {
JMenu menu = new JMenu("Background");
[Link](new ChooseBackgroundAction("Mandelbrot"));
[Link](new ChooseBackgroundAction("Earthrise"));
[Link](new ChooseBackgroundAction("Sunset"));
[Link](new ChooseBackgroundAction("Cloud"));
[Link](new ChooseBackgroundAction("Eagle_nebula"));
[Link]();
[Link](new ChooseBackgroundAction("Custom..."));
[Link]();
[Link](new ChooseBackgroundAction("Color..."));
[Link]();
[Link](gradientOverlayCheckbox);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if ([Link]())
[Link]([Link]);
else
[Link](null);
}
});
return menu;
}
private AbstractAction newPictureAction = new AbstractAction("New",
[Link]("resources/action_icons/[Link]")) {
public void actionPerformed(ActionEvent evt) {
[Link]();
[Link](true);
[Link]();
}
};
private AbstractAction quitAction = new AbstractAction("Quit",
[Link]("resources/action_icons/[Link]")) {
public void actionPerformed(ActionEvent evt) {
[Link](0);
}
};
private AbstractAction saveImageAction = new AbstractAction("Save Image...",
[Link]("resources/action_icons/[Link]")) {
public void actionPerformed(ActionEvent evt) {
File f = [Link](drawPanel, "Select Ouput File", "[Link]");
if (f != null) {
try {
BufferedImage img = [Link]();
String format;
String fileName = [Link]().toLowerCase();
if ([Link](".png"))
format = "PNG";
else if ([Link](".jpeg") || [Link](".jpg"))
format = "JPEG";
else {
[Link](drawPanel, "The output file name must end wth\[Link]
or .jpeg.");
return;
}
[Link](img, format, f);
} catch (Exception e) {
[Link](drawPanel, "Sorry, the image could not be saved.");
}
}
}
};
private class ChooseBackgroundAction extends AbstractAction {
String text;
ChooseBackgroundAction(String text) {
super(text);
[Link] = text;
if ( && ) {
putValue(Action.SMALL_ICON,
[Link]("resources/images/" + [Link]() + "_thumbnail.jpeg"));
}
if ([Link]("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 = [Link]();
[Link]([Link]);
[Link](0, 0, 10, 32);
[Link]([Link]);
[Link](11, 0, 11, 32);
[Link]([Link]);
[Link](22, 0, 10, 32);
[Link]();
putValue(Action.SMALL_ICON, new ImageIcon(colorSel));
} else if ([Link]("Custom...")) {
putValue(Action.SHORT_DESCRIPTION, "<html>Select an image file<br>to use as the
background.</html>");
putValue(Action.SMALL_ICON, [Link]("resources/action_icons/[Link]"));
} else {
putValue(Action.SHORT_DESCRIPTION, "Use this image as the background.");
}
}
public void actionPerformed(ActionEvent evt) {
if ([Link]("Custom...")) {
File inputFile = [Link](drawPanel, "Select Background Image");
if (inputFile != null) {
try {
BufferedImage img = [Link](inputFile);
if (img == null)
throw new Exception();
[Link](img);
} catch (Exception e) {
[Link](drawPanel, "Sorry, couldn't read the file.");
}
}
} else if ([Link]("Color...")) {
Color c = [Link](drawPanel, "Select Color for Background",
[Link]());
if (c != null) {
[Link](c);
[Link](null);
}
} else {
Image bg = [Link]("resources/images/" + [Link]() + ".jpeg");
[Link](bg);
}
}
}
Source code for [Link]:
package guidemo;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].Graphics2D;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class DrawPanel extends 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 = [Link];
private boolean horizontalOverlay = false;
private BufferedImage currentDrawImage;
private ArrayList<ImageItem> images = new ArrayList<ImageItem>(); // three objects for internal
use only
public DrawPanel() {
setPreferredSize(new Dimension(800, 600));
setBackground(Color.DARK_GRAY);
setBorder([Link](borderColor, borderThickness));
setCursor([Link](Cursor.CROSSHAIR_CURSOR));
addMouseListener(new MouseAdapter() {
AudioClip clink = [Link]("resources/sounds/[Link]");
AudioClip lase = [Link]("resources/sounds/[Link]");
public void mousePressed(MouseEvent evt) {
int x = [Link]();
int y = [Link]();
if (currentDrawImage != null) {
if (clink != null)
[Link]();
[Link](new ImageItem(currentDrawImage, x, y));
repaint();
} else {
for (int i = [Link]() - 1; i >= 0; i--)
if ([Link](i).contains(x, y)) {
if (lase != null)
[Link]();
[Link](i);
repaint();
break;
}
}
}
});
}
protected void paintComponent(Graphics g1) {
[Link](g1);
Graphics2D g2 = (Graphics2D) g1;
[Link](RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (backgroundImage != null)
[Link](backgroundImage, 0, 0, getWidth(), getHeight(), this);
if (gradientOverlayColor != null) {
int r = [Link]();
int b = [Link]();
int g = [Link]();
Color startColor = new Color(r, g, b, 50);
Color endColor = new Color(r, g, b, 200);
if (horizontalOverlay)
[Link](new GradientPaint(0, 0, startColor, getWidth(), 0, endColor, false));
else
[Link](new GradientPaint(0, 0, startColor, 0, getHeight(), endColor, false));
[Link](0, 0, getWidth(), getHeight());
}
[Link](g2, getWidth() / 2, getHeight() / 2);
for (ImageItem img : images)
[Link](g2);
}
public Image getBackgroundImage() {
return backgroundImage;
}
public void setBackgroundImage(Image backgroundImage) {
[Link] = backgroundImage;
repaint();
}
public Color getBorderColor() {
return borderColor;
}
public void setBorderColor(Color borderColor) {
[Link] = borderColor;
setBorder([Link](borderColor, borderThickness));
repaint();
}
public int getBorderThickness() {
return borderThickness;
}
public void setBorderThickness(int borderThickness) {
[Link] = borderThickness;
setBorder([Link](borderColor, borderThickness));
repaint();
}
public Color getGradientOverlayColor() {
return gradientOverlayColor;
}
public void setGradientOverlayColor(Color gradientOverlayColor) {
[Link] = gradientOverlayColor;
repaint();
}
public boolean isHorizontalOverlay() {
return horizontalOverlay;
}
public void setHorizontalOverlay(boolean horizontalOverlay) {
[Link] = horizontalOverlay;
repaint();
}
public BufferedImage getCurrentDrawImage() {
return currentDrawImage;
}
public void setCurrentDrawImage(BufferedImage currentDrawImage) {
[Link] = currentDrawImage;
}
public TextItem getTextItem() {
return text;
}
/**
* 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 = [Link]();
paintComponent(g);
[Link]();
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 = [Link];
horizontalOverlay = false;
borderThickness = 3;
setBorderColor(Color.DARK_GRAY);
[Link]();
repaint();
}
}
Source code for [Link]:
package guidemo;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
* Defines a modal dialog for inputing multiline text.
*/
public class GetTextDialog extends JDialog {
private boolean canceled = false;
private JTextArea text;
public static String showDialog(Component parent, String initialText) {
GetTextDialog dialog = new GetTextDialog(frameAncestor(parent), initialText);
[Link](true);
if ([Link])
return null;
else
return [Link]();
}
private static Frame frameAncestor(Component c) {
while (c != null && !(c instanceof Frame))
c = [Link]();
return (Frame) c;
}
/**
* 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);
[Link](Color.LIGHT_GRAY);
[Link](new BorderLayout(3, 3));
text = new JTextArea(10, 50);
[Link](new Insets(6, 6, 6, 6));
if (initialText != null)
[Link](initialText);
[Link](text, [Link]);
JPanel bottom = new JPanel();
[Link](bottom, [Link]);
JButton cancel = new JButton("Cancel");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent evt) {
canceled = true;
dispose();
}
});
JButton ok = new JButton("OK");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
[Link](cancel);
[Link](ok);
pack();
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
}
}
Source code for [Link]:
package guidemo;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class IconSupport {
private DrawPanel panel;
private ArrayList<BufferedImage> iconImages = new ArrayList<BufferedImage>();
private ArrayList<Action> actions = new ArrayList<Action>();
public IconSupport(DrawPanel owner) {
panel = owner;
String[] iconNames = { "bell", "camera", "flower", "star", "check", "crossout", "tux", "bomb",
"keyboard",
"lightbulb", "tv" };
for (String name : iconNames) {
BufferedImage img = [Link]("resources/icons/" + name + ".png");
if (img != null) {
[Link](img);
[Link](new SelectIconAction(name, [Link]() - 1));
}
}
[Link](new NoIconAction());
}
/**
* Return a menu.
*/
public JMenu createMenu() {
JMenu stamper = new JMenu("Stamper");
for (int i = 0; i < [Link]() - 1; i++) {
[Link]([Link](i));
}
[Link]();
[Link]([Link]([Link]() - 1));
return stamper;
}
/**
* Return a toolbar containing buttons representing the images that can be added
* to the DrawPanel.
*
* @param horizontal a value of [Link] or [Link] tells
* whether the toolbar is meant to have horizontal or vertical
* orientation.
*/
public JToolBar createToolbar(boolean horizontal) {
JToolBar tbar = new JToolBar(horizontal ? [Link] : [Link]);
for (int i = 0; i < [Link]() - 1; i++)
[Link]([Link](i));
[Link](new Dimension(15, 0));
[Link]([Link]([Link]() - 1));
return tbar;
}
private class NoIconAction extends AbstractAction {
NoIconAction() {
super("Eraser");
BufferedImage del = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
Graphics g = [Link]();
[Link]([Link]);
[Link](0, 0, 32, 32);
[Link]([Link]);
[Link]("DEL", 5, 20);
[Link]();
putValue(Action.SMALL_ICON, new ImageIcon(del));
putValue(Action.SHORT_DESCRIPTION, "Use Mouse to Erase Icons"); // tooltip
}
public void actionPerformed(ActionEvent evt) {
[Link](null);
[Link]([Link](Cursor.CROSSHAIR_CURSOR));
}
}
private class SelectIconAction extends AbstractAction {
int iconNumber;
SelectIconAction(String name, int n) {
// Note: The name is surpressed in toolbars, but not in menus.
super(name, new ImageIcon([Link](n)));
iconNumber = n;
putValue(Action.SHORT_DESCRIPTION, "Use Mouse to Stamp this Icon"); // tooltip
}
public void actionPerformed(ActionEvent evt) {
BufferedImage image = [Link](iconNumber);
[Link](image);
Cursor c = [Link](image, [Link]() / 2, [Link]() / 2);
[Link](c);
}
}
Source code for [Link]:
package guidemo;
import [Link];
import [Link];
/**
* Represents an image, drawn with its center at a specified point.
*/
public class ImageItem {
private BufferedImage image;
private int centerX, centerY;
public ImageItem(BufferedImage image, int centerX, int centerY) {
[Link] = image;
[Link] = centerX;
[Link] = centerY;
}
public void draw(Graphics g) {
[Link](image, centerX - [Link]() / 2, centerY - [Link]() / 2, null);
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
if (image == null)
throw new IllegalArgumentException("Null image not allowed");
[Link] = image;
}
public int getCenterX() {
return centerX;
}
public void setCenterX(int centerX) {
[Link] = centerX;
}
public int getCenterY() {
return centerY;
}
public void setCenterY(int centerY) {
[Link] = centerY;
}
public void setPosition(int x, int y) {
centerX = x;
centerY = y;
}
public boolean contains(int x, int y) {
int w = [Link]();
int h = [Link]();
return x > centerX - w / 2 && x < centerX + w / 2 && y > centerY - h / 2 && y < centerY + h / 2;
}
Source code for [Link]:
package guidemo;
import [Link];
import [Link];
import [Link];
import [Link];
public class SimpleFileChooser {
private JFileChooser dialog; // The dialog, which is created when needed.
public void setDefaultDirectory() {
if (dialog != null)
[Link](null);
}
public void setDefaultDirectory(String directoryName) {
if (dialog == null)
dialog = new JFileChooser();
[Link](new File(directoryName));
}
public void setDefaultDirectory(File directory) {
if (dialog == null)
dialog = new JFileChooser();
[Link](directory);
}
public File getInputFile() {
return getInputFile(null, null);
}
public File getInputFile(Component parent) {
return getInputFile(parent, null);
}
public File getInputFile(Component parent, String dialogTitle) {
if (dialog == null)
dialog = new JFileChooser();
if (dialogTitle != null)
[Link](dialogTitle);
else
[Link]("Select Input File");
int option = [Link](parent);
if (option != JFileChooser.APPROVE_OPTION)
return null; // User canceled or clicked the dialog's close box.
File selectedFile = [Link]();
return selectedFile;
}
public File getOutputFile() {
return getOutputFile(null, null, null);
}
public File getOutputFile(Component parent) {
return getOutputFile(parent, null, null);
}
public File getOutputFile(Component parent, String dialogTitle) {
return getOutputFile(parent, dialogTitle, null);
}
public File getOutputFile(Component parent, String dialogTitle, String defaultFile) {
if (dialog == null)
dialog = new JFileChooser();
if (dialogTitle != null)
[Link](dialogTitle);
else
[Link]("Select Output File");
if (defaultFile == null)
[Link](null);
else
[Link](new File(defaultFile));
while (true) {
int option = [Link](parent);
if (option != JFileChooser.APPROVE_OPTION)
return null; // User canceled or clicked the dialog's close box.
File selectedFile = [Link]();
if (![Link]())
return selectedFile;
else { // Ask the user whether to replace the file.
int response = [Link](parent,
"The file \"" + [Link]() + "\" 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.
}
}
}
}
Source code for [Link]:
package guidemo;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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 = [Link];
private double lineHeightMultiplier = 1;
private boolean bold;
private boolean italic;
private int fontSize = 30;
private String fontName = "Serif";
private int justify = LEFT;
private String[] lines = { "Hello", "World" }; // same as text, but broken into individual lines.
public void draw(Graphics g, int centerX, int centerY) {
Color saveColor = [Link]();
Font saveFont = [Link]();
int style;
if (italic && bold)
style = [Link] | [Link];
else if (italic)
style = [Link];
else if (bold)
style = [Link];
else
style = [Link];
Font font = new Font(fontName, style, fontSize);
[Link](font);
FontMetrics fm = [Link](font);
double lineHeight = [Link]() * lineHeightMultiplier;
int totalHeight = (int) (lineHeight * ([Link] - 1)) + [Link]() + [Link]();
if (color != null)
[Link](color);
int[] widths = new int[[Link]];
int totalWidth = 0;
for (int i = 0; i < [Link]; i++) {
widths[i] = [Link](lines[i]);
if (widths[i] > totalWidth)
totalWidth = widths[i];
}
for (int i = 0; i < [Link]; i++) {
int x;
if (justify == CENTER)
x = centerX - widths[i] / 2;
else if (justify == LEFT)
x = centerX - totalWidth / 2;
else
x = centerX + totalWidth / 2 - [Link](lines[i]);
int y = centerY - totalHeight / 2 + [Link]() + (int) (i * lineHeight);
[Link](lines[i], x, y);
}
[Link](saveColor);
[Link](saveFont);
}
public String getText() {
return text;
}
public void setText(String newText) {
Scanner reader = new Scanner(newText);
ArrayList<String> s = new ArrayList<String>();
while ([Link]()) {
[Link]([Link]());
}
while ([Link]() > 0 && [Link](0).trim().length() == 0)
[Link](0); // remove blank lines from front
while ([Link]() > 0 && [Link]([Link]() - 1).trim().length() == 0)
[Link]([Link]() - 1); // remove blank lines from end
if ([Link]() == 0)
throw new IllegalArgumentException("Text can't be empty.");
lines = new String[[Link]()];
for (int i = 0; i < [Link]; i++)
lines[i] = [Link](i);
text = newText;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
[Link] = color;
}
public double getLineHeightMultiplier() {
return lineHeightMultiplier;
}
public void setLineHeightMultiplier(double lineHeightMultiplier) {
if (lineHeightMultiplier < 0)
throw new IllegalArgumentException("Line height multiplier cannot be negative.");
[Link] = lineHeightMultiplier;
}
public boolean isBold() {
return bold;
}
public void setBold(boolean bold) {
[Link] = bold;
}
public boolean isItalic() {
return italic;
}
public void setItalic(boolean italic) {
[Link] = italic;
}
public int getFontSize() {
return fontSize;
}
public void setFontSize(int fontSize) {
if (fontSize <= 0)
throw new IllegalArgumentException("Font size must be positive.");
[Link] = fontSize;
}
public String getFontName() {
return fontName;
}
public void setFontName(String fontName) {
[Link] = fontName;
}
public int getJustify() {
return justify;
}
public void setJustify(int justify) {
if (justify != CENTER && justify != RIGHT && justify != LEFT)
throw new IllegalArgumentException("Justify can only be CENTER, LEFT, or RIGHT");
[Link] = justify;
}
}
Source code for [Link]:
package guidemo;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
* 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");
[Link] = owner;
final JMenuItem change = new JMenuItem("Change Text...");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String currentText = [Link]().getText();
String newText = [Link](panel, currentText);
if (newText != null && [Link]().length() > 0) {
[Link]().setText(newText);
[Link]();
}
}
});
final JMenuItem size = new JMenuItem("Set Size...");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int currentSize = [Link]().getFontSize();
String s = [Link](panel, "What font size do you want to use?",
currentSize);
if (s != null && [Link]().length() > 0) {
try {
int newSize = [Link]([Link]()); // can throw NumberFormatException
[Link]().setFontSize(newSize); // can throw IllegalArgumentException
[Link]();
} catch (Exception e) {
[Link](panel,
s + " is not a legal text size.\n" + "Please enter a positive integer.");
}
}
}
});
final JMenuItem height = new JMenuItem("Set Height...");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent evt) {
double currentHeight = [Link]().getLineHeightMultiplier();
String s = [Link](panel, "What height do you want to use?",
currentHeight);
if (s != null && [Link]().length() > 0) {
try {
int newHeight = [Link]([Link]()); // can throw NumberFormatException
[Link]().setLineHeightMultiplier(newHeight); // can throw IllegalArgumentException
[Link]();
} catch (Exception e) {
[Link](panel,
s + " is not a legal text height.\n" + "Please enter a positive integer.");
}
}
}
});
final JMenuItem color = new JMenuItem("Set Color...");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Color currentColor = [Link]().getColor();
Color newColor = [Link](panel, "Select Text Color", currentColor);
if (newColor != null) {
[Link]().setColor(newColor);
[Link]();
}
}
});
italic = new JCheckBoxMenuItem("Italic");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent evt) {
[Link]().setItalic([Link]());
[Link]();
}
});
bold = new JCheckBoxMenuItem("Bold");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent evt) {
[Link]().setBold([Link]());
[Link]();
}
});
add(change);
addSeparator();
add(size);
add(height);
add(color);
add(italic);
add(bold);
addSeparator();
add(makeFontNameSubmenu());
add(makeJustifyMenu());
}
public void setDefaults() {
[Link](false);
[Link](false);
}
private JMenu makeFontNameSubmenu() {
ActionListener setFontAction = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
[Link]().setFontName([Link]());
[Link]();
}
};
JMenu menu = new JMenu("Font Name");
String[] basic = { "Serif", "SansSerif", "Monospace" };
for (String f : basic) {
JMenuItem m = new JMenuItem(f + " Default");
[Link](f);
[Link](setFontAction);
[Link](new Font(f, [Link], 12));
[Link](m);
}
[Link]();
String[] fonts =
[Link]().getAvailableFontFamilyNames();
if ([Link] <= 20) {
for (String f : fonts) {
JMenuItem m = new JMenuItem(f);
[Link](setFontAction);
[Link](new Font(f, [Link], 12));
[Link](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 < [Link]) {
while (i < [Link] && ([Link](fonts[i].charAt(0)) <= ch2 || ch2 == 'Z')) {
JMenuItem item = new JMenuItem(fonts[i]);
[Link](setFontAction);
[Link](new Font(fonts[i], [Link], 12));
[Link](item);
i++;
}
if (i == [Link] || ([Link]() >= 12 && i < [Link] - 4)) {
if (ch1 == ch2)
[Link]("" + ch1);
else
[Link](ch1 + " to " + ch2);
[Link](m);
if (i < [Link])
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) {
[Link]().setJustify([Link]);
[Link]();
}
};
ActionListener setJustifyActionCenter = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
[Link]().setJustify([Link]);
[Link]();
}
};
ActionListener setJustifyActionRight = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
[Link]().setJustify([Link]);
[Link]();
}
};
JMenu menu = new JMenu("Justify");
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButtonMenuItem left = new JRadioButtonMenuItem("Left");
[Link](setJustifyActionLeft);
[Link](left);
[Link](left);
[Link](true); // Set default justify
JRadioButtonMenuItem center = new JRadioButtonMenuItem("Center");
[Link](setJustifyActionCenter);
[Link](center);
[Link](center);
JRadioButtonMenuItem right = new JRadioButtonMenuItem("Right");
[Link](setJustifyActionRight);
[Link](right);
[Link](right);
return menu;
}
}
Source code for [Link]:
package guidemo;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Util {
public static Image getImageResource(String pathToResource) {
ClassLoader cl = [Link]();
URL loc = [Link](pathToResource);
if (loc == null)
return null;
Image img = [Link]().createImage(loc);
return img;
}
public static BufferedImage getBufferedImageResource(String pathToResource) {
ClassLoader cl = [Link]();
URL loc = [Link](pathToResource);
if (loc == null)
return null;
try {
return [Link](loc);
} catch (Exception e) {
return null;
}
}
/**
* 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);
}
public static void playSoundResource(String pathToResource) {
try {
ClassLoader cl = [Link]();
URL loc = [Link](pathToResource);
AudioClip sound = [Link](loc);
[Link]();
} catch (Exception e) {
[Link]("Can't play soucd " + pathToResource);
}
}
public static AudioClip getSound(String pathToResource) {
ClassLoader cl = [Link]();
URL loc = [Link](pathToResource);
if (loc == null)
return null;
try {
return [Link](loc);
} catch (Exception e) {
return null;
}
}
/**
* Create a cursor from an image, with hot point at the upper left corner (0,0).
*
* @param image the image; can't be null.
* @return a cursor that will show the image.
*/
public static Cursor createImageCursor(Image image) {
return createImageCursor(image, 0, 0);
}
public static Cursor createImageCursor(String pathToResource) {
return createImageCursor(pathToResource, 0, 0);
}
public static Cursor createImageCursor(String pathToResource, int hotSpotX, int hotSpotY) {
Image img = getImageResource(pathToResource);
if (img == null)
return [Link]();
else
return [Link]().createCustomCursor(img, new Point(hotSpotX, hotSpotY),
pathToResource);
}
public static Cursor createImageCursor(Image image, int hotSpotX, int hotSpotY) {
return [Link]().createCustomCursor(image, new Point(hotSpotX, hotSpotY),
null);
}
Explanation:
The above provided code has been implemented in Java and appropriate comments has been
provided in the code.