Hey guys,

I've been looking around the web but can't find a definite answer for this one.

I have a program I'm making and I want to cut down my lines by using an array and just have it create my lines for me.

I have this set up

String[] colors = new String {"red", "yellow", "green"};
for (int i = 0; i < colors.length; i++) {
     textarea.setBackground(Color.colors[i]);
}

this is my logic, bit it doesn't work...

so in my array i thought of doing this

String[] colors = new String {".setBackground(Color.red)".. etc};

then have maybe a string or something to show

"textarea" + colors[i];

but i'm not sure how to get that to work, or pass the string into my code and not as output to the user.

Edited 6 Years Ago by s2xi: n/a

can u elaborate it.. or add rest of the code so that we can compile it and test

Ya sure, What I'm trying to do is in the Edit Menu have the Change Font and Background Colors automated by an array much Like I did with filling in the names for the colors off a String array.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Event;
import java.awt.FileDialog;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.Document;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

public class mstp extends JFrame {
	private JTextArea textarea = new JTextArea();
	static int WIDTH  = 500;
	static int HEIGHT = 350;
	String filename;
	Clipboard clip = getToolkit().getSystemClipboard();
	JLabel statusInfo;

	// Undo and Redo features
	private   Document    editorPaneDocument;
	protected UndoHandler undoHandler = new UndoHandler();
	protected UndoManager undoManager = new UndoManager();
	private   undoAction  undoAction  = null;
	private   redoAction  redoAction  = null;

	// File Menu Items
	private JMenuItem newF = new JMenuItem("New File");
	private JMenuItem open = new JMenuItem("Open...");
    private JMenuItem save = new JMenuItem("Save...");
    private JMenuItem quit = new JMenuItem("Quit...");
    
    // Edit Menu Items
    String undo = ("Undo");
    String redo = ("Redo");
    
    String[] fontColors = new String[] {"Red","Pink","Orange","Yellow","Green","Gray","Black","White"};
    String[] bgColors   = new String[] {"Red","Pink","Orange","Yellow","Green","Gray","Black","White"};
    
    //private JMenuItem undo					= new JMenuItem("Undo");
    //private JMenuItem redo					= new JMenuItem("Redo");
    private JMenuItem copy                  = new JMenuItem("Copy");
    private JMenuItem cut                   = new JMenuItem("Cut");
    private JMenuItem paste                 = new JMenuItem("Paste");
    private JMenuItem selectAll             = new JMenuItem("Select All");
    private JMenu changeFontColor           = new JMenu("Change Text Color");
//    	private JMenuItem redFC			        = new JMenuItem ("Red");
//    	private JMenuItem pinkFC			    = new JMenuItem ("Pink");
//    	private JMenuItem orangeFC			    = new JMenuItem ("Orange");
//    	private JMenuItem yellowFC			    = new JMenuItem ("Yellow");
//    	private JMenuItem greenFC		    	= new JMenuItem ("Green");
//    	private JMenuItem grayFC				= new JMenuItem ("Gray");
//    	private JMenuItem blackFC				= new JMenuItem ("Black");
//    	private JMenuItem whiteFC				= new JMenuItem ("White");
    private JMenu changeBackgroundColor     = new JMenu("Change Background Color");
//    	private JMenuItem redBG			    	= new JMenuItem ("Red");
//    	private JMenuItem pinkBG				= new JMenuItem ("Pink");
//    	private JMenuItem orangeBG				= new JMenuItem ("Orange");
//    	private JMenuItem yellowBG				= new JMenuItem ("Yellow");
//    	private JMenuItem greenBG				= new JMenuItem ("Green");
//    	private JMenuItem grayBG				= new JMenuItem ("Gray");
//    	private JMenuItem blackBG				= new JMenuItem ("Black");
//    	private JMenuItem whiteBG				= new JMenuItem ("White");
    
    // Tools Menu Items
    private JMenuItem wordCount = new JMenuItem("Word Count");
    private JMenuItem search    = new JMenuItem("Search");
    
    // Help Menu Items
    private JMenuItem about = new JMenu("About");
	
mstp() {
	
	editorPaneDocument = textarea.getDocument();
	editorPaneDocument.addUndoableEditListener(undoHandler);
	
	// Activates the use of the CTRL+Z and CTRL+Y key combinations
	KeyStroke undoKeystroke = KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.META_MASK);
	KeyStroke redoKeystroke = KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.META_MASK);
	
	undoAction = new undoAction();
	textarea.getInputMap().put(undoKeystroke, "undoKeystroke");
	textarea.getActionMap().put("undoKeystroke", undoAction);

	redoAction = new redoAction();
	textarea.getInputMap().put(redoKeystroke, "redoKeystroke");
	textarea.getActionMap().put("redoKeystroke", redoAction);
	
	// Main content panel
	JPanel content = new JPanel();
	
	content.setLayout(new BorderLayout());
	content.add(new JScrollPane(textarea), BorderLayout.CENTER);  
	statusInfo = new JLabel();
	content.add(statusInfo, BorderLayout.SOUTH);
	
	// Window
	this.setTitle("mySimpleTextPad | CIS 355A Final Project");
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    
	this.setJMenuBar(menubar());
	//this.setJToolBar(searchbar);
	this.setContentPane(content);
	this.pack();
}

// Create toolbar
public JMenuBar menubar() {
	
    JMenuBar menubar = new JMenuBar();
    	// File Menu
    	JMenu fileMenu = new JMenu("File");
    		menubar.add(fileMenu);
    			fileMenu.add(newF);
    				newF.addActionListener(new newFAction());
    			fileMenu.addSeparator();
    			fileMenu.add(open);
    				open.addActionListener(new openAction());
    			fileMenu.add(save);
    				save.addActionListener(new saveAction());
    			fileMenu.addSeparator();
    			fileMenu.add(quit);
    				quit.addActionListener(new quitAction());
    	// Edit Menu    		
    	JMenu editMenu = new JMenu("Edit");
    		editMenu.setMnemonic(KeyEvent.VK_E); // CTRL+E expands the Edit Menu
    		menubar.add(editMenu);
    			editMenu.add(undoAction);
    			editMenu.add(redoAction);
    			editMenu.addSeparator();
    			editMenu.add(copy);
    				copy.addActionListener(new copyAction());
    			editMenu.add(cut);
    				cut.addActionListener(new cutAction());
    			editMenu.add(paste);
    				paste.addActionListener(new pasteAction());
    			editMenu.addSeparator();
    			editMenu.add(selectAll);
    				selectAll.addActionListener(new selectAllAction());
    			editMenu.addSeparator();
    			editMenu.add(changeFontColor);
    				for (int i = 0; i < fontColors.length; i++) {
    					JMenuItem fontC = new JMenuItem(fontColors[i]);
    					fontC.addActionListener(new fontColorAction());
    					changeFontColor.add(fontC);
    				}
//    					redFC.addActionListener(new redFontAction());
//    					pinkFC.addActionListener(new pinkFontAction());
//    					orangeFC.addActionListener(new orangeFontAction());
//    					yellowFC.addActionListener(new yellowFontAction());
//    					greenFC.addActionListener(new greenFontAction());
//    					grayFC.addActionListener(new grayFontAction());
//    					blackFC.addActionListener(new blackFontAction());
//    					whiteFC.addActionListener(new whiteFontAction());
    			editMenu.add(changeBackgroundColor);
					for (int i = 0; i < fontColors.length; i++) {
						JMenuItem fontC = new JMenuItem(bgColors[i]);
						fontC.addActionListener(new fontColorAction());
						changeBackgroundColor.add(fontC);
					}
//						redBG.addActionListener(new redBackgroundAction());
//						pinkBG.addActionListener(new pinkBackgroundAction());
//						orangeBG.addActionListener(new orangeBackgroundAction());
//						yellowBG.addActionListener(new yellowBackgroundAction());
//						greenBG.addActionListener(new greenBackgroundAction());
//						grayBG.addActionListener(new grayBackgroundAction());
//						blackBG.addActionListener(new blackBackgroundAction());
//						whiteBG.addActionListener(new whiteBackgroundAction());
    	// Tools Menu
    	JMenu toolsMenu = new JMenu("Tools");
    		menubar.add(toolsMenu);
    			toolsMenu.add(wordCount);
    			toolsMenu.add(search);
    	// Help Menu
    	JMenu helpMenu = new JMenu("Help");
    		menubar.add(helpMenu);
    			helpMenu.add(about);
    			
    return menubar;
 }

////////// File Menu Item Classes ////////////

// Class: New
private class newFAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		//textarea.setText(""); //This will clear all the current content and not open a new window
		JFrame mstp = new mstp();    // This will make a new instance of the construction mstp, BUT will
		mstp.setSize(WIDTH, HEIGHT); // attach all actions belonging to mstp to the new window
		mstp.setVisible(true);	  	 // which means, that if you Quit the one window, it will close
								     // ALL windows who belong to the mstp()
	}
}
//Class: Open
private class openAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		FileDialog openFile = new FileDialog (mstp.this, "Open File", FileDialog.LOAD);
	    openFile.setFile ("*.java;*.txt");  // Set initial filename filter
	    openFile.show(); // Blocks
	    String curFile;
	    if ((curFile = openFile.getFile()) != null) {
	    	String filename = openFile.getDirectory() + curFile;
	    	char[] data;
	    	setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
	    	File f = new File (filename);
	    	try {
	    		FileReader fin = new FileReader (f);
	    		int filesize = (int)f.length();
	    		data = new char[filesize];
	    		fin.read (data, 0, filesize);
	    		textarea.setText (new String (data));
	    		statusInfo.setText ("Loaded: " + filename);
	    	} catch (FileNotFoundException exc) {
	    		statusInfo.setText ("File Not Found: " + filename);
	    	} catch (IOException exc) {
	    		statusInfo.setText ("IOException: " + filename);
	    	}
	    	setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	    }
	}
}
// Class: Save
private class saveAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		FileDialog file = new FileDialog (mstp.this, "Save File", FileDialog.SAVE);
		file.show(); // Blocks
		String curFile;
		if ((curFile = file.getFile()) != null) {
			String filename = file.getDirectory() + curFile + ".txt";
			setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			File f = new File (filename);
			try {
				FileWriter fw = new FileWriter (f);
				String text = textarea.getText();
				int textsize = text.length();
				fw.write (textarea.getText(), 0, textsize);
				fw.close ();
				statusInfo.setText ("Saved: " + filename);
			} catch (IOException exc) {
				statusInfo.setText ("IOException: " + filename);
			}
		setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		}
	}
}
// Class: Quit
private class quitAction implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }
}
////////// Edit Menu Item Classes //////////
class UndoHandler implements UndoableEditListener {
	public void undoableEditHappened(UndoableEditEvent e) {
		undoManager.addEdit(e.getEdit());
		undoAction.update();
		redoAction.update();
	}
}

// Class: Undo
class undoAction extends AbstractAction {
	public undoAction() {
		super(undo);
		setEnabled(false);
	}
	public void actionPerformed(ActionEvent e) {
		try{
			undoManager.undo();
		}catch(CannotUndoException ex){	}
		update();
		redoAction.update();
	}
	protected void update() {
		if (undoManager.canUndo()) {
			setEnabled(true);
			putValue(Action.NAME, undoManager.getUndoPresentationName());
		}else{
			setEnabled(false);
			//System.out.print(undo);
			//putValue(undo.substring(0, 4), Action.NAME);
		}
	}
}

//Class: Redo
class redoAction extends AbstractAction {
	public redoAction() {
		super(redo.substring(0, 4));
		setEnabled(false);
	}
	public void actionPerformed(ActionEvent e) {
		try{
			undoManager.redo();
		}catch(CannotRedoException ex){ }
		update();
		undoAction.update();
	}
	protected void update() {
		if (undoManager.canRedo()) {
			setEnabled(true);
			putValue(Action.NAME, undoManager.getRedoPresentationName());
		}else{
			setEnabled(false);
			//System.out.print(redo);
			//putValue(redo.substring(0, 4), Action.NAME);
		}
	}
}

//Class: Copy
private class copyAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
    String sel = textarea.getSelectedText();
    StringSelection clipString = new StringSelection(sel);
    clip.setContents(clipString,clipString);
	}
}

//Class: Cut
private class cutAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		String sel = textarea.getSelectedText();
		StringSelection ss = new StringSelection(sel);
		clip.setContents(ss,ss);
		textarea.replaceRange(" ",textarea.getSelectionStart(),textarea.getSelectionEnd());
	}
}

//Class: Paste
class pasteAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		Transferable cliptran = clip.getContents(mstp.this);
        try{
        	String sel = (String) cliptran.getTransferData(DataFlavor.stringFlavor);
            textarea.replaceRange(sel,textarea.getSelectionStart(),textarea.getSelectionEnd());
        }catch(Exception exc){
            System.out.println("not string flavour");
        }
    }
}

// Class: Select All
private class selectAllAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.selectAll();
	}
}

// Class: Font Color Array Classes
private class fontColorAction implements ActionListener {
	String[] fontColorArray = new String[] {"setForeground(Color.RED);", "setForeground(Color.PINK);", "setForeground(Color.ORANGE);","setForeground(Color.YELLOW);","setForeground(Color.GREEN);","setForeground(Color.GRAY);","setForeground(Color.BLACK);","setForeground(Color.WHITE);"};
	public void actionPerformed(ActionEvent e) {
		
		for (int i = 0; i < 0; i++) {
		String show = ("textarea." + fontColorArray[i]);
		}
	}
}
	// Class: Red Font Color
private class redFontAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setForeground(Color.RED);
	}
}

//Class: Pink Font Color
private class pinkFontAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setForeground(Color.PINK);
	}
}

//Class: Orange Font Color
private class orangeFontAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setForeground(Color.ORANGE);
	}
}

//Class: Yellow Font Color
private class yellowFontAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setForeground(Color.YELLOW);
	}
}

//Class: Green Font Color
private class greenFontAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setForeground(Color.GREEN);
	}
}

//Class: Gray Font Color
private class grayFontAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setForeground(Color.GRAY);
	}
}

//Class: Black Font Color
private class blackFontAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setForeground(Color.BLACK);
	}
}

//Class: White Font Color
private class whiteFontAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setForeground(Color.WHITE);
	}
}

//Class: Red Background Color
private class redBackgroundAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setBackground(Color.RED);
	}
}

//Class: Pink Background Color
private class pinkBackgroundAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setBackground(Color.PINK);
	}
}

//Class: Orange Background Color
private class orangeBackgroundAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setBackground(Color.ORANGE);
	}
}

//Class: Yellow Background Color
private class yellowBackgroundAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setBackground(Color.YELLOW);
	}
}

//Class: Green Background Color
private class greenBackgroundAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setBackground(Color.GREEN);
	}
}

//Class: Gray Background Color
private class grayBackgroundAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setBackground(Color.GRAY);
	}
}

//Class: Black Background Color
private class blackBackgroundAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setBackground(Color.BLACK);
	}
}

//Class: White Background Color
private class whiteBackgroundAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		textarea.setBackground(Color.WHITE);
	}
}
	
	//Main
	public static void main(String[] args) {
		JFrame mstp = new mstp();
		mstp.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		mstp.setSize(WIDTH, HEIGHT);
		mstp.setVisible(true);
	}
}

try this

Color[] colorArr = new Color[] {Color.red,Color.pink,Color.orange,Color.yellow,Color.green,Color.gray,Color.black,Color.white};

and u can iterate it like this...

for (int i = 0; i < colorArr.length; i++) {
	textarea.setBackground(colorArr[i]);
	}

I am not changing ur String[] bgColors as u r using it in
JMenuItem fontC = new JMenuItem(bgColors);

Edited 6 Years Ago by vchandra: n/a

try this

Color[] colorArr = new Color[] {Color.red,Color.pink,Color.orange,Color.yellow,Color.green,Color.gray,Color.black,Color.white};

and u can iterate it like this...

for (int i = 0; i < colorArr.length; i++) {
	textarea.setBackground(colorArr[i]);
	}

I am not changing ur String[] bgColors as u r using it in
JMenuItem fontC = new JMenuItem(bgColors);

well they would all be the same as setForeground and setBackground are the same exact functions but just used to change different aspects of the text.

where would I add your array? I saw how it was accepted into the

textarea.setBackground(colorArr[i]);

so that made me happy ;) but Its not getting applied in reference to ActionListener. Any tips?

update: I forgot to the add colorArr.length correctly. But now it turns all my text white, the last value in the array. How would this array be able to match correctly with the String array that labels the colors?

Edited 6 Years Ago by s2xi: n/a

This article has been dead for over six months. Start a new discussion instead.