Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    13
    Rep Power
    0

    Question GUI Calculator - How do I change the text color & set a background image?


    Hello! I had a project in my Java class which worked out great. We had to create a GUI Calculator, I got it running fine. The problem is that it is ugly. I have been trying to find some information on setting some of the keys with a different text color and maybe a background image. The keys are in rows/columns 5x5 with 10x10 pixels between them. I was wanting to add an image to the background that would be seen between the keys. If anyone knows anything about adding the colored text and background image please let me know. I can post the code if requested. (It is about 250+ lines) Thanks in advance.

    -Jay
  2. #2
  3. <?PHP user_title("gimp"); ?>
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2005
    Location
    Internet
    Posts
    7,652
    Rep Power
    6084
    Sally and Bobby go to the store. It is seven o'clock and might rain soon, but is still light out. How much money did they spend at the store?

    Notice how this had absolutely no relevant information? Neither did your post. You never specified what kind of text you're changing and what classes control that text. Nor have you said what kind of Object you're looking to give a background image to.

    Now let's do one thing more, which is pretend we have a valuable asset called a "search engine" at out disposal. Let's take a wild guess: What were to happen if you used this "search engine" to find out how to add a background by searching for whatever object you want to add a background to, along with the words "background image"? Or the same for text. What kind of results do you think you'd get?
    Last edited by gimp; November 10th, 2009 at 11:28 PM.
    Chat Server Project & Tutorial | WiFi-remote-control sailboat (building) | Joke Thread
    “Rational thinkers deplore the excesses of democracy; it abuses the individual and elevates the mob. The death of Socrates was its finest fruit.”
    Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. Use TODO to leave yourself reminders. Calling a program finished before all these points are checked off is lazy.
    -Partial Credit: Sun

    If I ask you to redescribe your problem, it's because when you describe issues in detail, you often get a *click* and you suddenly know the solutions.
    Ches Koblents
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    13
    Rep Power
    0

    Angry Search Engine? Whats that?


    Originally Posted by gimp
    Sally and Bobby go to the store. It is seven o'clock and might rain soon, but is still light out. How much money did they spend at the store?

    Notice how this had absolutely no relevant information? Neither did your post. You never specified what kind of text you're changing and what classes control that text. Nor have you said what kind of Object you're looking to give a background image to.

    Now let's do one thing more, which is pretend we have a valuable asset called a "search engine" at out disposal. Let's take a wild guess: What were to happen if you used this "search engine" to find out how to add a background by searching for whatever object you want to add a background to, along with the words "background image"? Or the same for text. What kind of results do you think you'd get?
    Been there done that, couldn't find what I wanted. Thats why I got on here, just for the sarcasm. It is a bit lenghty, so I will post in a bit after I get up and get my head together. Until then maybe go read a childrens story to hold you over, maybe call Sally and Bobby and ask if you can go with them, maybe they will buy you a lolly pop. Bring your rain coat.

    -Jay
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2009
    Posts
    119
    Rep Power
    0
    Originally Posted by jaysonjohnson
    Hello! I had a project in my Java class which worked out great. We had to create a GUI Calculator, I got it running fine. The problem is that it is ugly. I have been trying to find some information on setting some of the keys with a different text color and maybe a background image. The keys are in rows/columns 5x5 with 10x10 pixels between them. I was wanting to add an image to the background that would be seen between the keys. If anyone knows anything about adding the colored text and background image please let me know. I can post the code if requested. (It is about 250+ lines) Thanks in advance.

    -Jay
    use the setColor method()
    or the setBackground method()


    Code:
    // Make a text area, set its font and color, then add it to the frame
            TextArea text = new TextArea();
            Font font = new Font("Serif", Font.ITALIC, 20);
            text.setFont(font);
            text.setForeground(Color.blue);
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    13
    Rep Power
    0

    Red face Calculator Code


    Ok, I know the TextArea() method. My question is, where would I implement it in the program? I want to change the text that is inside the buttons, i.e. the numbers. And between the buttons display an image. One big image would be best that is in the background and can be seen between the buttons. I have included the code. Thanks in advance.

    java Code:
     
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
     
    public class Calculator extends Frame implements ActionListener
    {	//Declares Private Variables
    	private Button keys[];
    	private Panel keypad;
    	private TextField lcd;
    	private double op1;
    	private boolean first;
    	private boolean foundKey;
    	private boolean clearText;
    	private int last0p;
    	private DecimalFormat calcPattern;
     
    	public Calculator()
    	{
    		//create an instance of the menu
    		MenuBar mnuBar = new MenuBar();
    		setMenuBar(mnuBar);
     
    		//construct and populate the File menu
    		Menu mnuFile = new Menu("File", true);
    		mnuBar.add(mnuFile);
    			MenuItem mnuFileExit = new MenuItem("Exit");
    			mnuFile.add(mnuFileExit);
     
    		//construct and populate the Edit menu
    		Menu mnuEdit = new Menu("Edit", true);
    		mnuBar.add(mnuEdit);
    			MenuItem mnuEditClear = new MenuItem("Clear");
    			mnuEdit.add(mnuEditClear);
    			mnuEdit.insertSeparator(1);
    			MenuItem mnuEditCopy = new MenuItem("Copy");
    			mnuEdit.add(mnuEditCopy);
    			MenuItem mnuEditPaste = new MenuItem("Paste");
    			mnuEdit.add(mnuEditPaste);
     
    		//construct and populate the About Menu
    		Menu mnuAbout = new Menu("About", true);
    			mnuBar.add(mnuAbout);
    			MenuItem mnuAboutCalculator = new MenuItem("About Calculator");
    			mnuAbout.add(mnuAboutCalculator);
     
    		//add the ActionListener to each menu item
    		mnuFileExit.addActionListener(this);
    		mnuEditClear.addActionListener(this);
    		mnuEditCopy.addActionListener(this);
    		mnuEditPaste.addActionListener(this);
    		mnuAboutCalculator.addActionListener(this);
     
    		//assign an ActionCommand to each menu item
    		mnuFileExit.setActionCommand("Exit");
    		mnuEditClear.setActionCommand("Clear");
    		mnuEditCopy.setActionCommand("Copy");
    		mnuEditPaste.setActionCommand("Paste");
    		mnuAboutCalculator.setActionCommand("About");
     
    		//construct components and initialize beginning values
    		lcd = new TextField(20);
    			lcd.setEditable(false);
    		keypad = new Panel();
    		keys = new Button[20];
    		first = true;
    		op1 = 0.0;
    		clearText = true;
    		last0p = 0;
    		calcPattern = new DecimalFormat("########.########");
     
    		//construct and assign captions to the Buttons
    		for (int i=0; i<=9; i++)
    			keys[i] = new Button(String.valueOf(i));
     
    		keys[10] = new Button("/");
    		keys[11] = new Button("*");
    		keys[12] = new Button("-");
    		keys[13] = new Button("+");
    		keys[14] = new Button("=");
    		keys[15] = new Button(".");
    		keys[16] = new Button("M+");
    		keys[17] = new Button("MR");
    		keys[18] = new Button("Backspace");
    		keys[19] = new Button("Clear");
     
    		//sets Frame and keypad layout to grid layout
    		setLayout(new BorderLayout());
    		keypad.setLayout(new GridLayout(5,5,10,10));
     
    		for (int i=7; i<=10; i++)	//7, 8, 9, divide - Adds the first row of the grid
    			keypad.add(keys[i]);	//Adds the first row to the frame
     
    		for (int i=4; i<=6; i++)	//4, 5, 6 - adds the second row of the grid
    			keypad.add(keys[i]);	//Adds the second row to the frame
     
    		keypad.add(keys[11]);	//Adds the multiply button to the second row
     
    		for (int i=1; i<=3; i++)	//Adds 1, 2, 3 or the third row of the grid
    			keypad.add(keys[i]);	//Adds the third row to the frame
     
    		keypad.add(keys[12]);	//Adds the Subtract button to the third row
     
    		keypad.add(keys[0]);	//Adds the "0" key to fourth and final row
     
    		for (int i=15; i>=13; i--)	//Adds the '.', '=', and '+' to the fourth row
    			keypad.add(keys[i]);	//Adds the Fourth row to the frame
     
    		for (int i=19; i>=16; i--)	//Adds Copy, Paste, Backspace, and clear buttons
    			keypad.add(keys[i]);	//Adds the Fifth/Final row to the frame
     
    		for (int i=0; i<keys.length; i++)
    			keys[i].addActionListener(this);
     
    		add(lcd, BorderLayout.NORTH);
    		add(keypad, BorderLayout.CENTER);
     
    		addWindowListener(
    				new WindowAdapter()
    				{
    					public void windowClosing(WindowEvent e)
    					{
    						System.exit(0);
    					}
    				}
    			);
     
    	}	//End of the constructor Method
     
    			public void actionPerformed(ActionEvent e)
    			{
    				//test for menu item clicks
    				String arg = e.getActionCommand();
    				if (arg == "Exit")
    					System.exit(0);
     
    				if (arg == "Clear")
    				{
    					clearText = true;
    					first = true;
    					op1 = 0.0;
    					lcd.setText("");
    					lcd.requestFocus();
    				}
     
    				if (arg == "Copy")
    				{
    					Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
    					StringSelection contents = new StringSelection(lcd.getText());
    					cb.setContents(contents, null);
    				}
     
    				if (arg == "Paste")
    				{
    					Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
    					Transferable content = cb.getContents(this);
    					try
    					{
    						String s = (String)content.getTransferData(DataFlavor.stringFlavor);
    						lcd.setText(calcPattern.format(Double.parseDouble(s)));
    					}
    					catch (Throwable exc)
    					{
    						lcd.setText("");
    					}
    				}
     
    			if (arg == "About")
    			{
    				String message = "Calculator ver. 1.0\n Basic Software\nCopyright 2009\nAll rights reserved";
    				JOptionPane.showMessageDialog(null, message, "About Calculator", JOptionPane.INFORMATION_MESSAGE);
    			}
     
    			//test for button clicks
    			foundKey = false;
     
    			//search for the clicked key
    			for (int i=0; i<keys.length && !foundKey; i++)
    			{
    				if(e.getSource() == keys[i])
    				{
    					foundKey = true;
    					switch(i)
    					{
    						//number and decimal point buttons
    						case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 15:	//# buttons 0-9 and button 15 which is the '.' colon
    							if(clearText)
    							{
    								lcd.setText("");
    								clearText = false;
    							}
    							lcd.setText(lcd.getText() + keys[i].getLabel());
    							break;
     
    							//operator buttons
    							case 10: case 11: case 12: case 13: case 14:	//(+ - / * =) buttons
    								clearText = true;
     
    								if (first)
    								{
    									if(lcd.getText().length()==0) op1 = 0.0;
    									else op1 = Double.parseDouble(lcd.getText());
     
    									first = false;
    									clearText = true;
    									last0p = i;
    								}
    								else
    								{
    									switch(last0p)
    									{
    										case 10:	//divide button
    											op1 /= Double.parseDouble(lcd.getText());
    											break;
    										case 11:	//multiply button
    											op1 *= Double.parseDouble(lcd.getText());
    											break;
    										case 12:	//minus button
    											op1 -= Double.parseDouble(lcd.getText());
    											break;
    										case 13:	//plus button
    											op1 += Double.parseDouble(lcd.getText());
    											break;
    									}	//end of switch (Open-220)
    									lcd.setText(calcPattern.format(op1));
    									clearText = true;
     
    									if(i==14) first = true;	//Equals button.
    									else last0p = i;
    								}	//ends else (Open-218)
    								break;	//Break (Open-234)
     
    								case 16:	//Add to memory Button (M+)
    								Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
    								StringSelection contents = new StringSelection(lcd.getText());
    								cb.setContents(contents, null);
    								break;
     
    								case 17:	//Memory Recall Button (MR)
    								Clipboard cb2 = Toolkit.getDefaultToolkit().getSystemClipboard();
    								Transferable content = cb2.getContents(this);
    								try
    								{
    									String s = (String)content.getTransferData(DataFlavor.stringFlavor);
    									lcd.setText(calcPattern.format(Double.parseDouble(s)));
    								}
    								catch (Throwable exc)
    								{
    									lcd.setText("");
    								}
    								break;
     
    								case 18:	//Backspace Button
    								lcd.setText(lcd.getText().substring(0,lcd.getText().length()-1));
    								break;
     
    								case 19:	//Clear screen button
    								clearText = true;
    								lcd.setText("");
    								lcd.requestFocus();
    								break;
     
     
    						}	//end of the switch(i) statement (Open-186)
    				}	//end of if statement (Open-183)
    		}	//end of for statement (Open-181)
    	}//end of actionPerformed (Open-133)
     
    	public static void main(String args[])
    	{
    		//set frame properties
    		Calculator f = new Calculator();
    		f.setTitle("  Basic Calculator Application");
    		f.setBounds(200,200,300,300);
    		f.setVisible(true);
     
    		//set image properties and add to frame
    		Image icon = Toolkit.getDefaultToolkit().getImage("jj.jpg");
    		f.setIconImage(icon);
     
    	}	//end of main() method (Open-240)
    }	//end of Calculator class (Open-16)

    -Jay
  10. #6
  11. <?PHP user_title("gimp"); ?>
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2005
    Location
    Internet
    Posts
    7,652
    Rep Power
    6084
    Are you freaking kidding me? java.awt.Button has a setFont() method.

    As for setting background images, this tutorial was found from five minutes of googling.
    Chat Server Project & Tutorial | WiFi-remote-control sailboat (building) | Joke Thread
    “Rational thinkers deplore the excesses of democracy; it abuses the individual and elevates the mob. The death of Socrates was its finest fruit.”
    Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. Use TODO to leave yourself reminders. Calling a program finished before all these points are checked off is lazy.
    -Partial Credit: Sun

    If I ask you to redescribe your problem, it's because when you describe issues in detail, you often get a *click* and you suddenly know the solutions.
    Ches Koblents
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    13
    Rep Power
    0

    Wink Yeah... I was just kidding...


    Originally Posted by gimp
    Are you freaking kidding me? java.awt.Button has a setFont() method.

    As for setting background images, this tutorial was found from five minutes of googling.
    WOW!? 5 minutes, you are so ELITE! Thanks, anyways. Theres nothing like constructive sarcasm, works every time. I'll follow your advice like one would follow the word of god. Ive been programming Java for 8 weeks now, so you know that I know everything, Im trying to follow in your foot steps gimpy. You do realize that if it personally hurts or annoys you to answer "dumb" questions asked by people who havent been doing Java long, that YOU DONT HAVE TO REPLY!! Go figure!? I thought that was the reason for this site!? Its not like this is a "Genious Elite Coders" website. I thought this was an OPEN FORUM for SHARING and LEARNING. You may want to re-evaluate the reason you are here. Anyways, thanks for the advice.

    -Jay

    Comments on this post

    • gimp disagrees : (-10) Programming ability doesn't matter. What annoys me is that you don't know how to think, how to search to fix your problem. Also, learn to spell.
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2009
    Posts
    119
    Rep Power
    0
    you add it after every button that you want to change the color and the background image you add it before the background tag

    simple program that changes the background color to what the user types in. try red, blue, or white and you will notice where it is placed in the code


    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Colors extends JApplet implements ActionListener //make the class
    {
    	private GridLayout layout = new GridLayout(3, 1);
    	
    	JPanel panel02 = new JPanel(new FlowLayout());  //make panels
    	JPanel panel03 = new JPanel(new FlowLayout());
    	JPanel panel04 = new JPanel(new FlowLayout());
    	Container con = getContentPane();
    		
    	FlowLayout Lay = new FlowLayout(FlowLayout.CENTER);
    	JLabel head = new JLabel("Please enter a color");
    	JTextField choice = new JTextField("",10);
    	JButton enter = new JButton("Press After Typing");
    	JLabel error = new JLabel("");
    	JPanel pane = new JPanel() ;  //make a new panel
    
    
    		
    	public void init()
    	{
    		
    		
    		con.setLayout(layout);//set the layout
    		con.add(panel02);  //add panels
    		con.add(panel03);
    		con.add(panel04);
    		
    		panel02.add(head);  //add other goodies
    		panel03.add(choice);
    		panel03.add(enter);
    			enter.addActionListener(this);
    		panel04.add(error);
    	}
    	
    	
    		
    	public void actionPerformed(ActionEvent e)  //make the actions
    {
    			Object source = e.getSource(); //get the button workings
    			String cn = choice.getText();  //get the info
    			
    		try
    		{
    			if(cn.equals("red"))  //see if color is red
    			{
    				panel02.setBackground(Color.RED);   //change the back ground colors
    				panel03.setBackground(Color.RED);
    				panel04.setBackground(Color.RED);
    			}
    				else
    					if(cn.equals("blue"))  //see if it is blue
    					{
    						panel02.setBackground(Color.BLUE);  //change the back ground colors
    						panel03.setBackground(Color.BLUE);
    						panel04.setBackground(Color.BLUE);
    					}
    				
    						else
    							if(cn.equals("white"))  //see if it is blue								{
    								{
    									panel02.setBackground(Color.WHITE);  //change the back ground colors
    									panel03.setBackground(Color.WHITE);
    									panel04.setBackground(Color.WHITE);
    								}
    
    							else
    								throw new Exception("an invalid color");  //throw an exception
    								{
    									error.setText( "");  //clear label if its right
    								}
    		}			
    		catch(Exception ex)  //catch the exception
    			{
    				choice.setText("");  //erase color choice
    				error.setText( "an invalid color");  //change the label to show an error
    
    			}
    		}		
    }
    Last edited by Daren; November 11th, 2009 at 04:33 PM.
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    13
    Rep Power
    0

    Question Text Color Change


    Ok, thanks Daren. These are the changes I have made with good results. Pretty easy. I gave up on the idea of the background image. It looks even better if I just take the space out that is between the buttons. One other thing that I was wondering, in the GridLayout my buttons are 5x4 I want the operator buttons a different color then the number keys.
    http://bestinlifeproductions.angelfi...aquestion.html Here is a link to a picture that best describes what im talking about. I have tried a few things as far as playing around with the gridlayout but with no success. Thanks.

    java Code:
     
    lcd = new TextField(20);
    			lcd.setFont(new Font("Dialog", Font.BOLD, 30));
    			lcd.setEditable(false);
    		keypad = new Panel();
    			keypad.setForeground(Color.red);
    			keypad.setFont(new Font("Dialog", Font.BOLD, 22));


    -Jay
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2009
    Posts
    119
    Rep Power
    0
    Originally Posted by jaysonjohnson
    Ok, thanks Daren. These are the changes I have made with good results. Pretty easy. I gave up on the idea of the background image. It looks even better if I just take the space out that is between the buttons. One other thing that I was wondering, in the GridLayout my buttons are 5x4 I want the operator buttons a different color then the number keys.
    http://bestinlifeproductions.angelfi...aquestion.html Here is a link to a picture that best describes what im talking about. I have tried a few things as far as playing around with the gridlayout but with no success. Thanks.

    java Code:
     
    lcd = new TextField(20);
    			lcd.setFont(new Font("Dialog", Font.BOLD, 30));
    			lcd.setEditable(false);
    		keypad = new Panel();
    			keypad.setForeground(Color.red);
    			keypad.setFont(new Font("Dialog", Font.BOLD, 22));


    -Jay
    create a variable like this for red letters

    COLOR color = new COLOR(255, 0 , 0);

    then add this during your button placement to the frame.

    button name.setForeground(color);

    button name will be the button you want the color of the text to change --- color is the color from above which in this case is red

    so if you have lets say buttons called button1, button 2, button 3 then you would code like this

    button1.setForeground(color);
    (add button to panel)
    button2.setForeground(color);
    (add button to panel)
    button3.setForeground(color);
    (add button to panel)
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    13
    Rep Power
    0
    Originally Posted by Daren
    create a variable like this for red letters

    COLOR color = new COLOR(255, 0 , 0);

    then add this during your button placement to the frame.

    button name.setForeground(color);

    button name will be the button you want the color of the text to change --- color is the color from above which in this case is red

    so if you have lets say buttons called button1, button 2, button 3 then you would code like this

    button1.setForeground(color);
    (add button to panel)
    button2.setForeground(color);
    (add button to panel)
    button3.setForeground(color);
    (add button to panel)
    Thanks again Daren. Worked like a charm. It now looks great.

    -Jay
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2009
    Posts
    119
    Rep Power
    0
    Originally Posted by jaysonjohnson
    Thanks again Daren. Worked like a charm. It now looks great.

    -Jay
    any time
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Location
    Fairview, NC
    Posts
    11
    Rep Power
    0
    Something I have found that is usually helpful is to Google "Java API". It'll show you the main classes and everything under them. If you can't find what you're looking for, just Google "Java API (the class you're looking for)". If you are looking for the Cursor Class, which is java.awt.Cursor and is under java.lang.object, you could Google "Java API Cursor" and it's the first option.
  26. #14
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    13
    Rep Power
    0

    Question Open/Save text file


    Hello again everyone. Since I have this Calculator looking GREAT, I wanted to add some stuff to it. I thought it would be nice to have a place for notes, so I added a TextArea. I created menus for 'SAVE' and 'OPEN'. I would like it to be able to OPEN simple text files and/or SAVE the ones created in my TextArea.

    NOW, I have been doing some 'Googling' and looking on the java.sun.com API page and think I have found what I need, Scanner class (java.util.Scanner). The only problem I have is implementing it. Im not sure what 'syntax' is needed and 'where' to put 'said' syntax. I have found quite a bit of examples of its use MOSTLY in a command line. I want to use it in the JOptionPane windows, does it work the same for both? Is this the correct class to use? What would be a good class for OPENING a text file? Thanks for any help.

    -Jay
  28. #15
  29. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2009
    Posts
    119
    Rep Power
    0
    create a phone list example

    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    
    public class createPhoneList extends JFrame implements ActionListener //make the class
    {
    	private JLabel headTitle = new JLabel("Phone List");
    	private Font headFont = new Font("Mistral", Font.BOLD, 24);
    	private JLabel enterName = new JLabel("Please enter a name");
    	private JLabel name = new JLabel("Name\n");
    	private JTextField inputName = new JTextField(10);
    	private JLabel phone = new JLabel("Phone Number");
    	private JTextField inputPhone = new JTextField(10);
    	private JButton saveData = new JButton("Save");
    	private Container con = getContentPane();
    	DataOutputStream outstream;
    	
    	public createPhoneList()
    		{
    			super("Create Phone List");
    			
    			try
    			{
    				outstream = new DataOutputStream(new FileOutputStream("PhoneList.dat"));
    			}
    			catch(IOException ex)
    			{
    				System.err.println("File not opened");
    				System.exit(1);
    			}
    			
    			setSize(150,250);
    			con.setLayout(new FlowLayout());
    			headTitle.setFont(headFont);
    			con.add(headTitle);
    			con.add(enterName);
    			con.add(name);
    			con.add(inputName);
    			con.add(phone);
    			con.add(inputPhone);
    			con.add(saveData);
    			saveData.addActionListener(this);
    			setVisible(true);
    			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    			
    		}
    			
    			public void actionPerformed(ActionEvent e1)
    			{
    				try
    				{
    					outstream.writeUTF(inputName.getText());
    					outstream.writeUTF(inputPhone.getText());
    					
    					inputName.setText("");
    					inputPhone.setText("");
    				}
    				catch(IOException e2)
    				{
    					System.err.println("Error writing file");
    					System.exit(1);
    				}
    			}	
    			public static void main(String[] args)
    			{
    				createPhoneList cpf = new createPhoneList();
    			}
    }



    simple reading of a phone list that you created above

    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    
    public class readPhoneList extends JFrame implements ActionListener //make the class
    {
    	private JLabel headTitle = new JLabel("Phone List");
    	private Font headFont = new Font("Mistral", Font.BOLD, 24);
    	private JLabel enterName = new JLabel("Click view to see a name");
    	private JLabel name = new JLabel("Name");
    	private JTextField inputName = new JTextField(10);
    	private JLabel phone = new JLabel("Phone Number");
    	private JTextField inputPhone = new JTextField(10);
    	private JButton openData = new JButton("View");
    	private Container con = getContentPane();
    	DataInputStream instream;
    	
    	public readPhoneList()
    		{
    			super("Create Phone List");
    			
    			try
    			{
    				instream = new DataInputStream(new FileInputStream("PhoneList.dat"));
    			}
    			catch(IOException ex)
    			{
    				System.err.println("File not opened");
    				System.exit(1);
    			}
    			
    			setSize(160,250);
    			con.setLayout(new FlowLayout());
    			headTitle.setFont(headFont);
    			con.add(headTitle);
    			con.add(enterName);
    			con.add(name);
    			con.add(inputName);
    			con.add(phone);
    			con.add(inputPhone);
    			con.add(openData);
    			openData.addActionListener(this);
    			setVisible(true);
    			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    			
    		}
    			
    			public void actionPerformed(ActionEvent e1)
    			{
    				String theName, theNumber;
    				try
    				{
    					theName = instream.readUTF();
    					theNumber = instream.readUTF();
    								
    					inputName.setText(theName);
    					inputPhone.setText(theNumber);
    				}
    				catch(EOFException e2)
    				{
    					closeFile();
    				}
    				catch(IOException e3)
    				{
    					System.err.println("Error reading file");
    					System.exit(1);
    				}
    			}	
    			public void closeFile()
    			{
    				try
    				{
    					instream.close();
    					System.exit(0);
    				}
    				catch(IOException e)
    				{
    					System.err.println("Error reading file");
    					System.exit(1);
    				}
    			}
    			public static void main(String[] args)
    			{
    				readPhoneList cpf = new readPhoneList();
    			}
    }

    hope this helps
    Last edited by Daren; November 13th, 2009 at 06:16 PM.
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo