JTextArea formatting

I've written a basic compiler and am attempting to put a GUI front-end on it. What I'd like to do is display the source code from a text file in a Text Area or something similar. I'd like to highlight the recognised words in a colour, say blue.
Is there something similar to the new line escape character "\n" ? Or should I look at doing this in an applet?
Any suggestions would be welcome...
Thanks

use the append method.
private void setData(ResultSet rs) .... {
  txtNoteDesc.setText("");          // clear textarea
  while (rs.next())
    txtNoteDesc.append(rs.getString(3)+"\n");
not really sure what the application is but,
give it a try.

Similar Messages

  • JTextArea Formatting Questions

    How can I add a Scroll Bar to the JTextArea in the following code, I have tried adding it, as one can see below, however no matter what I seem to change, the scroll bar does not appear. If anyone could help me I'd grealtly appreciate it.
    public class CardLayoutDemo extends JTextArea implements ItemListener {
    JPanel cards; //a panel that uses CardLayout
    final static String BUTTONPANEL = "JPanel with JButtons";
    final static String TEXTPANEL = "JPanel with JTextField";
    public void addComponentToPane(Container pane) {
    //Put the JComboBox in a JPanel to get a nicer look.
    JPanel comboBoxPane = new JPanel(); //use FlowLayout
    String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
    JComboBox cb = new JComboBox(comboBoxItems);
    cb.setEditable(false);
    cb.addItemListener(this);
    comboBoxPane.add(cb);
    //Create the "cards".
    JPanel card1 = new JPanel();
    card1.add(new JButton("Button 1"));
    card1.add(new JButton("Button 2"));
    card1.add(new JButton("Button 3"));
    JPanel card2 = new JPanel();
    String text = "This is just jibberish to see whether the scroll function will work, \n"+
         "This is just jibberish to see whether the scroll function will work, \n"+
         "This is just jibberish to see whether the scroll function will work, \n"+
    "This is just jibberish to see whether the scroll function will work, \n"+
         "This is just jibberish to see whether the scroll function will work, \n"+
         "This is just jibberish to see whether the scroll function will work, \n";
    JTextArea textArea = new JTextArea (text);
    JScrollPane scrollPane = new JScrollPane(textArea);
    add(scrollPane);
    card2.add(textArea);
    //Create the panel that contains the "cards".
    cards = new JPanel(new CardLayout());
    cards.add(card1, BUTTONPANEL);
    cards.add(card2, TEXTPANEL);
    pane.add(comboBoxPane, BorderLayout.PAGE_START);
    pane.add(cards, BorderLayout.CENTER);
    public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("CardLayoutDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    CardLayoutDemo demo = new CardLayoutDemo();
    demo.addComponentToPane(frame.getContentPane());
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    JScrollPane scrollPane = new JScrollPane(textArea);
    add(scrollPane);
    card2.add(textArea);This is messed up. I think you wanted to add the text-area-in-a-scroll-pane to card2 and not to "this". Try doing that instead:JScrollPane scrollPane = new JScrollPane(textArea);
    card2.add(scrollPane);PC²

  • JTextArea formatting when declared final

    Hi all,
    I have a JTextArea which is inside an infinte loop and has to be declared final for it to update on demand.
    My quetion is how can I change the font and style of text when it is declared final? nothing seems to work.
    Any ideas?
    Thanks a lot,
    Dan

    The fact that it is declared final shouldn't be important. You are probably either updating it on the event thread or trying to update it so much that the event thread is getting no CPU cycles.
    Probably best to post some code.

  • JTextArea formatting text and colors

    Hi,
    I have a jTextArea and I need to wrap line, how can I do?
    I want to change color of a selected text, how?
    Thanks to all!

    Refer to the Java Tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html for more info on how to use the JTextArea. JTextArea only allow you to display plain text, so if you want the selected text to change color, you will have to use the JEditorPane (or its subclass JTextPane). Refer to http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html for more info.

  • Tab format/size in JTextArea not working

    Howdy, I am writing a program that uses Runtime.exec() method, I get the error stream from the new process, etc... all that works fine, but as I use append(String s) where s = StreamOutput+"\n";, the output is not formatted in the JTextArea. However, if I do System.out.println(s), the output is perfectly lined up.
    I recall reading somewhere about setting the tab size or something or other about a similar problem, but now cannot find the answer in the forums or the docs. Any assistance would be greatly appreciated.
    Brian

    here is the chunk of code in question:
    String[] commandLine = {profile.getCompilerPath(),filePath};
                   Process p = rt.exec(commandLine);
                   BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                   String s = reader.readLine();
                  while(s!=null)
                        writer.write(s2.toString());
                        System.out.println(s);
                        s = reader.readLine();
                   writer.write(null);writer is an instance of an innner calss of the gui, and its only method is write(String s). write does this: txtAreaOutput.append("\n" + s); if s !=null. having messed with tab sizes etc to no avail, I am at a loss. the output I am trying to capture is from the javac.exe compiler, imagine that! and the little carats that point to the errors don't line up with the code in the JTextArea. what's worst, notice the call to System.out.println(s) after the call to writer. this was to check to see that the output was coming out right, and there it is PERFECT!!! ahhhh. Please help if you can.
    Is there an issue that the JTextArea is not using a monospaced font, and if so, how do I fix that, or is there some other component with similar funcitonality that will work? Thank you for your time and mental sweat.. I am at my wit's end here :(

  • Formatting JTextArea text

    I want to take the text of a JTextField and save it on the file system formatting with character length limited to a certain amount per line (say 77) and save any blank lines the user enters. Each line is prefixed with "//$" which I look for when I read it back in. The problem I am running into is when I encounter a blank line. My code looks like this (str is the string from the JTextField.getText() method):
              if(!str.trim().equals(""))
                   try
                        for(x = 0; x < str.length(); x++)
                             while(count != 76 && x < str.length() && !endOfLine)
                                  count++;
                                  if(str.charAt(x) == '\n')
                                       endOfLine = true;
                                  x++;
                             if(x == str.length())
                                  tmpStr+="//$ " + str.substring(start, x) + "\n";
                                  count = 0;
                             else if(endOfLine)
                                  tmpStr+="//$ " + str.substring(start, x);     
                                  start = x;
                                  count = 0;
                                  endOfLine = false;
                             else if(str.substring(start, x).equals(null))
                                  tmpStr+="//$$";
                                  start = x;
                                  count = 0;
                             else                         
                                  tmpStr+="//$ " + str.substring(start, x) + "\n";
                                  start = x;
                                  count = 0;

    Refer to the Java Tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html for more info on how to use the JTextArea. JTextArea only allow you to display plain text, so if you want the selected text to change color, you will have to use the JEditorPane (or its subclass JTextPane). Refer to http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html for more info.

  • Formatting string output in columns to a JtextArea

    Hello,
    I am pretty new to java and GUI's but i am working on a project that needs to output some statisitcs to a JtextArea. I need have all the data in an array and i want it to appear as
    First Name Last Name Points Rebounds Assists Minutes
    The last four columns are numbers but are stored as strings. I would like to find a way to format them into colums so that even though each name is a differing number of characters, each column will be flush left. Thanks.

    I strongly agree with Camikr, use Jtable is the best solution since you have arrays of data to be displayed
    I'll show you few tips that might be helped
    if you don't want the header part to appear you do this:
    JTable table = new JTable(..)
    table.getTableHeader().setPreferredSize(new Dimension(0,0));if you want the table to appear like JLabel maybe you can set like this:
    table.setBackground(UIManager.getColor("Panel.background"));
    table.setGridColor(UIManager.getColor("Panel.background"));so it will make the background and cell border color to be the same as panel
    if you insist to use table another work around is by formatting your jlabel using html code like this
    new JLabel("<html><table><td>First Name</td>.......</table></html>");

  • Formatting JTextArea

    I am writing a program that generates a matrix of random numbers and displays in the textarea. I then have a subprogram that locates the highest generated value and displays it location in the matrix and the value of it. However, all the displayed values are displayed one after the other with no spaces and so impossible to distinguish between them.
    I thought about a JTable but I am not sure how to generate data and enter it into each cell in the table. Also whenever I print out the location of the highest value I need a textarea for that piece.
    Is it possible to create a JScrollPane that contains both a JTable for the information and a JTextArea for the analysis.
    Later down the line I will also have to colour the rows and columns that the highest value occurs in.
    I would appreciate any help on this issue and will offer as much information as what is needed to find a good solution.
    Thankyou

    What you have sent me looks fine but everytime i try to implement it I get countless errors. One error in the table model is that i cannot create random numbers and put them into the array. The generation of these number sare double but the array is Double.
    Then in the main code I get probelms with defined the Component for the cellrenderer saying stuff like illegal start to expression.
    I have attached the code that I would like to apply the renderer to and if you dont mind, could you please take a look at it and see if there is something different about it. Thanks for taking the time to do this already.
    Cheers.
    import ccj.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import java.text.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    class randomClassical extends JFrame
         public static double c, s, t, theta, max;
         public static double eps = 0.0000005;
         public static double total = 0.0;
         public static int p, q, i, j, r, sign;
         public static int x = 0;
         public static double [][] a = new double [50][50];
         public randomClassical(int n)
              x=0;
              final int WIDTH = 1000;
              final int HEIGHT = 600;
              setSize(WIDTH, HEIGHT);
              addWindowListener(new WindowCloser());
              int m = (int)Math.pow(n,4);
              JTable table = new JTable(m,n+1);
              table.setColumnSelectionAllowed(true);
              JScrollPane scrollPane = new JScrollPane(table);
              scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              //table.setFont(new Font("Monospaced", Font.PLAIN, 12));
              Container contentPane = getContentPane();
              contentPane.add(scrollPane, "Center");
              // Generate random values for the first matrix     
              for (i=0; i<n; i++)
                   for (j=0; j<n; j++)
                        a[i][j] = Numeric.randomDouble(-100, 100);
              // Prints out the values in a table
              for (i=0; i<n; i++)
                   for (j=0; j<n; j++)
                        a[i][j] = a[j];
                        table.setValueAt(""+a[i][j], i, j);
              // Calculation to find the max value in the matrix          
              max = 0;
              for (int i=0; i<n; i++)
                   for (int j=i+1; j<n; j++)
                        if (Math.abs(a[i][j]) > (max))
                             max = Math.abs(a[i][j]);     
                             p=i; q=j;
              table.setValueAt("Matrix : "+x, (n-3),n);
              table.setValueAt("Row P : "+p, n-2,n);
              table.setValueAt("Column Q : "+q, n-1,n);
              table.setValueAt("Max value: "+max, n,n);
              calculation(n,p,q,table);
         public static void calculation(int n, int p, int q, JTable table)
              if ((n*max)>(eps))     //Checks for the termination condition
                   theta = 0.5*(a[q][q] - a[p][p])/a[p][q];
                             if (theta >= 0)
                                  sign = 1;
                             else
                                  sign = -1;
                        if (theta == 0)
                             t = 1;     
                        else
                             t = 1/(theta + (theta*sign) * Math.sqrt(1+Math.pow(theta,2)));
                        c = 1/Math.sqrt(1 + Math.pow(t,2));
                        s = c * t;
                        //Start the rotation procedure based on the values of p and q     
                        double matrix = rotation(n,c,s,p,q,a);
                        //Print out the new matrix
                        for (int i=0; i<n; i++)
                             for (int j=0; j<n; j++)
                                  a[i][j] = a[j][i];
                                  table.setValueAt(""+a[i][j], ((n+2)*x)+i, j);
                        // Calculation to find the max value in the matrix          
                        max = 0;
                        for (i=0; i<n; i++)
                             for (j=i+1; j<n; j++)
                                  if (Math.abs(a[i][j]) > (max))
                                       max = Math.abs(a[i][j]);     
                                       p=i; q=j;
                        table.setValueAt("Matrix : "+x, (((n+2)*(x+1))-5),n);
                        table.setValueAt("Row P : "+p, (((n+2)*(x+1))-4),n);
                        table.setValueAt("Column Q : "+q, (((n+2)*(x+1))-3),n);
                        table.setValueAt("Max value: "+max, (((n+2)*(x+1))-2),n);
                        calculation(n,p,q,table);
              else
              table.setValueAt("", (((n+2)*(x+1))-5),n);
              table.setValueAt("", (((n+2)*(x+1))-4),n);
              table.setValueAt("", (((n+2)*(x+1))-3),n);
              table.setValueAt("", (((n+2)*(x+1))-2),n);
              table.setValueAt("N*Max less than eps", (((n+2)*(x+1))+3),n);
         public static JTextArea inputArea;
         public static JTable table;
         public static double rotation(int n,double c,double s,int p,int q, double [][]a)
              double h = c*c*a[p][p] - 2*c*s*a[p][q] + s*s*a[q][q];
              double g = s*s*a[p][p] + 2*c*s*a[p][q] + c*c*a[q][q];
              a[p][q] = c*s*(a[p][p]-a[q][q])+(c*c-s*s)*a[p][q];
              a[p][p] = h; a[q][q] = g; a[q][p] = a[p][q];
              a[p][q] = 0;     a[q][p] = 0;
              x = x+1;
              for (j=0;j<p;j++){
                   h = c*a[j][p] - s*a[j][q];
                   a[j][q] = s*a[j][p] + c*a[j][q];
                   a[q][j] = a[j][q];
                   a[j][p] = h; a[p][j] = h;
              for (j=p+1;j<q;j++){
                   h = c*a[p][j] - s*a[j][q];
                   a[j][q] = s * a[p][j] + c*a[j][q];
                   a[q][j] = a[j][q];
                   a[p][j] = h; a[j][p] = h;
              for (j=q+1;j<n;j++){
                   h = c*a[p][j] - s*a[q][j];
                   a[q][j] = s*a[p][j]+c*a[q][j];
                   a[j][q] = a[q][j];
                   a[p][j] = h; a[j][p] = h;
         return h;
         private class WindowCloser extends WindowAdapter
              public void windowClosing(WindowEvent event)
                   dispose();

  • To refresh the contents in JTextArea on selection of a row in JTable.

    This is the block of code that i have tried :
    import java.awt.GridBagConstraints;
    import java.awt.SystemColor;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.DefaultTableModel;
    import ui.layouts.ComponentsBox;
    import ui.layouts.GridPanel;
    import ui.layouts.LayoutConstants;
    import util.ui.UIUtil;
    public class ElectronicJournal extends GridPanel {
         private boolean DEBUG = false;
         private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
         private GridPanel jGPanel = new GridPanel();
         private GridPanel jGPanel1 = new GridPanel();
         private GridPanel jGPanel2 = new GridPanel();
         DefaultTableModel model;
         private JLabel jLblTillNo = UIUtil.getHeaderLabel("TillNo :");
         private JLabel jLblTillNoData = UIUtil.getBodyLabel("TILL123");
         private JLabel jLblData = UIUtil.getBodyLabel("Detailed View");
         private JTextArea textArea = new JTextArea();
         private JScrollPane spTimeEntryView = new JScrollPane();
         private JScrollPane pan = new JScrollPane();
         String html= " Item Description: Price Change \n Old Price: 40.00 \n New Price: 50.00 \n Authorized By:USER1123 \n";
         private JButton jBtnExporttoExcel = UIUtil.getButton(85,
                   "Export to Excel - F2", "");
         final String[] colHeads = { "Task No", "Data", "User ID", "Date Time",
                   "Description" };
         final Object[][] data = {
                   { "1", "50.00", "USER123", "12/10/2006 05:30", "Price Change" },
                   { "2", "100.00", "USER234", "15/10/2006 03:30", "Price Change12345"},
         final String[] colHeads1 = {"Detailed View" };
         final Object[][] data1 = {
                   { "Task:Price Change", "\n"," Old Price:50.00"," \n ","New Price:100.00"," \n" }
         JTable jtblTimeEntry = new JTable(data, colHeads);
         JTable jTbl1 = new JTable(data1,colHeads1);
         ComponentsBox jpBoxButton = new ComponentsBox(LayoutConstants.X_AXIS);
         public ElectronicJournal() {
              super();
              jtblTimeEntry.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              if (ALLOW_ROW_SELECTION) { // true by default
    ListSelectionModel rowSM = jtblTimeEntry.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
    textArea.append("asd \n 123 \n");
    } else {
         jtblTimeEntry.setRowSelectionAllowed(false);
              if (DEBUG) {
                   jtblTimeEntry.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
         printDebugData(jtblTimeEntry);
              initialize();
         private void printDebugData(JTable table) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
         private void initialize() {
              this.setSize(680, 200);
              this.setBackground(java.awt.SystemColor.control);
              jBtnExporttoExcel.setBackground(SystemColor.control);
              ComponentsBox cmpRibbonHORZ = new ComponentsBox(LayoutConstants.X_AXIS);
              cmpRibbonHORZ.addComponent(jBtnExporttoExcel, false);
              jpBoxButton.add(cmpRibbonHORZ);
              this.addFilledComponent(jGPanel, 1, 1, 1, 1, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel1, 2, 1, 11, 5, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel2, 2, 13, 17, 5, GridBagConstraints.BOTH);
              jGPanel.setSize(650, 91);
              jGPanel.setBackground(SystemColor.control);
              jGPanel.addFilledComponent(jLblTillNo,1,1,GridBagConstraints.WEST);
              jGPanel.addFilledComponent(jLblTillNoData,1,10,GridBagConstraints.BOTH);
              jGPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
              jGPanel1.setBackground(SystemColor.control);
              jGPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              spTimeEntryView.setViewportView(jtblTimeEntry);
              jGPanel1.addFilledComponent(spTimeEntryView, 1, 1, 11, 4,
                        GridBagConstraints.BOTH);
              jGPanel2.addFilledComponent(jLblData,1,1,GridBagConstraints.WEST);
              jGPanel2.setBackground(SystemColor.control);
              jGPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              //textArea.setText(html);
              pan.setViewportView(textArea);
         int selectedRow = jTbl1.getSelectedRow();
              System.out.println("selectedRow ::" +selectedRow);
              int colCount = jTbl1.getColumnCount();
              System.out.println("colCount ::" +colCount);
              StringBuffer buf = new StringBuffer();
              System.out.println("Out Of For");
              /*for(int count =0;count<colCount;count++)
              {System.out.println("Inside For");
              buf.append(jTbl1.getValueAt(selectedRow,count));
              // method 1 : Constructs a new text area with the specified text. 
              textArea  =new JTextArea(buf.toString());
              //method 2 :To Append the given string to the text area's current text.   
             textArea.append(buf.toString());
              jGPanel2.addFilledComponent(pan,2,1,5,5,GridBagConstraints.BOTH);
              this.addAnchoredComponent(jpBoxButton, 7, 5, 11, 5,
                        GridBagConstraints.CENTER);
    This code displays the same data on the JTextArea everytime i select each row,but my requirement is ,it has to refresh and display different datas in the JTextArea accordingly,as i select each row.Please help.Its urgent.
    Message was edited by: Samyuktha
    Samyuktha

    Please help.Its urgentThen why didn't you use the formatting tags to make it easier for use to read the code?
    Because of the above I didn't take a close look at your code, but i would suggest you should be using a ListSelectionListener to be notified when a row is selected, then you just populate the text area.

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • How to print JTextArea??

    I am trying to print JTextArea which has more than one page of text. When there is more than one page of text in JTextArea, it only prints what is there on first page eventhough it print multiple pages.
    Here is the code I am using. Let me know if you know what I am doing wrong.
    public class TextAreaPrint implements Printable {
         private JTextArea textArea;
         public TextAreaPrint(JTextArea area) {
         textArea = area;
         PrinterJob pj = PrinterJob.getPrinterJob();
         pj.setPrintable(TextAreaPrint.this);
         pj.printDialog();
         try{
              pj.print();
         catch(PrinterException pe){System.out.println("Error");}
         public int print(Graphics g, PageFormat format, int pageNumber)
    throws PrinterException
    double pageOffset = pageNumber * format.getImageableHeight();
    View view = textArea.getUI().getRootView(textArea);
    if(pageOffset > view.getPreferredSpan(View.Y_AXIS))
    return Printable.NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D)g;
    g2.translate(format.getImageableX(), format.getImageableY());
    textArea.paint(g2);
    return Printable.PAGE_EXISTS;
    thanks
    amit

    Try this class performs simple printing of a JTextArea by extending JTextArea and implementing Printable.
    All you need to do is invoke SimplePrintableJTextArea.print() from your application.
    * PrintableJTextArea.java
    package your.package;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics2D;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.standard.Chromaticity;
    import javax.print.attribute.standard.MediaPrintableArea;
    import javax.print.attribute.standard.OrientationRequested;
    import javax.print.attribute.standard.PrintQuality;
    import javax.swing.JTextArea;
    import javax.swing.text.BadLocationException;
    * @author David J. Ward
    public class SimplePrintableJTextArea extends JTextArea implements Printable {
    * Holds value of property jobName.
    private String jobName = "Print Job for "+System.getProperty("user.name");
    /** Creates a new instance of PrintableJTextArea */
    public SimplePrintableJTextArea() {
    super();
    public SimplePrintableJTextArea(String text) {
    super(text);
    int inchesToPage(double inches) {
    return (int)(inches*72.0);
    int left_margin = inchesToPage(0.5);
    int right_margin = inchesToPage(0.5);
    int top_margin = inchesToPage(0.5);
    int bottom_margin = inchesToPage(0.5);
    public void print() {
    // Create a printerJob object
    final PrinterJob printJob = PrinterJob.getPrinterJob();
    // Set the printable class to this one since we
    // are implementing the Printable interface
    printJob.setPrintable(this);
    printJob.setJobName(jobName);
    //Collect the print request attributes.
    final HashPrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
    attrs.add(OrientationRequested.PORTRAIT);
    attrs.add(Chromaticity.COLOR);
    attrs.add(Chromaticity.MONOCHROME);
    attrs.add(PrintQuality.NORMAL);
    attrs.add(PrintQuality.DRAFT);
    attrs.add(PrintQuality.HIGH);
    //Assume US Letter size, someone else can do magic for other paper formats
    attrs.add(new MediaPrintableArea(0.25f, 0.25f, 8.0f, 10.5f, MediaPrintableArea.INCH));
    // Show a print dialog to the user. If the user
    // clicks the print button, then print, otherwise
    // cancel the print job
    if (printJob.printDialog()) {
    //You may want to do the printing in a thread or SwingWorker
    //But this gets the job done all the same.
    try {
    printJob.print(attrs);
    } catch (Exception PrintException) {
    PrintException.printStackTrace();
    public int print(java.awt.Graphics graphics, java.awt.print.PageFormat pageFormat, int pageIndex) throws PrinterException {
    Graphics2D g2 = (Graphics2D) graphics;
    //Found it unwise to use the TextArea font's size,
    //We area just printing text so use a a font size that will
    //be generally useful.
    g2.setFont(getFont().deriveFont(9.0f));
    int bodyheight = (int)pageFormat.getImageableHeight();
    int bodywidth = (int)pageFormat.getImageableWidth();
    int lineheight = g2.getFontMetrics().getHeight()-(g2.getFontMetrics().getLeading()/2);
    int lines_per_page = (bodyheight-top_margin-bottom_margin)/lineheight;
    int start_line = lines_per_page*pageIndex;
    if (start_line > getLineCount()) {
    return NO_SUCH_PAGE;
    int page_count = (getLineCount()/lines_per_page)+1;
    int end_line = start_line + lines_per_page;
    int linepos = (int)top_margin;
    int lines = getLineCount();
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    for (int line = start_line; line < end_line; line++) {
    try {
    String linetext = getText(
    getLineStartOffset(line),
    getLineEndOffset(line)-getLineStartOffset(line));
    g2.drawString(linetext, left_margin, linepos);
    } catch (BadLocationException e) {
    //never a bad location
    linepos += lineheight;
    if (linepos > bodyheight-bottom_margin) {
    break;
    return Printable.PAGE_EXISTS;
    }

  • JTextArea w/Scroll bar wont scroll AND code drops through if statements

    Hi, I'm still having trouble with the text area in the following code. When you run the code, you get the top arrow on the scroll bar, but the bottom is cut off. Also, a big problem is that no matter what choice is selected from the combo box, the code drops through to the last available value each time. Someone on the forums suggested using an array list for the values in the combo box, but I have not been able to figure out how to do that. A quick example would be apprciated.
    Thank you in advance for any help
    //Import required libraries
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.text.*;
    import java.math.*;
    import java.util.*;
    //Create the class
    public class Week3Assignment407B extends JFrame implements ActionListener
         //Panels used in container
         private JPanel jPanelRateAndTermSelection;         
         //Variables for Menu items
         private JMenuBar menuBar;    
         private JMenuItem exitMenuItem; 
         private JMenu fileMenu; 
         //Variables for user instruction and Entry       
         private JLabel jLabelPrincipal;   
         private JPanel jPanelEnterPrincipal;  
         private JLabel jLabelChooseRateAndTerm; 
         private JTextField jTextFieldMortgageAmt;
         //Variables for combo box and buttons
         private JComboBox TermAndRate;
         private JButton buttonCompute;
         private JButton buttonNew; 
         private JButton buttonClose;
         //Variables display output
         private JPanel jPanelPaymentOutput;
         private JLabel jLabelPaymentOutput;
         private JPanel jPanelErrorOutput;
         private JLabel jLabelErrorOutput;  
         private JPanel jPanelAmoritizationSchedule;
         private JTextArea jTextAreaAmoritization;
         // Constructor 
         public Week3Assignment407B() {            
              super("Mortgage Application");      
               initComponents();      
         // create a method that will initialize the main frame for the GUI
          private void initComponents()
              setSize(700,400);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
              Container pane = getContentPane();
              GridLayout grid = new GridLayout(15, 1);
              pane.setLayout(grid);       
              //declare all of the panels that will go inside the main frame
              // Set up the menu Bar
              menuBar = new JMenuBar();
              fileMenu = new JMenu();
              fileMenu.setText("File");        
              exitMenuItem = new JMenuItem(); 
               exitMenuItem.setText("Exit");
              fileMenu.add(exitMenuItem); 
              menuBar.add(fileMenu);       
              pane.add(menuBar);
              //*******************TOP PANEL ENTER PRINCIPAL*****************************//
              // Create a label that will advise user to enter a principle amount
              jPanelEnterPrincipal = new JPanel(); 
              jLabelPrincipal = new JLabel("Amt to borrow in whole numbers");
              jTextFieldMortgageAmt = new JTextField(10);
              GridLayout Principal = new GridLayout(1,2);
              jPanelEnterPrincipal.setLayout(Principal); 
                jPanelEnterPrincipal.add(jLabelPrincipal);
              jPanelEnterPrincipal.add(jTextFieldMortgageAmt);
              pane.add(jPanelEnterPrincipal);
              //****************MIDDLE PANEL CHOOSE INTEREST RATE AND TERM*****************//
              // Create a label that will advise user to choose an Int rate and term combination
              // from the combo box
              jPanelRateAndTermSelection = new JPanel();
              jLabelChooseRateAndTerm = new JLabel("Choose the Rate and Term");
              buttonCompute = new JButton("Compute Mortgage");
              buttonNew = new JButton("New Mortgage");
              buttonClose = new JButton("Close");
              GridLayout RateAndTerm = new GridLayout(1,5);
              //FlowLayout RateAndTerm = new FlowLayout(FlowLayout.LEFT);
              jPanelRateAndTermSelection.setLayout(RateAndTerm);
              jPanelRateAndTermSelection.add(jLabelChooseRateAndTerm);
              TermAndRate = new JComboBox();
              jPanelRateAndTermSelection.add(TermAndRate);
              TermAndRate.addItem("7 years at 5.35%");
              TermAndRate.addItem("15 years at 5.5%");
              TermAndRate.addItem("30 years at 5.75%");
              jPanelRateAndTermSelection.add(buttonCompute);
              jPanelRateAndTermSelection.add(buttonNew);
              jPanelRateAndTermSelection.add(buttonClose);
              pane.add(jPanelRateAndTermSelection);
              //**************BOTTOM PANEL TEXT AREA FOR AMORITIZATION SCHEDULE***************//
              jPanelAmoritizationSchedule = new JPanel();
              jTextAreaAmoritization = new JTextArea(26,50);
              // add scroll pane to output text area
                   JScrollPane scrollBar = new JScrollPane(jTextAreaAmoritization, 
                   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                     JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              jPanelAmoritizationSchedule.add(scrollBar);
                pane.add(jPanelAmoritizationSchedule);
              //***************ADD THE ACTION LISTENERS TO THE GUI COMPONENTS*****************//
              // Add ActionListener to the buttons and menu item
              exitMenuItem.addActionListener(this);
              buttonCompute.addActionListener(this);         
              buttonNew.addActionListener(this);
              buttonClose.addActionListener(this);
              TermAndRate.addActionListener(this);
              jTextFieldMortgageAmt.addActionListener(this);
              //*************** Set up the Error output area*****************//
              jPanelErrorOutput = new JPanel();
              jLabelErrorOutput = new JLabel();
              FlowLayout error = new FlowLayout();
              jPanelErrorOutput.setLayout(error);
              pane.add(jLabelErrorOutput);
              setContentPane(pane);
              pack();
              setVisible(true);
         //Display error messages
         private void OutputError(String ErrorMsg){
              jLabelErrorOutput.setText(ErrorMsg);
              jPanelErrorOutput.setVisible(true);
         //create a method that will clear all fields when the New Mortgage button is chosen
         private void clearFields()
              jTextAreaAmoritization.setText("");
              jTextFieldMortgageAmt.setText("");
         //**************CREATE THE CLASS THAT ACTUALLY DOES SOMETHING WITH THE EVENT*****//
         //This is the section that receives the action source and directs what to do with it
         public void actionPerformed(ActionEvent e)
              Object source = e.getSource();
              String ErrorMsg;
              double principal;
              double IntRate;
              int Term;
              double monthlypymt;
              double TermInYears = 0 ;
              if(source == buttonClose)
                   System.exit(0);
              if (source == exitMenuItem) {      
                       System.exit(0);
              if (source == buttonNew)
                   clearFields();
              if (source == buttonCompute)
                   //Make sure the user entered valid numbers
                   try
                        principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                   catch(NumberFormatException nfe)
                        ErrorMsg = (" You Entered an invalid Mortgage amount"
                                  + " Please try again. Please do not use commas or decimals");
                        jTextAreaAmoritization.setText(ErrorMsg);
                   principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                    if (TermAndRate.getSelectedItem() == "7 years at 5.35%") ;
                        Term = 7;
                        IntRate = 5.35;
                    if (TermAndRate.getSelectedItem()  == "15 years at 5.5%") ;
                        Term = 15;
                        IntRate = 5.5;
                    if (TermAndRate.getSelectedItem() == "30 years at 5.75%") ;
                        Term = 30;
                        IntRate = 5.75;
                   //Variables have been checked for valid input, now calculate the monthly payment
                   NumberFormat formatter = new DecimalFormat ("$###,###.00");
                   double intdecimal = intdecimal = IntRate/(12 * 100);
                   int months = Term * 12;
                   double monthlypayment = principal *(intdecimal / (1- Math.pow((1 + intdecimal),-months)));
                   //Display the Amoritization schedule
                   jTextAreaAmoritization.setText(" Loan amount of " + formatter.format(principal)
                                                    + "\n"
                                                    + " Interest Rate is " +  IntRate + "%"
                                            + "\n"
                                            + " Term in Years "  + Term
                                            + " Monthly payment "+  formatter.format(monthlypayment)
                                            + "\n"
                                            + "  Amoritization is as follows:  "
                                            + "------------------------------------------------------------------------");
         public Insets getInsets()
              Insets around = new Insets(35,20,20,35);
              return around;
         //Main program     
         public static void main(String[]args) { 
              Week3Assignment407B frame = new Week3Assignment407B(); 
       }

    here's your initComponents with a couple of changes, the problem was the Gridlayout(15,1)
    also, the scrollpane needed a setPreferredSize()
      private void initComponents()
        setSize(700,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Container pane = getContentPane();
        JPanel pane = new JPanel();
        //GridLayout grid = new GridLayout(15, 1);
        GridLayout grid = new GridLayout(2, 1);
        pane.setLayout(grid);
        menuBar = new JMenuBar();
        fileMenu = new JMenu();
        fileMenu.setText("File");
        exitMenuItem = new JMenuItem();
        exitMenuItem.setText("Exit");
        fileMenu.add(exitMenuItem);
        menuBar.add(fileMenu);
        //pane.add(menuBar);
        setJMenuBar(menuBar);
        jPanelEnterPrincipal = new JPanel();
        jLabelPrincipal = new JLabel("Amt to borrow in whole numbers");
        jTextFieldMortgageAmt = new JTextField(10);
        GridLayout Principal = new GridLayout(1,2);
        jPanelEnterPrincipal.setLayout(Principal);
          jPanelEnterPrincipal.add(jLabelPrincipal);
        jPanelEnterPrincipal.add(jTextFieldMortgageAmt);
        pane.add(jPanelEnterPrincipal);
        jPanelRateAndTermSelection = new JPanel();
        jLabelChooseRateAndTerm = new JLabel("Choose the Rate and Term");
        buttonCompute = new JButton("Compute Mortgage");
        buttonNew = new JButton("New Mortgage");
        buttonClose = new JButton("Close");
        GridLayout RateAndTerm = new GridLayout(1,5);
        jPanelRateAndTermSelection.setLayout(RateAndTerm);
        jPanelRateAndTermSelection.add(jLabelChooseRateAndTerm);
        TermAndRate = new JComboBox();
        jPanelRateAndTermSelection.add(TermAndRate);
        TermAndRate.addItem("7 years at 5.35%");
        TermAndRate.addItem("15 years at 5.5%");
        TermAndRate.addItem("30 years at 5.75%");
        jPanelRateAndTermSelection.add(buttonCompute);
        jPanelRateAndTermSelection.add(buttonNew);
        jPanelRateAndTermSelection.add(buttonClose);
        pane.add(jPanelRateAndTermSelection);
        jPanelAmoritizationSchedule = new JPanel();
        jTextAreaAmoritization = new JTextArea(26,50);
        JScrollPane scrollBar = new JScrollPane(jTextAreaAmoritization,
          JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollBar.setPreferredSize(new Dimension(500,100));//<------------------------
        jPanelAmoritizationSchedule.add(scrollBar);
        getContentPane().add(pane,BorderLayout.NORTH);
        getContentPane().add(jPanelAmoritizationSchedule,BorderLayout.CENTER);
        exitMenuItem.addActionListener(this);
        buttonCompute.addActionListener(this);
        buttonNew.addActionListener(this);
        buttonClose.addActionListener(this);
        TermAndRate.addActionListener(this);
        jTextFieldMortgageAmt.addActionListener(this);
        jPanelErrorOutput = new JPanel();
        jLabelErrorOutput = new JLabel();
        FlowLayout error = new FlowLayout();
        jPanelErrorOutput.setLayout(error);
        //pane.add(jLabelErrorOutput);not worrying about this one
        //setContentPane(pane);
        pack();
        setVisible(true);
      }instead of
    if (TermAndRate.getSelectedItem() == "7 years at 5.35%") ;
    Term = 7;
    IntRate = 5.35;
    you would be better off setting up arrays
    int[] term = {7,15,30};
    double[] rate = {5.35,5.50,5.75};
    then using getSelectedIndex()
    int loan = TermAndRate.getSelectedIndex()
    Term = term[loan];
    IntRate = rate[loan];

  • Line up text in a JTextArea

    I'm trying to format line up text in columns in a JTextArea. Here is an example of what I'm trying to do.
    SubTotal $5.00
    Tax $8.00
    Total $13.00
    I've tried formating the text so that the first work will be a certain length but it still will not line up correctly in the text area because different letters take up different amounts of space. Thanks

    change the font of the textarea to monospaced, then append the data
    something like in this println
    class Testing
      public Testing()
        String pad = "                   ";
        String[][] lines = {{"SubTotal", "$5.00"},{"Tax", "$8.00"},{"Total", "$13.00"}};
        for(int x = 0; x < lines.length; x++)
          System.out.println(lines[x][0]+(pad+lines[x][1]).substring(lines[x][0].length()+lines[x][1].length()));
      public static void main(String[] args){new Testing();}
    }

  • Multiple text colors in a JTextArea

    i created a JTextArea in a frame --- // JTextArea ta = new JTextArea();
    and wrote some words onto it with codes like: ta.append("abcd");
    ta.append("efg");
    how to make the color of the words "abcd" different from "efg"?

    JTextArea doesn't support multiple fonts and colours. Have a look at JTextPane or JEditorPane which allow more flexibility in formatting your text. JEditorPane also supports HTML.

  • JTextArea seems to be invisible

    Hi,
    Java programming is not my strength. However, I've been required to develop a design package of late. I've been updating the GUI to combine several programs into a tabbed pane layout. However, the JTextArea I want ot use to display the results of my claculations wont appear. Is any one able to help?
    I've attached the two sets of code involved in this problem.
    package frontend;
    import javax.swing.*; //imported for buttons, labels, and images
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeEvent;
    import java.text.*;
    public class Distill extends JPanel
        // Create Layout
        GridBagLayout layout;
        GridBagConstraints constraints;
        // Create Initial Variables
        double Finitial = 267583.3482;
        double dFinitial = 0.0;
        double Dinitial = 36703.45493;
        double dDinitial = 0.0;
        double dtinitial = 0.0;
        double Rinitial = 0.369514598;
        double Mwfinitial = 175.6623;
        double Ninitial = 12;
        double Pdinitial = 306;
        double Pbinitial = 321.3;
        double Fvinitial = 52355.3606;
        double Flinitial = 15357.0823;
        double RHOvinitial = 7.6287;
        double RHOlinitial = 632.4401;
        double PSinitial = 0.55;
        double PFinitial = 80;
        double DAinitial = 12;
        double Hainitial = 10;
        double Hwinitial = 0.05;
        double Dhinitial = 0.005;
        double Ptinitial = 0.005;
        double tdinitial = 70;
        double Wuinitial = 0.05;
        double Wcinitial = 0.05;
        // Buttons
        private JButton CalculateButton;
        // Create Text Fields
        private JFormattedTextField FField;
        private JFormattedTextField dFField;
        private JFormattedTextField DField;
        private JFormattedTextField dDField;
        private JFormattedTextField dtField;
        private JFormattedTextField RField;
        private JFormattedTextField MwfField;
        private JFormattedTextField NField;
        private JFormattedTextField PdField;
        private JFormattedTextField PbField;
        private JFormattedTextField FvField;
        private JFormattedTextField FlField;
        private JFormattedTextField RHOvField;
        private JFormattedTextField RHOlField;
        private JFormattedTextField PSField;
        private JFormattedTextField PFField;
        private JFormattedTextField DAField;
        private JFormattedTextField HaField;
        private JFormattedTextField HwField;
        private JFormattedTextField DhField;
        private JFormattedTextField PtField;
        private JFormattedTextField tdField;
        private JFormattedTextField WuField;
        private JFormattedTextField WcField;
        // Number Formats
        private NumberFormat amountFormat;
        public Distill()                                                            // Constructor Information
            // Layout Setup      
            layout = new GridBagLayout();
            setLayout( layout );
            setBackground(Color.white);
            constraints = new GridBagConstraints();
            // Initialize Buttons       
            CalculateButton = new JButton("Calculate");
            addComponent(CalculateButton, 12, 2, 1, 1);
            // Create Button Handler       
            ButtonHandler calculate = new ButtonHandler();
            CalculateButton.addActionListener( calculate );
            // Create Labels
            // Input Labels
            JLabel InputLabel = new JLabel(" << Required Input Variables>> ");
            JLabel FLabel = new JLabel("Feed Flow (kg/h)");
            JLabel DLabel = new JLabel("Distillate Flowrate (kg/h)");
            JLabel dtLabel = new JLabel("time over which change occurs (s)");
            JLabel MwfLabel = new JLabel ("Molecular Weight of Feed (kg/kmol)"); 
            JLabel NLabel = new JLabel ("Number of Real Stages");
            JLabel PdLabel = new JLabel ("Top Pressure (kPa)");
            JLabel PbLabel = new JLabel ("Bottom Pressure (kPa)");
            JLabel FvLabel = new JLabel ("Vapor Flowrate (kg/h)");
            JLabel FlLabel = new JLabel ("Liquid Flowrate (kg/h)");
            JLabel RHOvLabel = new JLabel ("Vapor Density (kg/m3)");
            JLabel RHOlLabel = new JLabel ("Liquid Density (kg/m3)");
            JLabel PSLabel = new JLabel ("Plate Spacing (m)");
            JLabel PFLabel = new JLabel ("Percent Flooding");
            JLabel DALabel = new JLabel ("Downcomer Area as a percentage of plate area ");
            JLabel HALabel = new JLabel ("Hole Active Area Percentage 6, 8 or 10 %" );
            JLabel HwLabel = new JLabel (" Weir Height (m)");
            JLabel DhLabel = new JLabel (" Hole Diameter (m)");
            JLabel PtLabel = new JLabel (" Plate Thickness (m)");
            JLabel tdLabel = new JLabel (" Percent Turndown");
            JLabel WuLabel = new JLabel (" Unperforated Strip Width (m)");
            JLabel WcLabel = new JLabel (" Calming Zone Width (m)");
            JLabel DyLabel = new JLabel (" <<< Dynamic Operation Variables >>>");
            JLabel dFLabel = new JLabel("Change in Feed Flow (kg/h)");
            JLabel dDLabel = new JLabel("Change in Distillate Flowrate (kg/h)");
            JLabel RLabel = new JLabel("Reflux Ratio");
            // Add Labels
            addComponent(InputLabel,1,0,1,1);
            addComponent(FLabel ,2,0,1,1);
            addComponent(DLabel,3,0,1,1);
            addComponent(RLabel ,4,0,1,1);
            addComponent(MwfLabel ,5,0,1,1); 
            addComponent(NLabel ,6,0,1,1);
            addComponent(PdLabel ,7,0,1,1);
            addComponent(PbLabel ,8,0,1,1);
            addComponent(FvLabel ,9,0,1,1);
            addComponent(FlLabel ,10,0,1,1);
            addComponent(RHOvLabel ,11,0,1,1);
            addComponent(RHOlLabel ,12,0,1,1);
            addComponent(PSLabel ,13,0,1,1);
            addComponent(PFLabel ,14,0,1,1);
            addComponent(DALabel ,15,0,1,1);
            addComponent(HALabel ,16,0,1,1);
            addComponent(HwLabel ,17,0,1,1);
            addComponent(DhLabel ,18,0,1,1);
            addComponent(PtLabel ,19,0,1,1);
            addComponent(tdLabel ,20,0,1,1);
            addComponent(WuLabel ,21,0,1,1);
            addComponent(WcLabel ,22,0,1,1);
            addComponent(DyLabel ,23,0,1,1);
            addComponent(dFLabel,24,0,1,1);
            addComponent(dDLabel ,25,0,1,1);
            addComponent(dtLabel ,26,0,1,1);
            // Create Text Fields
            FField = new JFormattedTextField(amountFormat);
            FField = new JFormattedTextField(amountFormat);
            dFField = new JFormattedTextField(amountFormat);
            DField = new JFormattedTextField(amountFormat);
            dDField = new JFormattedTextField(amountFormat);
            dtField = new JFormattedTextField(amountFormat);
            RField = new JFormattedTextField(amountFormat);
            MwfField = new JFormattedTextField(amountFormat);
            NField = new JFormattedTextField(amountFormat);
            PdField = new JFormattedTextField(amountFormat);
            PbField = new JFormattedTextField(amountFormat);
            FvField = new JFormattedTextField(amountFormat);
            FlField = new JFormattedTextField(amountFormat);
            RHOvField = new JFormattedTextField(amountFormat);
            RHOlField = new JFormattedTextField(amountFormat);
            PSField = new JFormattedTextField(amountFormat);
            PFField = new JFormattedTextField(amountFormat);
            DAField = new JFormattedTextField(amountFormat);
            HaField = new JFormattedTextField(amountFormat);
            HwField = new JFormattedTextField(amountFormat);
            DhField = new JFormattedTextField(amountFormat);
            PtField = new JFormattedTextField(amountFormat);
            tdField = new JFormattedTextField(amountFormat);
            WuField = new JFormattedTextField(amountFormat);
            WcField = new JFormattedTextField(amountFormat);
            // Set Initial values to Fields
            FField.setValue(Finitial);
            dFField.setValue( dFinitial);
            DField.setValue( Dinitial);
            dDField.setValue( dDinitial);
            dtField.setValue( dtinitial);
            RField.setValue( Rinitial);
            MwfField.setValue( Mwfinitial);
            NField.setValue( Ninitial);
            PdField.setValue( Pdinitial);
            PbField.setValue( Pbinitial);
            FvField.setValue( Fvinitial);
            FlField.setValue( Flinitial);
            RHOvField.setValue( RHOvinitial);
            RHOlField.setValue( RHOlinitial);
            PSField.setValue( PSinitial);
            PFField.setValue( PFinitial);
            DAField.setValue( DAinitial);
            HaField.setValue( Hainitial);
            HwField.setValue( Hwinitial);
            DhField.setValue( Dhinitial);
            PtField.setValue( Ptinitial);
            tdField.setValue( tdinitial);
            WuField.setValue( Wuinitial);
            WcField.setValue( Wcinitial);
            // Set Number of Columns
            FField.setColumns(12);
            dFField.setColumns(12);
            DField.setColumns(12);
            dDField.setColumns(12);
            dtField.setColumns(12);
            RField.setColumns(12);
            MwfField.setColumns(12);
            NField.setColumns(12);
            PdField.setColumns(12);
            PbField.setColumns(12);
            FvField.setColumns(12);
            FlField.setColumns(12);
            RHOvField.setColumns(12);
            RHOlField.setColumns(12);
            PSField.setColumns(12);
            PFField.setColumns(12);
            DAField.setColumns(12);
            HaField.setColumns(12);
            HwField.setColumns(12);
            DhField.setColumns(12);
            PtField.setColumns(12);
            tdField.setColumns(12);
            WuField.setColumns(12);
            WcField.setColumns(12);
            // Add Required Number Fields
            addComponent(FField ,2,1,1,1);
            addComponent(DField  ,3,1,1,1);
            addComponent(RField ,4,1,1,1);
            addComponent(MwfField ,5,1,1,1);
            addComponent(NField ,6,1,1,1);
            addComponent(PdField ,7,1,1,1);
            addComponent(PbField ,8,1,1,1);
            addComponent(FvField ,9,1,1,1);
            addComponent(FlField ,10,1,1,1);
            addComponent(RHOvField ,11,1,1,1);
            addComponent(RHOlField ,12,1,1,1);
            addComponent(PSField ,13,1,1,1);
            addComponent(PFField ,14,1,1,1);
            addComponent(DAField ,15,1,1,1);
            addComponent(HaField , 16,1,1,1);
            addComponent(HwField ,17,1,1,1);
            addComponent(DhField ,18,1,1,1);
            addComponent(PtField ,19,1,1,1);
            addComponent(tdField ,20,1,1,1);
            addComponent(WuField ,21,1,1,1);
            addComponent(WcField ,22,1,1,1);
            addComponent(dFField ,24,1,1,1);
            addComponent(dDField ,25,1,1,1);
            addComponent(dtField ,26,1,1,1);
            // Create Ouput Field
            //create text area
         String header = "Results appear here";
         JTextArea textArea = new JTextArea(header);
         textArea.setEditable(false);
         textArea.setMargin(new Insets(1, 4, 26, 4));
            textArea.setBackground(Color.RED);
    //     //create panel to contain text area
    //     JPanel textAreaPane = new JPanel();
    //     textAreaPane.add(textArea);
    //        textAreaPane.setBorder(BorderFactory.createCompoundBorder(
    //                BorderFactory.createTitledBorder("Output Results"),
    //                BorderFactory.createEmptyBorder(0, 5, 5, 5)));
        private void setUpFormats()
            amountFormat = NumberFormat.getNumberInstance();
        private void addComponent( Component component,
                int row, int column, int width, int height )
            constraints.gridx = column;
            constraints.gridy = row;
            layout.setConstraints( component, constraints);
            add ( component );
        private class ButtonHandler implements ActionListener
            public void actionPerformed( ActionEvent event )
                double F = ((Number)FField.getValue()).doubleValue();
                double D = ((Number)DField.getValue()).doubleValue();
                double R = ((Number)RField.getValue()).doubleValue();
                double Mw = ((Number)MwfField.getValue()).doubleValue();
                double N = ((Number)NField.getValue()).doubleValue();
                double Pd = ((Number)PdField.getValue()).doubleValue();
                double Pb = ((Number)PbField.getValue()).doubleValue();
                double Fv = ((Number)FvField.getValue()).doubleValue();
                double Fl = ((Number)FlField.getValue()).doubleValue();
                double RHOv = ((Number)RHOvField.getValue()).doubleValue();
                double RHOl = ((Number)RHOlField.getValue()).doubleValue();
                double PS = ((Number)PSField.getValue()).doubleValue();
                double PF = ((Number)PFField.getValue()).doubleValue();
                double DA = ((Number)DAField.getValue()).doubleValue();
                double Ha = ((Number)HaField.getValue()).doubleValue();
                double Hw = ((Number)HwField.getValue()).doubleValue();
                double Dh = ((Number)DhField.getValue()).doubleValue();
                double Pt = ((Number)PtField.getValue()).doubleValue();
                double td = ((Number)tdField.getValue()).doubleValue();
                double Wu = ((Number)WuField.getValue()).doubleValue();
                double Wc = ((Number)WcField.getValue()).doubleValue();
                double dF = ((Number)dFField.getValue()).doubleValue();;
                double dD = ((Number)dDField.getValue()).doubleValue();
                double dt = ((Number)dtField.getValue()).doubleValue();
                JOptionPane.showMessageDialog(null, "Import Successful " + F);
    }and the part that this plugs into so to speak
    package frontend;
    import java.awt.*;                                                              // Import Relevant Libraries
    import java.awt.event.*;
    import java.applet.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Front extends JFrame{                                              // Setup Main Frame
        private JTabbedPane tabbedPane;
        public Front()                                                             
            super("Chemical Design Workshop");                                      // Set Conditions On Main Window
            setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
            addWindowListener(new WindowAdapter()
                public void WindowClosing(WindowEvent e)
                    System.exit(0);
            tabbedPane = new JTabbedPane(SwingConstants.LEFT);
            tabbedPane.setBackground(Color.blue);
            tabbedPane.setForeground(Color.white);
            populateTabbedPane();
            buildMenu();
            getContentPane().add(tabbedPane);
        private void populateTabbedPane()
            tabbedPane.addTab("Distillation",null,new Distill(), "Distillation");
            tabbedPane.addTab("Decanter",null,new Decant(), "Decanter");
        private void buildMenu()
            JMenuBar mb = new JMenuBar();
            JMenu menu = new JMenu("File");
            JMenuItem item = new JMenuItem("Exit");                                 //Closes the application from the Exit
            item.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                System.exit(0);
        menu.add(item);
        mb.add(menu);
        setJMenuBar(mb);
        public static void main(String args[]){
        Front frame = new Front();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    I just had one more question. Now that the field is added (thank you by the way) I was wondering why it is only the size of the text string inside it?

Maybe you are looking for

  • P4MAM-V and Celeron 320D

    Just thought somebody should know that if you install a Celeron 320D into a P4MAM-V logic board and go into the BIOS, make a change and try to save the change, the board will lock up. I've tried this with different processors (all 320D) and different

  • Photoshop Touch for iPad v2.50 strips exif data

    I would like ALL original Exif data preserved.  This is very important to me.  Is this a bug, a planned fix, or have I neglected to set something?

  • Report generation tools from WLP behaviout tracking tables.

    Hi All, Can somebody suggest me tools that are available and can be integrated with WLP 8.1 for generating Report from default Behavoiur tacking tables provided by WLP?? Any pointers for such tools are also welcome. TIA, Prashanth bhat.

  • Can't rebuid index for failed index

    Hi, I got a kind of indexing failure for certain reason, for example, using too long name of dot-notation to specifying a object attribute for indexing. Then I drop the failed index by the following statement: drop index myIdx force; Then try to re-c

  • Firefox is painfully slow, but Safari is normal/quick

    Hello. My pc laptop is running so slooow with Firefox browser, but with Safari it is normal, fast. This started 2 days ago. Firefox was running very nicely, fast, normal. Now I have to wait to see the letters after I type....everything is slow... Why