Question

could you please help me with this problem, also I need a little text so I can understand how you solved the problem?

12:42 4 al 80% Lab 10 Unit 6 Lab 10: ArrayLists and Files in a GUI Application For this lab, you will work on a simple GUI ap

12:43 16 a 80% Lab 10 Unit 6 Part 1: ArrayLists You can run TextCollage to see what it does. As it stands, you can click the

12:43 40 a 80% Lab 10 Unit 6 Part 2: Files The program is already able to save the contents of the drawing area as an image.

12:43 19 all 80% Lab 10 Unit 6 user. First, implement the Save command. Use the method fileChooser.getOutput File to get a F

12:43 .. 80% Lab 10 Unit 6 as such a file). Note: As long as each item is on its own line in the file, you can use scanner.ne

import java.io.File; import java.util.Scanner; /** * This program lists the files in a directory specified by * the user. The user is asked to type in a directory name. * If the name entered by the user is not a directory, a * message is printed and the program ends. */ public class DirectoryList { public static void main(String[] args) { String directoryName; // Directory name entered by the user. File directory; // File object referring to the directory. String[] files; // Array of file names in the directory. Scanner scanner; // For reading a line of input from the user. scanner = new Scanner(System.in); // scanner reads from standard input. System.out.print("Enter a directory name: "); directoryName = scanner.nextLine().trim(); directory = new File(directoryName); if (directory.isDirectory() == false) { if (directory.exists() == false) System.out.println("There is no such directory!"); else System.out.println("That file is not a directory."); } else { files = directory.list(); System.out.println("Files in directory \"" + directory + "\":"); for (int i = 0; i < files.length; i++) System.out.println(" " + files[i]); } } // end main() } // end class DirectoryList
package textcollage; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; /** * An object of type DrawText can draw a string in * a graphics context, with various effects, such as * color, magnification, and rotation The string * is specified in the constructor and cannot be changed. * The position and other properties can be changed. */ public class DrawTextItem { private final String string; // The String that is drawn by this item. private Font font = null; private int x = 0; private int y = 0; private Color textColor = Color.BLACK; private Color background = null; private boolean border = false; private double rotationAngle = 0; private double magnification = 1; private double textTransparency = 0; private double backgroundTransparency = 0; /** * Create a DrawTextItem to draw a specified string. Initially, * the position is set to (0,0) and all properties have their * default values. * @throws NullPointerException if the parameter is null */ public DrawTextItem(String stringToDraw) { this(stringToDraw,0,0); } /** * Create a DrawTextItem to draw a specified string. Initially, * the position is set to (x,y) and all other properties have their * default values. Note that x and y give the position of * the center of the string. * @param x the x-coordinate where the string will be drawn. * @param y the y-coordinate where the string will be drawn. * @throws NullPointerException if the parameter is null */ public DrawTextItem(String stringToDraw, int x, int y) { if (stringToDraw == null) throw new NullPointerException("String can't be null."); string = stringToDraw; this.x = x; this.y = y; } /** * Draw this item's string in the given Graphics constext, * applying all of this item's property settings. * @param g the graphics context in which the string will * be drawn. Note that this is assumed to be actually of * type Graphics2D (which should not be a problem). */ public void draw(Graphics g) { Graphics2D g2 = (Graphics2D)g.create(); if (font != null) g2.setFont(font); FontMetrics fm = g2.getFontMetrics(); int width = fm.stringWidth(string); int height = fm.getAscent() + fm.getDescent(); g2.translate(x,y); if (magnification != 1) { float pixelSize = 1/(float)magnification; g2.setStroke( new BasicStroke(pixelSize) ); // magnification won't apply to border g2.scale(magnification,magnification); } if (rotationAngle > 0) g2.rotate( -Math.PI * (rotationAngle / 180)); Color colorToUseForText = textColor; if (colorToUseForText == null) colorToUseForText = g2.getColor(); if (background != null) { if (backgroundTransparency == 0) g2.setColor(background); else g2.setColor( new Color( background.getRed(), background.getGreen(), background.getBlue(), (int)(255*(1-backgroundTransparency))) ); g2.fillRect(-width/2 - 3, -height/2 - 3, width + 6, height + 6); } if (textTransparency == 0) g2.setColor(colorToUseForText); else g2.setColor( new Color( colorToUseForText.getRed(), colorToUseForText.getGreen(), colorToUseForText.getBlue(), (int)(255*(1-textTransparency)) ) ); if (border) g2.drawRect(-width/2 -3, -height/2 - 3, width + 6, height + 6); g2.drawString(string,-width/2, -height/2 + fm.getAscent()); } /** * Returns the string that is drawn by this DrawTextItem. The * string is set in the constructor and cannot be changed. */ public String getString() { return string; } /** * Set the background color. If the value is non-null, then * a rectangle of this color is drawn behind the string. * If the value is null, no background rectangle is drawn. * The default value is null. */ public void setBackground(Color background) { this.background = background; } /** * Set the level of transparency of the background color, where 0 indicates * no transparency and 1 indicates completely transparent. If the value * is not 1, then the transparency level of the background color is set to * this value. If the background color is null, then the value of * backgroundTransparency is ignored. The default value is zero. * @param backgroundTransparency the background transparency level, in the range 0 to 1 * @throws IllegalArgumentException if the parameter is less than 0 or greater than 1 */ public void setBackgroundTransparency(double backgroundTransparency) { if (backgroundTransparency < 0 || backgroundTransparency > 1) throw new IllegalArgumentException("Transparency must be in the range 0 to 1."); this.backgroundTransparency = backgroundTransparency; } /** * If border is set to true, then a rectangular border is drawn around * the string. The default value is false. */ public void setBorder(boolean border) { this.border = border; } /** * Sets the font to be used for drawing the string. A value of * null indicates that the font that is set for the graphics context * where the string is drawn should be used. The default value is * null. */ public void setFont(Font font) { this.font = font; } /** * Set a magnification level that is applied when the string is drawn. * A magnification of 2 will double the size; a value of 0.5 will cut * it in half. Negative values will produce backwards, upside-down text. * Zero is not a legal value, and an attempt to set the magnification to * zero will cause an IllegalArgumentException. The default value is * 1, Indicating no magnification. */ public void setMagnification(double magnification) { if (magnification == 0) throw new IllegalArgumentException("Magnification cannot be 0."); this.magnification = magnification; } /** * Sets the angle of the baseline of the string with respect to the * horizontal. The angle is specified in degrees. The default is * 0, which gives normal, unrotated, horizontal text. */ public void setRotationAngle(double rotationAngle) { this.rotationAngle = rotationAngle; } /** * Sets the color to be used for drawing the text (and the border if there is one). * The default value is null, which means that the color that is set in the * graphics context where the string is drawn will be used for drawing the text. */ public void setTextColor(Color textColor) { this.textColor = textColor; } /** * Set the level of transparency of the text color, where 0 indicates * no transparency and 1 indicates completely transparent. If the value * is not 1, then the transparency level of the text color is set to * this value. This property is also applied to the border, if there is one. * The default value is zero. * @param textTransparency the text transparency level, in the range 0 to 1 * @throws IllegalArgumentException if the parameter is less than 0 or greater than 1 */ public void setTextTransparency(double textTransparency) { if (textTransparency < 0 || textTransparency > 1) throw new IllegalArgumentException("Transparency must be in the range 0 to 1."); this.textTransparency = textTransparency; } /** * Set the x-coordinate where the string is drawn. This gives the position of * the center of the string. */ public void setX(int x) { this.x = x; } /** * Set the y-coordinate where the string is drawn. This gives the position of * the center of the string. */ public void setY(int y) { this.y = y; } /** * returns the value of the background color property */ public Color getBackground() { return background; } /** * returns the value of the background transparency property */ public double getBackgroundTransparency() { return backgroundTransparency; } /** * returns the value of the border property */ public boolean getBorder() { return border; } /** * returns the value of the font property */ public Font getFont() { return font; } /** * returns the value of the magnification property */ public double getMagnification() { return magnification; } /** * returns the value of the rotation angle property */ public double getRotationAngle() { return rotationAngle; } /** * returns the value of the text color property */ public Color getTextColor() { return textColor; } /** * returns the value of the text transparency property */ public double getTextTransparency() { return textTransparency; } /** * returns the x-coord of the center of the string */ public int getX() { return x; } /** * returns the y-coord of the center of the string */ public int getY() { return y; } }
package textcollage; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.JColorChooser; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; /** * A panel that contains a large drawing area where strings * can be drawn. The strings are represented by objects of * type DrawTextItem. An input box under the panel allows * the user to specify what string will be drawn when the * user clicks on the drawing area. */ public class DrawTextPanel extends JPanel { // As it now stands, this class can only show one string at at // a time! The data for that string is in the DrawTextItem object // named theString. (If it's null, nothing is shown. This // variable should be replaced by a variable of type // ArrayList<DrawStringItem> that can store multiple items. private DrawTextItem theString; // change to an ArrayList<DrawTextItem> ! private Color currentTextColor = Color.BLACK; // Color applied to new strings. private Canvas canvas; // the drawing area. private JTextField input; // where the user inputs the string that will be added to the canvas private SimpleFileChooser fileChooser; // for letting the user select files private JMenuBar menuBar; // a menu bar with command that affect this panel private MenuHandler menuHandler; // a listener that responds whenever the user selects a menu command private JMenuItem undoMenuItem; // the "Remove Item" command from the edit menu /** * An object of type Canvas is used for the drawing area. * The canvas simply displays all the DrawTextItems that * are stored in the ArrayList, strings. */ private class Canvas extends JPanel { Canvas() { setPreferredSize( new Dimension(800,600) ); setBackground(Color.LIGHT_GRAY); setFont( new Font( "Serif", Font.BOLD, 24 )); } protected void paintComponent(Graphics g) { super.paintComponent(g); ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (theString != null) theString.draw(g); } } /** * An object of type MenuHandler is registered as the ActionListener * for all the commands in the menu bar. The MenuHandler object * simply calls doMenuCommand() when the user selects a command * from the menu. */ private class MenuHandler implements ActionListener { public void actionPerformed(ActionEvent evt) { doMenuCommand( evt.getActionCommand()); } } /** * Creates a DrawTextPanel. The panel has a large drawing area and * a text input box where the user can specify a string. When the * user clicks the drawing area, the string is added to the drawing * area at the point where the user clicked. */ public DrawTextPanel() { fileChooser = new SimpleFileChooser(); undoMenuItem = new JMenuItem("Remove Item"); undoMenuItem.setEnabled(false); menuHandler = new MenuHandler(); setLayout(new BorderLayout(3,3)); setBackground(Color.BLACK); setBorder(BorderFactory.createLineBorder(Color.BLACK, 2)); canvas = new Canvas(); add(canvas, BorderLayout.CENTER); JPanel bottom = new JPanel(); bottom.add(new JLabel("Text to add: ")); input = new JTextField("Hello World!", 40); bottom.add(input); add(bottom, BorderLayout.SOUTH); canvas.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { doMousePress( e ); } } ); } /** * This method is called when the user clicks the drawing area. * A new string is added to the drawing area. The center of * the string is at the point where the user clicked. * @param e the mouse event that was generated when the user clicked */ public void doMousePress( MouseEvent e ) { String text = input.getText().trim(); if (text.length() == 0) { input.setText("Hello World!"); text = "Hello World!"; } DrawTextItem s = new DrawTextItem( text, e.getX(), e.getY() ); s.setTextColor(currentTextColor); // Default is null, meaning default color of the canvas (black). // SOME OTHER OPTIONS THAT CAN BE APPLIED TO TEXT ITEMS: // s.setFont( new Font( "Serif", Font.ITALIC + Font.BOLD, 12 )); // Default is null, meaning font of canvas. // s.setMagnification(3); // Default is 1, meaning no magnification. // s.setBorder(true); // Default is false, meaning don't draw a border. // s.setRotationAngle(25); // Default is 0, meaning no rotation. // s.setTextTransparency(0.3); // Default is 0, meaning text is not at all transparent. // s.setBackground(Color.BLUE); // Default is null, meaning don't draw a background area. // s.setBackgroundTransparency(0.7); // Default is 0, meaning background is not transparent. theString = s; // Set this string as the ONLY string to be drawn on the canvas! undoMenuItem.setEnabled(true); canvas.repaint(); } /** * Returns a menu bar containing commands that affect this panel. The menu * bar is meant to appear in the same window that contains this panel. */ public JMenuBar getMenuBar() { if (menuBar == null) { menuBar = new JMenuBar(); String commandKey; // for making keyboard accelerators for menu commands if (System.getProperty("mrj.version") == null) commandKey = "control "; // command key for non-Mac OS else commandKey = "meta "; // command key for Mac OS JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); JMenuItem saveItem = new JMenuItem("Save..."); saveItem.setAccelerator(KeyStroke.getKeyStroke(commandKey + "N")); saveItem.addActionListener(menuHandler); fileMenu.add(saveItem); JMenuItem openItem = new JMenuItem("Open..."); openItem.setAccelerator(KeyStroke.getKeyStroke(commandKey + "O")); openItem.addActionListener(menuHandler); fileMenu.add(openItem); fileMenu.addSeparator(); JMenuItem saveImageItem = new JMenuItem("Save Image..."); saveImageItem.addActionListener(menuHandler); fileMenu.add(saveImageItem); JMenu editMenu = new JMenu("Edit"); menuBar.add(editMenu); undoMenuItem.addActionListener(menuHandler); // undoItem was created in the constructor undoMenuItem.setAccelerator(KeyStroke.getKeyStroke(commandKey + "Z")); editMenu.add(undoMenuItem); editMenu.addSeparator(); JMenuItem clearItem = new JMenuItem("Clear"); clearItem.addActionListener(menuHandler); editMenu.add(clearItem); JMenu optionsMenu = new JMenu("Options"); menuBar.add(optionsMenu); JMenuItem colorItem = new JMenuItem("Set Text Color..."); colorItem.setAccelerator(KeyStroke.getKeyStroke(commandKey + "T")); colorItem.addActionListener(menuHandler); optionsMenu.add(colorItem); JMenuItem bgColorItem = new JMenuItem("Set Background Color..."); bgColorItem.addActionListener(menuHandler); optionsMenu.add(bgColorItem); } return menuBar; } /** * Carry out one of the commands from the menu bar. * @param command the text of the menu command. */ private void doMenuCommand(String command) { if (command.equals("Save...")) { // save all the string info to a file JOptionPane.showMessageDialog(this, "Sorry, the Save command is not implemented."); } else if (command.equals("Open...")) { // read a previously saved file, and reconstruct the list of strings JOptionPane.showMessageDialog(this, "Sorry, the Open command is not implemented."); canvas.repaint(); // (you'll need this to make the new list of strings take effect) } else if (command.equals("Clear")) { // remove all strings theString = null; // Remove the ONLY string from the canvas. undoMenuItem.setEnabled(false); canvas.repaint(); } else if (command.equals("Remove Item")) { // remove the most recently added string theString = null; // Remove the ONLY string from the canvas. undoMenuItem.setEnabled(false); canvas.repaint(); } else if (command.equals("Set Text Color...")) { Color c = JColorChooser.showDialog(this, "Select Text Color", currentTextColor); if (c != null) currentTextColor = c; } else if (command.equals("Set Background Color...")) { Color c = JColorChooser.showDialog(this, "Select Background Color", canvas.getBackground()); if (c != null) { canvas.setBackground(c); canvas.repaint(); } } else if (command.equals("Save Image...")) { // save a PNG image of the drawing area File imageFile = fileChooser.getOutputFile(this, "Select Image File Name", "textimage.png"); if (imageFile == null) return; try { // Because the image is not available, I will make a new BufferedImage and // draw the same data to the BufferedImage as is shown in the panel. // A BufferedImage is an image that is stored in memory, not on the screen. // There is a convenient method for writing a BufferedImage to a file. BufferedImage image = new BufferedImage(canvas.getWidth(),canvas.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setFont(canvas.getFont()); canvas.paintComponent(g); // draws the canvas onto the BufferedImage, not the screen! boolean ok = ImageIO.write(image, "PNG", imageFile); // write to the file if (ok == false) throw new Exception("PNG format not supported (this shouldn't happen!)."); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Sorry, an error occurred while trying to save the image:\n" + e); } } }

package textcollage; import java.awt.Component; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * This class provides a slightly simplified interface to one of Java's * standard JFileChooser dialogs. An object of type SimpleFileChooser * has methods that allow the user to select files for input or output. * If the object is used several times, the same JFileChooser is used * each time. By default, the dialog box is set to the user's home * directory the first time it is used, and after that it remembers the * current directory between one use and the next. However, methods * are provided for setting the current directory. (Note: On Windows, * the user's home directory will probably mean the user's "My Documents" * directory".) */ public class SimpleFileChooser { private JFileChooser dialog; // The dialog, which is created when needed. /** * Reset the default directory in the dialog box to the user's home * directory. The next time the dialog appears, it will show the * contents of that directory. */ public void setDefaultDirectory() { if (dialog != null) dialog.setCurrentDirectory(null); } /** * Set the default directory for the dialog box. The next time the * dialog appears, it will show the contents of that directory. * @param directoryName A File object that specifies the directory name. * If this name is null, then the user's home directory will be used. */ public void setDefaultDirectory(String directoryName) { if (dialog == null) dialog = new JFileChooser(); dialog.setCurrentDirectory(new File(directoryName)); } /** * Set the default directory for the dialog box. The next time the * dialog appears, it will show the contents of that directory. * @param directoryName The name of the new default directory. If the * name is null, then the user's home directory will be used. */ public void setDefaultDirectory(File directory) { if (dialog == null) dialog = new JFileChooser(); dialog.setCurrentDirectory(directory); } /** * Show a dialog box where the user can select a file for reading. * This method simply returns <code>getInputFile(null,null)</code>. * @see #getInputFile(Component, String) * @return the selected file, or null if the user did not select a file. */ public File getInputFile() { return getInputFile(null,null); } /** * Show a dialog box where the user can select a file for reading. * This method simply returns <code>getInputFile(parent,null)</code>. * @see #getInputFile(Component, String) * @return the selected file, or null if the user did not select a file. */ public File getInputFile(Component parent) { return getInputFile(parent,null); } /** * Show a dialog box where the user can select a file for reading. * If the user cancels the dialog by clicking its "Cancel" button or * the Close button in the title bar, then the return value of this * method is null. Otherwise, the return value is the selected file. * Note that the file has to exist, but it is not guaranteed that the * user is allowed to read the file. * @param parent If the parent is non-null, then the window that contains * the parent component becomes the parent window of the dialog box. This * means that the window is "blocked" until the dialog is dismissed. Also, * the dialog box's position on the screen should be based on the position of * the window. Generally, you should pass your application's main window or * panel as the value of this parameter. * @param dialogTitle a title to be displayed in the title bar of the dialog * box. If the value of this parameter is null, then the dialog title will * be "Select Input File". * @return the selected file, or null if the user did not select a file. */ public File getInputFile(Component parent, String dialogTitle) { if (dialog == null) dialog = new JFileChooser(); if (dialogTitle != null) dialog.setDialogTitle(dialogTitle); else dialog.setDialogTitle("Select Input File"); int option = dialog.showOpenDialog(parent); if (option != JFileChooser.APPROVE_OPTION) return null; // User canceled or clicked the dialog's close box. File selectedFile = dialog.getSelectedFile(); return selectedFile; } /** * Show a dialog box where the user can select a file for writing. * This method simply calls <code>getOutputFile(null,null,null)</code> * @see #getOutputFile(Component, String, String) * @return the selcted file, or null if no file was selected. */ public File getOutputFile() { return getOutputFile(null,null,null); } /** * Show a dialog box where the user can select a file for writing. * This method simply calls <code>getOutputFile(null,null,null)</code> * @see #getOutputFile(Component, String, String) * @return the selcted file, or null if no file was selected. */ public File getOutputFile(Component parent) { return getOutputFile(parent,null,null); } /** * Show a dialog box where the user can select a file for writing. * This method calls <code>getOutputFile(parent,dialogTitle,null)</code> * @see #getOutputFile(Component, String, String) * @return the selcted file, or null if no file was selected. */ public File getOutputFile(Component parent, String dialogTitle) { return getOutputFile(parent,dialogTitle,null); } /** * Show a dialog box where the user can select a file for writing. * If the user cancels the dialog by clicking its "Cancel" button or * the Close button in the title bar, then the return value of this * method is null. A non-null value indicates that the user specified * a file name and that, if the file exists, then the user wants to * replace that file. (If the user selects a file that already exists, * then the user will be asked whether to replace the existing file.) * Note that it is not quaranteed that the selected file is actually * writable; the user might not have permission to create or modify the file. * @param parent If the parent is non-null, then the window that contains * the parent component becomes the parent window of the dialog box. This * means that the window is "blocked" until the dialog is dismissed. Also, * the dialog box's position on the screen should be based on the position of * the window. Generally, you should pass your application's main window or * panel as the value of this parameter. * @param dialogTitle a title to be displayed in the title bar of the dialog * box. If the value of this parameter is null, then the dialog title will * be "Select Input File". * @param defaultFile when the dialog appears, this name will be filled in * as the name of the selected file. If the value of this parameter is null, * then the file name box will be empty. * @return the selected file, or null if the user did not select a file. */ public File getOutputFile(Component parent, String dialogTitle, String defaultFile) { 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 textcollage; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JFrame; /** * This main program simply shows a window that contains * a DrawTextPanel and the menu bar for that panel. */ public class TextCollage { public static void main(String[] args) { JFrame frame = new JFrame("Text Collage"); DrawTextPanel panel = new DrawTextPanel(); frame.setContentPane( panel ); frame.setJMenuBar(panel.getMenuBar()); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation( (screenSize.width - frame.getWidth())/2, (screenSize.height - frame.getHeight())/2 ); frame.setVisible(true); } }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

Working code implemented in Java and appropriate comments provided for better understanding:

Here I am attaching code for these files:

DrawTextItem.java
DrawTextPanel.java
SimpleFileChooser.java
TextCollage.java
Source code for DrawTextItem.java:

package textcollage;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;

/**
* An object of type DrawText can draw a string in
* a graphics context, with various effects, such as
* color, magnification, and rotation The string
* is specified in the constructor and cannot be changed.
* The position and other properties can be changed.
*/
public class DrawTextItem {
  
private final String string; // The String that is drawn by this item.
  
private Font font = null;
private int x = 0;
private int y = 0;
private Color textColor = Color.BLACK;
private Color background = null;
private boolean border = false;
private double rotationAngle = 0;
private double magnification = 1;
private double textTransparency = 0;
private double backgroundTransparency = 0;
  
/**
* Create a DrawTextItem to draw a specified string. Initially,
* the position is set to (0,0) and all properties have their
* default values.
* @throws NullPointerException if the parameter is null
*/
public DrawTextItem(String stringToDraw) {
this(stringToDraw,0,0);
}
  
/**
* Create a DrawTextItem to draw a specified string. Initially,
* the position is set to (x,y) and all other properties have their
* default values. Note that x and y give the position of
* the center of the string.
* @param x the x-coordinate where the string will be drawn.
* @param y the y-coordinate where the string will be drawn.
* @throws NullPointerException if the parameter is null
*/
public DrawTextItem(String stringToDraw, int x, int y) {
if (stringToDraw == null)
throw new NullPointerException("String can't be null.");
string = stringToDraw;
this.x = x;
this.y = y;
}
  
/**
* Draw this item's string in the given Graphics constext,
* applying all of this item's property settings.
* @param g the graphics context in which the string will
* be drawn. Note that this is assumed to be actually of
* type Graphics2D (which should not be a problem).
*/
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D)g.create();
if (font != null)
g2.setFont(font);
FontMetrics fm = g2.getFontMetrics();
int width = fm.stringWidth(string);
int height = fm.getAscent() + fm.getDescent();
g2.translate(x,y);
if (magnification != 1) {
float pixelSize = 1/(float)magnification;
g2.setStroke( new BasicStroke(pixelSize) ); // magnification won't apply to border
g2.scale(magnification,magnification);
}
if (rotationAngle > 0)
g2.rotate( -Math.PI * (rotationAngle / 180));
Color colorToUseForText = textColor;
if (colorToUseForText == null)
colorToUseForText = g2.getColor();
if (background != null) {
if (backgroundTransparency == 0)
g2.setColor(background);
else
g2.setColor( new Color( background.getRed(), background.getGreen(), background.getBlue(),
(int)(255*(1-backgroundTransparency))) );
g2.fillRect(-width/2 - 3, -height/2 - 3, width + 6, height + 6);
}
if (textTransparency == 0)
g2.setColor(colorToUseForText);
else
g2.setColor( new Color( colorToUseForText.getRed(),
colorToUseForText.getGreen(), colorToUseForText.getBlue(),
(int)(255*(1-textTransparency)) ) );
if (border)
g2.drawRect(-width/2 -3, -height/2 - 3, width + 6, height + 6);
g2.drawString(string,-width/2, -height/2 + fm.getAscent());
}

/**
* Returns the string that is drawn by this DrawTextItem. The
* string is set in the constructor and cannot be changed.
*/
public String getString() {
return string;
}

/**
* Set the background color. If the value is non-null, then
* a rectangle of this color is drawn behind the string.
* If the value is null, no background rectangle is drawn.
* The default value is null.
*/
public void setBackground(Color background) {
this.background = background;
}

/**
* Set the level of transparency of the background color, where 0 indicates
* no transparency and 1 indicates completely transparent. If the value
* is not 1, then the transparency level of the background color is set to
* this value. If the background color is null, then the value of
* backgroundTransparency is ignored. The default value is zero.
* @param backgroundTransparency the background transparency level, in the range 0 to 1
* @throws IllegalArgumentException if the parameter is less than 0 or greater than 1
*/
public void setBackgroundTransparency(double backgroundTransparency) {
if (backgroundTransparency < 0 || backgroundTransparency > 1)
throw new IllegalArgumentException("Transparency must be in the range 0 to 1.");
this.backgroundTransparency = backgroundTransparency;
}

/**
* If border is set to true, then a rectangular border is drawn around
* the string. The default value is false.
*/
public void setBorder(boolean border) {
this.border = border;
}

/**
* Sets the font to be used for drawing the string. A value of
* null indicates that the font that is set for the graphics context
* where the string is drawn should be used. The default value is
* null.
*/
public void setFont(Font font) {
this.font = font;
}

/**
* Set a magnification level that is applied when the string is drawn.
* A magnification of 2 will double the size; a value of 0.5 will cut
* it in half. Negative values will produce backwards, upside-down text.
* Zero is not a legal value, and an attempt to set the magnification to
* zero will cause an IllegalArgumentException. The default value is
* 1, Indicating no magnification.
*/
public void setMagnification(double magnification) {
if (magnification == 0)
throw new IllegalArgumentException("Magnification cannot be 0.");
this.magnification = magnification;
}

/**
* Sets the angle of the baseline of the string with respect to the
* horizontal. The angle is specified in degrees. The default is
* 0, which gives normal, unrotated, horizontal text.
*/
public void setRotationAngle(double rotationAngle) {
this.rotationAngle = rotationAngle;
}

/**
* Sets the color to be used for drawing the text (and the border if there is one).
* The default value is null, which means that the color that is set in the
* graphics context where the string is drawn will be used for drawing the text.
*/
public void setTextColor(Color textColor) {
this.textColor = textColor;
}

/**
* Set the level of transparency of the text color, where 0 indicates
* no transparency and 1 indicates completely transparent. If the value
* is not 1, then the transparency level of the text color is set to
* this value. This property is also applied to the border, if there is one.
* The default value is zero.
* @param textTransparency the text transparency level, in the range 0 to 1
* @throws IllegalArgumentException if the parameter is less than 0 or greater than 1
*/
public void setTextTransparency(double textTransparency) {
if (textTransparency < 0 || textTransparency > 1)
throw new IllegalArgumentException("Transparency must be in the range 0 to 1.");
this.textTransparency = textTransparency;
}

/**
* Set the x-coordinate where the string is drawn. This gives the position of
* the center of the string.
*/
public void setX(int x) {
this.x = x;
}

/**
* Set the y-coordinate where the string is drawn. This gives the position of
* the center of the string.
*/
public void setY(int y) {
this.y = y;
}

/**
* returns the value of the background color property
*/
public Color getBackground() {
return background;
}

/**
* returns the value of the background transparency property
*/
public double getBackgroundTransparency() {
return backgroundTransparency;
}

/**
* returns the value of the border property
*/
public boolean getBorder() {
return border;
}

/**
* returns the value of the font property
*/
public Font getFont() {
return font;
}

/**
* returns the value of the magnification property
*/
public double getMagnification() {
return magnification;
}

/**
* returns the value of the rotation angle property
*/
public double getRotationAngle() {
return rotationAngle;
}

/**
* returns the value of the text color property
*/
public Color getTextColor() {
return textColor;
}

/**
* returns the value of the text transparency property
*/
public double getTextTransparency() {
return textTransparency;
}

/**
* returns the x-coord of the center of the string
*/
public int getX() {
return x;
}

/**
* returns the y-coord of the center of the string
*/
public int getY() {
return y;
}

}

Source code for DrawTextPanel.java:

package textcollage;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

/**
* A panel that contains a large drawing area where strings
* can be drawn. The strings are represented by objects of
* type DrawTextItem. An input box under the panel allows
* the user to specify what string will be drawn when the
* user clicks on the drawing area.
*/
public class DrawTextPanel extends JPanel {

private ArrayList<DrawTextItem> theString = new ArrayList(); // list of DrawTextItems that will be displayed on the canvas
private Color currentTextColor = Color.BLACK; // Color applied to new strings.
private Canvas canvas; // the drawing area.
private JTextField input; // where the user inputs the string that will be added to the canvas
private JTextField rotation; // where the user inputs the angle that the string will be displayed
private SimpleFileChooser fileChooser; // for letting the user select files
private JMenuBar menuBar; // a menu bar with command that affect this panel
private MenuHandler menuHandler; // a listener that responds whenever the user selects a menu command
private JMenuItem undoMenuItem; // the "Remove Item" command from the edit menu


/**
* An object of type Canvas is used for the drawing area.
* The canvas simply displays all the DrawTextItems that
* are stored in the ArrayList, strings.
*/
private class Canvas extends JPanel {
Canvas() {
setPreferredSize( new Dimension( 800, 600 ) );
setBackground( Color.LIGHT_GRAY );
setFont( new Font( "Serif", Font.BOLD, 24 ) );
}

protected void paintComponent( Graphics g ) {
super.paintComponent( g );
( (Graphics2D) g ).setRenderingHint( RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON );
if ( theString != null ) {
for ( DrawTextItem item : theString ) { // loop through the list and draw each object
item.draw( g );
}
}
}
}

/**
* An object of type MenuHandler is registered as the ActionListener
* for all the commands in the menu bar. The MenuHandler object
* simply calls doMenuCommand() when the user selects a command
* from the menu.
*/
private class MenuHandler implements ActionListener {
public void actionPerformed( ActionEvent evt ) {
doMenuCommand( evt.getActionCommand() );
}
}

/**
* Creates a DrawTextPanel. The panel has a large drawing area and
* a text input box where the user can specify a string. When the
* user clicks the drawing area, the string is added to the drawing
* area at the point where the user clicked.
*/
public DrawTextPanel() {
fileChooser = new SimpleFileChooser();
undoMenuItem = new JMenuItem( "Remove Item" );
undoMenuItem.setEnabled( false );
menuHandler = new MenuHandler();
setLayout( new BorderLayout( 3, 3 ) );
setBackground( Color.BLACK );
setBorder( BorderFactory.createLineBorder( Color.BLACK, 2 ) );
canvas = new Canvas();
add( canvas, BorderLayout.CENTER );
JPanel bottom = new JPanel();
bottom.add( new JLabel( "Text to add: " ) );
input = new JTextField( "Hello World!", 30 );
bottom.add( input );
bottom.add( new JLabel( "Text Rotation: " ) ); // added rotation label
rotation = new JTextField( "0", 5 ); // added rotation field
bottom.add( rotation );
add( bottom, BorderLayout.SOUTH );
canvas.addMouseListener( new MouseAdapter() {
public void mousePressed( MouseEvent e ) {
doMousePress( e );
}
} );
}

/**
* This method is called when the user clicks the drawing area.
* A new string is added to the drawing area. The center of
* the string is at the point where the user clicked.
*
* @param e the mouse event that was generated when the user clicked
*/
public void doMousePress( MouseEvent e ) {
String text = input.getText().trim();
double angle;
try {
angle = Double.parseDouble( rotation.getText().trim() ); // parse the rotation text into a double
} catch ( NumberFormatException error ) {
JOptionPane.showMessageDialog( this, "Sorry, please use a valid number for the angle." );
angle = 0;
rotation.setText( "0" );
}
if ( angle > 360 ) { // dont let the angle rotate more then 360 degrees
angle = 360;
rotation.setText( "360" );
}
if ( text.length() == 0 ) {
input.setText( "Hello World!" );
text = "Hello World!";
}

DrawTextItem s = new DrawTextItem( text, e.getX(), e.getY() );
s.setTextColor( currentTextColor ); // Default is null, meaning default color of the canvas (black).

// SOME OTHER OPTIONS THAT CAN BE APPLIED TO TEXT ITEMS:
// s.setFont( new Font( "Serif", Font.ITALIC + Font.BOLD, 12 )); // Default is null, meaning font of canvas.
// s.setMagnification(3); // Default is 1, meaning no magnification.
// s.setBorder(true); // Default is false, meaning don't draw a border.
s.setRotationAngle( angle ); // Default is 0, meaning no rotation.
// s.setTextTransparency(0.3); // Default is 0, meaning text is not at all transparent.
// s.setBackground(Color.BLUE); // Default is null, meaning don't draw a background area.
// s.setBackgroundTransparency(0.7); // Default is 0, meaning background is not transparent.

theString.add( s ); // add this DrawTextItem to other DrawTextItem that get drawn on the canvas
undoMenuItem.setEnabled( true );
canvas.repaint();
}

/**
* Returns a menu bar containing commands that affect this panel. The menu
* bar is meant to appear in the same window that contains this panel.
*/
public JMenuBar getMenuBar() {
if ( menuBar == null ) {
menuBar = new JMenuBar();

String commandKey; // for making keyboard accelerators for menu commands
if ( System.getProperty( "mrj.version" ) == null )
commandKey = "control "; // command key for non-Mac OS
else
commandKey = "meta "; // command key for Mac OS

JMenu fileMenu = new JMenu( "File" );
menuBar.add( fileMenu );
JMenuItem saveItem = new JMenuItem( "Save..." );
saveItem.setAccelerator( KeyStroke.getKeyStroke( commandKey + "N" ) );
saveItem.addActionListener( menuHandler );
fileMenu.add( saveItem );
JMenuItem openItem = new JMenuItem( "Open..." );
openItem.setAccelerator( KeyStroke.getKeyStroke( commandKey + "O" ) );
openItem.addActionListener( menuHandler );
fileMenu.add( openItem );
fileMenu.addSeparator();
JMenuItem saveImageItem = new JMenuItem( "Save Image..." );
saveImageItem.addActionListener( menuHandler );
fileMenu.add( saveImageItem );

JMenu editMenu = new JMenu( "Edit" );
menuBar.add( editMenu );
undoMenuItem.addActionListener( menuHandler ); // undoItem was created in the constructor
undoMenuItem.setAccelerator( KeyStroke.getKeyStroke( commandKey + "Z" ) );
editMenu.add( undoMenuItem );
editMenu.addSeparator();
JMenuItem clearItem = new JMenuItem( "Clear" );
clearItem.addActionListener( menuHandler );
editMenu.add( clearItem );

JMenu optionsMenu = new JMenu( "Options" );
menuBar.add( optionsMenu );
JMenuItem colorItem = new JMenuItem( "Set Text Color..." );
colorItem.setAccelerator( KeyStroke.getKeyStroke( commandKey + "T" ) );
colorItem.addActionListener( menuHandler );
optionsMenu.add( colorItem );
JMenuItem bgColorItem = new JMenuItem( "Set Background Color..." );
bgColorItem.addActionListener( menuHandler );
optionsMenu.add( bgColorItem );

}
return menuBar;
}

/**
* Carry out one of the commands from the menu bar.
*
* @param command the text of the menu command.
*/
private void doMenuCommand( String command ) {
if ( command.equals( "Save..." ) ) { // save all the string info to a file
saveFile();
} else if ( command.equals( "Open..." ) ) { // read a previously saved file, and reconstruct the list of strings
readFile();
canvas.repaint(); // (you'll need this to make the new list of strings take effect)
} else if ( command.equals( "Clear" ) ) { // remove all strings
theString.removeAll( theString ); //remove all objects from the arraylist
undoMenuItem.setEnabled( false );
canvas.repaint();
} else if ( command.equals( "Remove Item" ) ) { // remove the most recently added string
theString.remove( theString.size() - 1 ); // Remove one object at a time from the list
if ( theString.size() == 0 ) {
undoMenuItem.setEnabled( false );
}
canvas.repaint();
} else if ( command.equals( "Set Text Color..." ) ) {
Color c = JColorChooser.showDialog( this, "Select Text Color", currentTextColor );
if ( c != null )
currentTextColor = c;
} else if ( command.equals( "Set Background Color..." ) ) {
Color c = JColorChooser.showDialog( this, "Select Background Color", canvas.getBackground() );
if ( c != null ) {
canvas.setBackground( c );
canvas.repaint();
}
} else if ( command.equals( "Save Image..." ) ) { // save a PNG image of the drawing area
File imageFile = fileChooser.getOutputFile( this, "Select Image File Name", "textimage.png" );
if ( imageFile == null )
return;
try {
// Because the image is not available, I will make a new BufferedImage and
// draw the same data to the BufferedImage as is shown in the panel.
// A BufferedImage is an image that is stored in memory, not on the screen.
// There is a convenient method for writing a BufferedImage to a file.
BufferedImage image = new BufferedImage( canvas.getWidth(), canvas.getHeight(),
BufferedImage.TYPE_INT_RGB );
Graphics g = image.getGraphics();
g.setFont( canvas.getFont() );
canvas.paintComponent( g ); // draws the canvas onto the BufferedImage, not the screen!
boolean ok = ImageIO.write( image, "PNG", imageFile ); // write to the file
if ( ok == false )
throw new Exception( "PNG format not supported (this shouldn't happen!)." );
} catch ( Exception e ) {
JOptionPane.showMessageDialog( this,
"Sorry, an error occurred while trying to save the image:\n" + e );
}
}
}

/**
* output the settings for the canvas background and
* the properties of each text item displayed on the canvas
* format:
* background: 255, 104, 004
* <p>
* StartTextItem
* text: Hello World!
* color: 0, 0, 0
* position: 250, 178
* rotation: 0.0
* EndTextItem
* ...
*/
private void saveFile() {
File objectFile = fileChooser.getOutputFile( this, "Select a File Name", "Unit6.dat" );
PrintWriter out = null;
Color bgColor = canvas.getBackground();
try {
FileOutputStream stream = new FileOutputStream( objectFile );
out = new PrintWriter( stream );

} catch ( FileNotFoundException e ) {
JOptionPane.showMessageDialog( this,
"Sorry, but an error occurred in making the file:\n" + e );
e.printStackTrace();
}

out.println( "background: " + bgColor.getRed() + ", " + bgColor.getBlue() + ", " + bgColor.getGreen() );
for ( DrawTextItem item : theString ) {
out.println();
out.println( "StartTextItem" );
out.println( " text: " + item.getString().trim() );
out.println( " color: " + item.getTextColor().getRed() + ", " +
item.getTextColor().getGreen() + ", " + item.getTextColor().getBlue() );
out.println( " position: " + item.getX() + ", " + item.getY() );
out.println( " rotation: " + item.getRotationAngle() );
out.println( "EndTextItem" );
}
out.flush();
out.close();
}

/**
* read a saved display file.
* format:
* background: 255, 104, 004
* <p>
* StartTextItem
* text: Hello World!
* color: 0, 0, 0
* position: 250, 178
* rotation: 0.0
* EndTextItem
* ...
*/
private void readFile() {
theString.removeAll( theString ); // clear the canvas if there is already text on it
File objectFile = fileChooser.getInputFile( this, "Select a File Name" );
Scanner scan = null;
Color textColor = Color.BLACK; //if color is not present default to black
DrawTextItem item;
double rotation = 0; // if rotation is not present default to 0
String text = "no Text"; // if text is not present default to 'no text'
Color bgColor = Color.WHITE; // if background is not present default to white
try {
Reader stream = new BufferedReader( new FileReader( objectFile ) );
scan = new Scanner( stream );
} catch ( FileNotFoundException e ) {
JOptionPane.showMessageDialog( this,
"Sorry, but an error occurred in reading the file:\n" + e );
e.printStackTrace();
}
while ( scan.hasNext() ) {
try {
String itemName = scan.nextLine(); // read a line at a time
System.out.println( itemName );
if ( itemName.contains( "background: " ) ) {
String[] value = itemName.split( ":", 2 )[ 1 ].split( "," ); // get the second group splitting on the first ':' then split on ','
int red = Integer.parseInt( value[ 0 ].trim() );
int green = Integer.parseInt( value[ 1 ].trim() );
int blue = Integer.parseInt( value[ 2 ].trim() );
canvas.setBackground( new Color( red, green, blue ) );
} else if ( itemName.contains( "StartTextItem" ) ) {
int x = 0;
int y = 0;
while ( !itemName.contains( "EndTextItem" ) ) {
itemName = scan.nextLine();
if ( itemName.contains( " text:" ) ) {
text = itemName.split( ":", 2 )[ 1 ].trim();
} else if ( itemName.contains( " color: " ) ) {
String[] value = itemName.split( ":", 2 )[ 1 ].split( "," ); // get the second group splitting on the first ':' then split on ','
int r = Integer.parseInt( value[ 0 ].trim() );
int g = Integer.parseInt( value[ 1 ].trim() );
int b = Integer.parseInt( value[ 2 ].trim() );
textColor = new Color( r, g, b );
} else if ( itemName.contains( " position: " ) ) {
String[] value = itemName.split( ":", 2 )[ 1 ].split( "," ); // get the second group splitting on the first ':' then split on ','
x = Integer.parseInt( value[ 0 ].trim() );
;
y = Integer.parseInt( value[ 1 ].trim() );
;
} else if ( itemName.contains( " rotation:" ) ) {
rotation = Double.parseDouble( itemName.split( ":", 2 )[ 1 ].trim() );
}
}
System.out.printf( "item: text: '%s', RGB: %d %d %d, position: x: %d, y: %d, rotation: %.2f%n", text, textColor.getRed(), textColor.getBlue(), textColor.getGreen(), x, y, rotation );
item = new DrawTextItem( text, x, y );
item.setTextColor( textColor );
item.setRotationAngle( rotation );
theString.add( item );
}
} catch ( Exception e ) { // if something goes wrong. most likely a parsing error
JOptionPane.showMessageDialog( this,
"An Error occurred in parsing the file:\n" + e );
e.printStackTrace();
}
}
scan.close(); // close the file
}
}

Source code for SimpleFileChooser.java:

package textcollage;
import java.awt.Component;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
* This class provides a slightly simplified interface to one of Java's
* standard JFileChooser dialogs. An object of type SimpleFileChooser
* has methods that allow the user to select files for input or output.
* If the object is used several times, the same JFileChooser is used
* each time. By default, the dialog box is set to the user's home
* directory the first time it is used, and after that it remembers the
* current directory between one use and the next. However, methods
* are provided for setting the current directory. (Note: On Windows,
* the user's home directory will probably mean the user's "My Documents"
* directory".)
*/
public class SimpleFileChooser {

private JFileChooser dialog; // The dialog, which is created when needed.

/**
* Reset the default directory in the dialog box to the user's home
* directory. The next time the dialog appears, it will show the
* contents of that directory.
*/
public void setDefaultDirectory() {
if (dialog != null)
dialog.setCurrentDirectory(null);
}

/**
* Set the default directory for the dialog box. The next time the
* dialog appears, it will show the contents of that directory.
* @param directoryName A File object that specifies the directory name.
* If this name is null, then the user's home directory will be used.
*/
public void setDefaultDirectory(String directoryName) {
if (dialog == null)
dialog = new JFileChooser();
dialog.setCurrentDirectory(new File(directoryName));
}

/**
* Set the default directory for the dialog box. The next time the
* dialog appears, it will show the contents of that directory.
* @param directoryName The name of the new default directory. If the
* name is null, then the user's home directory will be used.
*/
public void setDefaultDirectory(File directory) {
if (dialog == null)
dialog = new JFileChooser();
dialog.setCurrentDirectory(directory);
}
  
/**
* Show a dialog box where the user can select a file for reading.
* This method simply returns <code>getInputFile(null,null)</code>.
* @see #getInputFile(Component, String)
* @return the selected file, or null if the user did not select a file.
*/
public File getInputFile() {
return getInputFile(null,null);
}

/**
* Show a dialog box where the user can select a file for reading.
* This method simply returns <code>getInputFile(parent,null)</code>.
* @see #getInputFile(Component, String)
* @return the selected file, or null if the user did not select a file.
*/
public File getInputFile(Component parent) {
return getInputFile(parent,null);
}

/**
* Show a dialog box where the user can select a file for reading.
* If the user cancels the dialog by clicking its "Cancel" button or
* the Close button in the title bar, then the return value of this
* method is null. Otherwise, the return value is the selected file.
* Note that the file has to exist, but it is not guaranteed that the
* user is allowed to read the file.
* @param parent If the parent is non-null, then the window that contains
* the parent component becomes the parent window of the dialog box. This
* means that the window is "blocked" until the dialog is dismissed. Also,
* the dialog box's position on the screen should be based on the position of
* the window. Generally, you should pass your application's main window or
* panel as the value of this parameter.
* @param dialogTitle a title to be displayed in the title bar of the dialog
* box. If the value of this parameter is null, then the dialog title will
* be "Select Input File".
* @return the selected file, or null if the user did not select a file.
*/
public File getInputFile(Component parent, String dialogTitle) {
if (dialog == null)
dialog = new JFileChooser();
if (dialogTitle != null)
dialog.setDialogTitle(dialogTitle);
else
dialog.setDialogTitle("Select Input File");
int option = dialog.showOpenDialog(parent);
if (option != JFileChooser.APPROVE_OPTION)
return null; // User canceled or clicked the dialog's close box.
File selectedFile = dialog.getSelectedFile();
return selectedFile;
}
  
/**
* Show a dialog box where the user can select a file for writing.
* This method simply calls <code>getOutputFile(null,null,null)</code>
* @see #getOutputFile(Component, String, String)
* @return the selcted file, or null if no file was selected.
*/
public File getOutputFile() {
return getOutputFile(null,null,null);
}

/**
* Show a dialog box where the user can select a file for writing.
* This method simply calls <code>getOutputFile(null,null,null)</code>
* @see #getOutputFile(Component, String, String)
* @return the selcted file, or null if no file was selected.
*/
public File getOutputFile(Component parent) {
return getOutputFile(parent,null,null);
}

/**
* Show a dialog box where the user can select a file for writing.
* This method calls <code>getOutputFile(parent,dialogTitle,null)</code>
* @see #getOutputFile(Component, String, String)
* @return the selcted file, or null if no file was selected.
*/
public File getOutputFile(Component parent, String dialogTitle) {
return getOutputFile(parent,dialogTitle,null);
}


/**
* Show a dialog box where the user can select a file for writing.
* If the user cancels the dialog by clicking its "Cancel" button or
* the Close button in the title bar, then the return value of this
* method is null. A non-null value indicates that the user specified
* a file name and that, if the file exists, then the user wants to
* replace that file. (If the user selects a file that already exists,
* then the user will be asked whether to replace the existing file.)
* Note that it is not quaranteed that the selected file is actually
* writable; the user might not have permission to create or modify the file.
* @param parent If the parent is non-null, then the window that contains
* the parent component becomes the parent window of the dialog box. This
* means that the window is "blocked" until the dialog is dismissed. Also,
* the dialog box's position on the screen should be based on the position of
* the window. Generally, you should pass your application's main window or
* panel as the value of this parameter.
* @param dialogTitle a title to be displayed in the title bar of the dialog
* box. If the value of this parameter is null, then the dialog title will
* be "Select Input File".
* @param defaultFile when the dialog appears, this name will be filled in
* as the name of the selected file. If the value of this parameter is null,
* then the file name box will be empty.
* @return the selected file, or null if the user did not select a file.
*/
public File getOutputFile(Component parent,
String dialogTitle, String defaultFile) {
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.
}
}
}

}

Source code for TextCollage.java:

package textcollage;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;

/**
* This main program simply shows a window that contains
* a DrawTextPanel and the menu bar for that panel.
*/
public class TextCollage {
  
public static void main(String[] args) {
JFrame frame = new JFrame("Text Collage");
DrawTextPanel panel = new DrawTextPanel();
frame.setContentPane( panel );
frame.setJMenuBar(panel.getMenuBar());
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation( (screenSize.width - frame.getWidth())/2,
(screenSize.height - frame.getHeight())/2 );
frame.setVisible(true);
}

}

Sample Output Screenshots:

- x Text Collage File Edit Options Hello World! Hello World! Hello World! Hello World! Hello World! Text to add: Hello World!

#please consider my effort and give me a like...thank u.....

Add a comment
Know the answer?
Add Answer to:
could you please help me with this problem, also I need a little text so I...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Practically dying here with this, need help ASAP, just need to do hide(), hideBoth(), and matchFound(),...

    Practically dying here with this, need help ASAP, just need to do hide(), hideBoth(), and matchFound(), then implement them, so far in my version i tentatively made them, but I don't know ho to implement them so i posted the original code before i made my version of the three methods listed above. Need help fast, this is ridiculous. Implement just one requirement at a time. For example, try implementing the case where after the user clicks 2 squares, both...

  • Hi. Could you help me with the code below? I need to validate the code below, using expressions that can carry out the actions or that make appropriate changes to the program’s state, using conditiona...

    Hi. Could you help me with the code below? I need to validate the code below, using expressions that can carry out the actions or that make appropriate changes to the program’s state, using conditional and iterative control structures that repeat actions as needed. The unit measurement is missing from the final output and I need it to offer options to lbs, oz, grams, tbsp, tsp, qt, pt, and gal. & fl. oz. Can this be added? The final output...

  • Lab Assignment : In this lab, you are going to implement QueueADT interface that defines a...

    Lab Assignment : In this lab, you are going to implement QueueADT interface that defines a queue. Then you are going to use the queue to store animals. 1. Write a LinkedQueue class that implements the QueueADT.java interface using links. 2. Textbook implementation uses a count variable to keep track of the elements in the queue. Don't use variable count in your implementation (points will be deducted if you use instance variable count). You may use a local integer variable...

  • I need help with adding comments to my code and I need a uml diagram for...

    I need help with adding comments to my code and I need a uml diagram for it. PLs help.... Zipcodeproject.java package zipcodesproject; import java.util.Scanner; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Zipcodesproject { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input=new Scanner(System.in); BufferedReader reader; int code; String state,town; ziplist listOFCodes=new ziplist(); try { reader = new BufferedReader(new FileReader("C:UsersJayDesktopzipcodes.txt")); String line = reader.readLine(); while (line != null) { code=Integer.parseInt(line); line =...

  • how would i do subdirectory because i want to be able to grab all subdirectory out...

    how would i do subdirectory because i want to be able to grab all subdirectory out of a directory and still be able to get add them I have a subdirectory called testFolder in it contains the following: defaulfolder.1 defaultfolder defaultfolder2.1 defaultfolder2 I only want to be able to grab the default folder without the "." i would like to get a test output of the answers import java.io.File; import java.util.ArrayList; import java.util.List; public class checkFile { private List<File> tests;...

  • I started this but need to convert it using JavaFX import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage;...

    I started this but need to convert it using JavaFX import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.Font; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ArtProject { public static void main(String[] args) throws IOException { /*this will be the size of the rectangle background with circles inside the image*/ int width = 400; int height = 250; int circleWidth = height; //create an image object BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); //this sets the...

  • pls help me with it. you just need to answer the question in Appointment.Java, There is...

    pls help me with it. you just need to answer the question in Appointment.Java, There is only 1 question u need to answer! Appointment.Java package option1.stage3; import option1.stage1.Doctor; import option1.stage1.Patient; import option1.stage2.TimeSlot; public class Appointment { private Doctor doctor; private Patient patient; private TimeSlot timeSlot; public Doctor getDoctor() { return doctor; } public void setDoctor(Doctor doctor) { this.doctor = doctor; } public Patient getPatient() { return patient; } public void setPatient(Patient patient) { this.patient = patient; } public TimeSlot getTimeSlot()...

  • Hey I really need some help asap!!!! I have to take the node class that is...

    Hey I really need some help asap!!!! I have to take the node class that is in my ziplist file class and give it it's own file. My project has to have 4 file classes but have 3. The Node class is currently in the ziplist file. I need it to be in it's own file, but I am stuck on how to do this. I also need a uml diagram lab report explaining how I tested my code input...

  • Please help me fix my errors. I would like to read and write the text file...

    Please help me fix my errors. I would like to read and write the text file in java. my function part do not have errors. below is my code import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.IOException; public class LinkedList {    Node head;    class Node    {        int data;        Node next;       Node(int d)        {            data = d;            next = null;        }    }    void printMiddle()    {        Node slow_ptr...

  • import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow...

    import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow for simple graphical drawing on a canvas. * This is a modification of the general purpose Canvas, specially made for * the BlueJ "shapes" example. * * @author: Bruce Quig * @author: Michael Kolling (mik) * Minor changes to canvas dimensions by William Smith 6/4/2012 * * @version: 1.6 (shapes) */ public class Canvas { // Note: The implementation of this class (specifically the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT