Previous Page

Roman Numeral Converter - Java GUI

Copy and Paste the following code into your favorite Java Integrated Development Environment (IDE) - compile and run.

Here are the 2 image files if you want.(NOTE: Not needed for the program to work.)
Place them in the same directory as your .java files. roman_background.png and roman_converter.png

Below is the RomanMain.java containing the main method to run the program. It calls the object of the Roman.java class

/***********************************************************************************
/ Name: Brian Butler
/ Professor: Gary Hartell
/ Date: May 5, 2011
/ Assignment: 								   
/					   		 Descripion:
/     This program converts a number entered in Roman numerals to a decimal number.
/     This program creates an object for the Roman.java class which does the 
/	 calculations. THIS CLASS CONTAINS THE METHOD MAIN.
/
************************************************************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color.*;
import java.util.*;
import java.util.regex.*;//split strings
import javax.swing.border.*;//allows the use of borders

public class RomanMain extends JFrame
{	
	private static JTextArea outputTA, inputTA;	
	private JLabel headingL;	
	private JScrollPane scrollText, scrollText2;//creates the scroll 
									              feature for JTextArea 													 
	private JButton convertB, exitB, clearB;
	private ConvertButtonHandler encrbHandler;	
	private ExitButtonHandler ebHandler;
	private ClearButtonHandler clbHandler;		
	
	private static int WIDTH = 455;
     private static int HEIGHT = 285;	
	
   public RomanMain()
	{
/************************************************************* Create borders  * */	        
	    Border raisedbevel, loweredbevel, blackline, compound;
		blackline = BorderFactory.createLineBorder(Color.black);    
		raisedbevel = BorderFactory.createRaisedBevelBorder();
          loweredbevel = BorderFactory.createLoweredBevelBorder();
		compound = BorderFactory.createCompoundBorder(loweredbevel, blackline);	
/************************************************************* Create Fonts    * */			
     Font font =  new Font("Courier New", Font.BOLD, 30);	
	  Font font2 = new Font("Times New Roman", Font.BOLD, 20);
	  Font font3 = new Font("Times New Roman", Font.BOLD, 36);
/************************************************************* Create labels   * */			
	  headingL = new JLabel("Enter a Roman numeral to convert it to a number",
	  SwingConstants.CENTER);
	  headingL.setFont(font2);
	  headingL.setBorder(raisedbevel);	   
		 
	/*************** SET GRAY BACKGROUND IMAGE IN TEXT AREA ***************/ 
	  	final ImageIcon imageIcon = new ImageIcon("roman_converter.png");
		
	inputTA = new JTextArea("",50,895) 
	{
      Image image = imageIcon.getImage();

      Image grayImage = GrayFilter.createDisabledImage(image);
      {
        setOpaque(false);
      }

      public void paint(Graphics g) {
        g.drawImage(grayImage, 0, 0, this);
        super.paint(g);
      }
    };//END SET BACKGROUND IMAGE
	  
	scrollText2 = new JScrollPane(inputTA);//adds the scroll feature to the outputTA
     scrollText2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	scrollText2.setBorder(compound);	
	inputTA.setFont(font); 
	inputTA.setLineWrap(true);
     inputTA.setWrapStyleWord(true);

/*************** SET GRAY BACKGROUND IMAGE IN TEXT AREA ***************/ 
	final ImageIcon imageIcon2 = new ImageIcon("roman_background.png");
	outputTA = new JTextArea("",50,895) 
	{
      Image image = imageIcon2.getImage();

      Image grayImage = GrayFilter.createDisabledImage(image);
      {
        setOpaque(false);
      }

      public void paint(Graphics g) {
        g.drawImage(grayImage, 0, 0, this);
        super.paint(g);
      }
    };//END SET BACKGROUND IMAGE	 
	 	
	scrollText = new JScrollPane(outputTA);//adds the scroll feature to the outputTA
     scrollText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	scrollText.setBorder(compound);
	outputTA.setFont(font);	
	outputTA.setLineWrap(true);
     outputTA.setWrapStyleWord(false);//set to false because the 
	                                   Output is one char at a time
	outputTA.setEditable(false); 
		
	 convertB = new JButton("Convert");
      encrbHandler = new ConvertButtonHandler();
      convertB.addActionListener(encrbHandler);
	 convertB.setFont(font3);	 
	 	 
	 exitB = new JButton("EXIT");
      ebHandler = new ExitButtonHandler();
      exitB.addActionListener(ebHandler);
	 exitB.setFont(font3);
	 
	 clearB = new JButton("Clear All");
      clbHandler = new ClearButtonHandler();
      clearB.addActionListener(clbHandler);
	 clearB.setFont(font3);	
	 
	 setTitle("Roman Numeral Conversion");	              
      Container myWindow = getContentPane();
      myWindow.setLayout(null);
	          
		  convertB.setSize(200,40); 
            exitB.setSize(200, 40);
		  clearB.setSize(200, 40);		 
		  headingL.setSize(425,40);				 
		  scrollText2.setSize(445,50);		 
		  scrollText.setSize(445,50);			  
		  
	 	  convertB.setLocation(120, 105);
		  exitB.setLocation(228, 203);
		  clearB.setLocation(15, 203);		 
		  scrollText2.setLocation(2,52);		  
		  scrollText.setLocation(2,150);		
		  headingL.setLocation(10,5);	  	 
		  		 
		  myWindow.add(convertB);          
            myWindow.add(exitB);
		  myWindow.add(clearB);
		  myWindow.add(headingL);		 
		  myWindow.add(scrollText2);		 
		  myWindow.add(scrollText);

		  
	   setSize(WIDTH, HEIGHT);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE); 
 	  }
	  
	 private class ConvertButtonHandler implements ActionListener
    {//start convert button class
       public  void actionPerformed(ActionEvent e)       	 							
       {	        
         inputTA.setForeground(Color.blue);//changes user input text to 
									        blue when button is clicked
			outputTA.setText("");
			outputTA.setForeground(Color.red);	
						
			String roman = inputTA.getText();//Get user input		
                
      Roman N = new Roman(roman);//Use Roman Class to convert the input for (roman)
			 
	outputTA.append(N.toString() + " = " + N.toInt());//output conversion as 
														String and Integer Number			 
		}
	}        

    private class ExitButtonHandler implements ActionListener
    {
       public void actionPerformed(ActionEvent e)
       {
           System.exit(0);//allows the exit button to close the JFrame window 
       }
    }//End of EXIT BUTTON actionPerformed  
	 
	 private class ClearButtonHandler implements ActionListener
    {
       public void actionPerformed(ActionEvent e)
       {
           inputTA.setText("");
		     inputTA.setForeground(Color.black);
			  outputTA.setText("");
			  inputTA.requestFocusInWindow();
       }
	 }									 
	 public static void main(String[] args)
    {							  
        
		 RomanMain romanObject = new RomanMain();		 
       romanObject.setLocationRelativeTo(null);//lets the window popup in the 
									  middle of the user's screen    
	 }        

}
  

//END OF CODE

Below is the Roman.java class that is called by the RomanMain.java
Simply place these two .java files into the same directory (and the image files - if you want) and run RomanMain.java


/***********************************************************************************
/ Name: Brian Butler
/ Professor: Gary Hartell
/ Date: May 5, 2011
/ Assignment: 	CHAPTER 8 PAGE 505 Roman Numeral Conversion							   
/			 		   		      Descripion:
/			  This Class converts a Roman Numeral to an integer number
/
/	    NOTE: THERE IS NO MAIN METHOD IN THIS CLASS ---USE RomanMain.java
/              FOR THE MAIN METHOD
************************************************************************************/
		  
    public class Roman
	 {
		
       private int num;        
       private static int[]    numbers = { 1000,  900,  500,  400,  100,   90,  
                                             50,   40,   10,    9,    5,    4,    1 };                                          
       private static String[] letters = { "M",  "CM",  "D",  "CD", "C",  "XC",
                                           "L",  "XL",  "X",  "IX", "V",  "IV", "I" };  									 
	       
       public Roman(String roman)
		 {             
          roman = roman.toUpperCase();            
          int i = 0;       
		int decimal = 0; 
			 
	   while (i < roman.length()) 
	   {          
             char letter = roman.charAt(i);        
             int number = letterToNumber(letter);                             
             i++;               
            		if (i == roman.length())
					   {                  
                		decimal += number;
             		}
             		else
						{
                      int nextNumber = letterToNumber(roman.charAt(i));
                      if (nextNumber > number) 
					       {
                  			 decimal += (nextNumber - number);
                   			 i++;
                      }
                      else
							 {
                   			decimal += number;
                		 }
             		}
             
            } 
                num = decimal;          
       }     
       private int letterToNumber(char letter)
		 {            
          switch (letter)
			 {
             case 'I':  return 1;
             case 'V':  return 5;
             case 'X':  return 10;
             case 'L':  return 50;
             case 'C':  return 100;
             case 'D':  return 500;
             case 'M':  return 1000;
             default:   return -1;
          }
       }       
    
     public String toString()
	  {
          String roman = "";  
          int N = num;                
			  for (int i = 0; i < numbers.length; i++)
			  {
             while (N >= numbers[i])
				 {
                roman += letters[i];
                N -= numbers[i];
             }
          }
			 roman = roman.toUpperCase();
          return roman;
       }       
     
       public int toInt()
		 {           
          return num;
       }

       
} 
//END OF CODE

Below is a sample input/output of this program.sample conversion