Close a JTextArea?

How do I close a JTextArea?
JTextArea.close();?
JTextArea.exit();?

ColinDiam wrote:
You can use textArea.setEnabled(false);
This removes it from use...No it doesn't. It does what it says: sets the enabled property to false, which disables the component from receiving user input. No more, no less.
db

Similar Messages

  • 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.

  • Bug in JTextArea/JTextPane ??

    Hi,
    I am facing huge memory leak problems with JTextArea/JTextPane. After considerable investigation, I found out that the Document associated with the component is not being GC'ed properly. I ran OptimizeIt and found out that the memory is being consumed by the JTextPane.setText() method. I have implmented a HTML viewer to display large amounts of HTML data and it is leaking memory like crazy on each successive execution. Any thoughts ??
    JDK1.4.2_01, WinXP
    Here is the code fragment:
    public class ReportViewer extends BaseFrame implements FontChange_int
         private     String          cReport;          
         private boolean          testMode = false;     
         // Graphical components
         private     BorderLayout     cMainLayout;
         private     JButton          cClose;
         private     JTextPane     cRptPane;
         private     Button          cClose2;
         private ViewUpdater cViewUpdater = null;
         // Constants
         final     static     int     startupXSize = 650;
         final     static     int     startupYSize = 500;
         // Methods
         public ReportViewer(String report, ReportMain main)
              // BaseFrame extends JFrame
              super("Reports Viewer", true, startupXSize, startupYSize);
              testMode = false;
              cReport = report;
              cViewUpdater = new ViewUpdater();
              initialize();
         public void initialize()
              // Create main layout manager
              cMainLayout = new BorderLayout();
              getContentPane().setLayout(cMainLayout);
              // Quick button bar - print, export, save as
              JToolBar     topPanel = new JToolBar();
              topPanel.setBorder(new BevelBorder(BevelBorder.RAISED) );
              java.net.URL     url;
              topPanel.add(Box.createHorizontalStrut(10));
              url = Scm.class.getResource("images/Exit.gif");
              cClose = new Button(new ImageIcon(url), true);
              cClose.setToolTipText("Close Window");
              topPanel.add(cClose);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              // Main view window - HTML
              cRptPane = new JTextPane();
              cRptPane.setContentType("text/html");
              cRptPane.setEditable(false);
              JScrollPane sp = new JScrollPane(cRptPane);
              getContentPane().add(sp, BorderLayout.CENTER);
              // Main button - Close
              JPanel     bottomPanel = new JPanel();
              url = Scm.class.getResource("images/Exit.gif");
              cClose2 = new Button(new ImageIcon(url), "Close");
              bottomPanel.add(cClose2);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              cClose.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              cClose2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              show();
              cViewUpdater.setText(cReport);
              SwingUtilities.invokeLater(cViewUpdater);
         protected void
         closeWindow()
              super.closeWindow();
              // If I add the following lines, the GC reclaims
    // part of the memory but does not flush out the text
    // component as a whole
              /*Document doc = cRptPane.getDocument();
              try
                   doc.remove(0,doc.getLength());
              catch(Exception e) {;}
              doc=null; */
              cRptPane=null;
              cReport = null;
              cViewUpdater = null;
              dispose();
         private class ViewUpdater implements Runnable
              private String cText = null;
              public ViewUpdater() {;}
              public void
              setText(String text) {
                   cText = text;
              public void
              run() {
                   cRptPane.setText(cText);
                   cRptPane.setCaretPosition(0);
                   cText = null;
         // Local main - for testing
         public static void main(String args[])
              //new ReportViewer(str,comp);
    Sudarshan
    www.spectrumscm.com

    Hi,
    I am facing huge memory leak problems with JTextArea/JTextPane. After considerable investigation, I found out that the Document associated with the component is not being GC'ed properly. I ran OptimizeIt and found out that the memory is being consumed by the JTextPane.setText() method. I have implmented a HTML viewer to display large amounts of HTML data and it is leaking memory like crazy on each successive execution. Any thoughts ??
    JDK1.4.2_01, WinXP
    Here is the code fragment:
    public class ReportViewer extends BaseFrame implements FontChange_int
         private     String          cReport;          
         private boolean          testMode = false;     
         // Graphical components
         private     BorderLayout     cMainLayout;
         private     JButton          cClose;
         private     JTextPane     cRptPane;
         private     Button          cClose2;
         private ViewUpdater cViewUpdater = null;
         // Constants
         final     static     int     startupXSize = 650;
         final     static     int     startupYSize = 500;
         // Methods
         public ReportViewer(String report, ReportMain main)
              // BaseFrame extends JFrame
              super("Reports Viewer", true, startupXSize, startupYSize);
              testMode = false;
              cReport = report;
              cViewUpdater = new ViewUpdater();
              initialize();
         public void initialize()
              // Create main layout manager
              cMainLayout = new BorderLayout();
              getContentPane().setLayout(cMainLayout);
              // Quick button bar - print, export, save as
              JToolBar     topPanel = new JToolBar();
              topPanel.setBorder(new BevelBorder(BevelBorder.RAISED) );
              java.net.URL     url;
              topPanel.add(Box.createHorizontalStrut(10));
              url = Scm.class.getResource("images/Exit.gif");
              cClose = new Button(new ImageIcon(url), true);
              cClose.setToolTipText("Close Window");
              topPanel.add(cClose);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              // Main view window - HTML
              cRptPane = new JTextPane();
              cRptPane.setContentType("text/html");
              cRptPane.setEditable(false);
              JScrollPane sp = new JScrollPane(cRptPane);
              getContentPane().add(sp, BorderLayout.CENTER);
              // Main button - Close
              JPanel     bottomPanel = new JPanel();
              url = Scm.class.getResource("images/Exit.gif");
              cClose2 = new Button(new ImageIcon(url), "Close");
              bottomPanel.add(cClose2);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              cClose.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              cClose2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              show();
              cViewUpdater.setText(cReport);
              SwingUtilities.invokeLater(cViewUpdater);
         protected void
         closeWindow()
              super.closeWindow();
              // If I add the following lines, the GC reclaims
    // part of the memory but does not flush out the text
    // component as a whole
              /*Document doc = cRptPane.getDocument();
              try
                   doc.remove(0,doc.getLength());
              catch(Exception e) {;}
              doc=null; */
              cRptPane=null;
              cReport = null;
              cViewUpdater = null;
              dispose();
         private class ViewUpdater implements Runnable
              private String cText = null;
              public ViewUpdater() {;}
              public void
              setText(String text) {
                   cText = text;
              public void
              run() {
                   cRptPane.setText(cText);
                   cRptPane.setCaretPosition(0);
                   cText = null;
         // Local main - for testing
         public static void main(String args[])
              //new ReportViewer(str,comp);
    Sudarshan
    www.spectrumscm.com

  • How can I update a JTextArea from another class

    I am new to Java so forgive me if this is confusing, or if I seem to be taking an overly complex route to acheiving my goal.
    I've got a JTextArea component added to a JPanel object, which is then inserted into the JFrame. I have a JMenuBar with a JMenu "file" and a JMenuItem "connect" on this same JFrame. When clicked, the actionEvent of JMenuItem "connect" calls a class "ConnectToDb" to establish a connection with the Database. On a successful connection, I want to append the String "Connection Successful" to the JTextArea component, but since the component is a part of the JPanel object, I cannot seem to get access to the JTextArea component to update it. I tried instantiating the JPanel object from within the "ConnectToDb" class and then called a method I created to set the JTextArea. No luck. Can someone give me an idea of what I need to do that would allow me to update the text of the JTextArea component from anywhere in my program? Once it has been contained in the JPanel or JFrame, can it be updated?
    This is the class that establishes the simple Db Connection
    package cjt;
    import java.io.*;
    import java.sql.*;
    * Get a database connection
    * Creation date: (04/01/2002 4:08:39 PM)
    * @author: Yaffin
    public class ConnectToDB {
    public Connection dbConnection;
    // ConnectToDB constructor
    public ConnectToDB() {
    public Connection DbConnect() {
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String sourceURL = new String("jdbc:odbc:CJTSQL");
    Connection dbConnection = DriverManager.getConnection(sourceURL, "Encryptedtest", "pass");
    System.out.println("Connection Successful\n");
    //this is where I originally tried to append "Connection Successful
    //to the JTextArea Object in WelcomePane()          
    } catch (ClassNotFoundException cnfe) {
    //user code
    System.out.println("This ain't working because of a class not found exeption/n");
    } catch (SQLException sqle) {
    //user code
    System.out.println("SQL Exception caused your DB Connection to SUCK!/n");
    return dbConnection;
    This is the JPanel that contains the JTextArea "ivjStatusArea" I am trying to update from other classes. Specifically the "ConnectToDb" class above.
    package cjt;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    * Build Welcome Pane
    * Creation date: (04/01/2002 3:42:50 PM)
    * @author: yaffin
    public class WelcomePane extends JPanel {
         private JTextArea ivjtxtConnect = null;
         private JLabel ivjwelcomeLbl = null;
         private JTextArea ivjStatusArea = null;
    * WelcomePane constructor comment.
    public WelcomePane() {
         super();
         initialize();
    * Return the StatusArea property value.
    * @return javax.swing.JTextArea
    private javax.swing.JTextArea getStatusArea() {
         if (ivjStatusArea == null) {
              try {
                   ivjStatusArea = new javax.swing.JTextArea();
                   ivjStatusArea.setName("StatusArea");
                   ivjStatusArea.setLineWrap(true);
                   ivjStatusArea.setWrapStyleWord(true);
                   ivjStatusArea.setBounds(15, 153, 482, 120);
                   ivjStatusArea.setEditable(false);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjStatusArea;
    * Initialize the class.
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("WelcomePane");
              setLayout(null);
              setSize(514, 323);
              add(getStatusArea(), getStatusArea().getName());
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    This is the main class where evrything is brought together. Notice the BuildMenu() method where the JMenuItem "connect" is located. Also notice the PopulateTabbedPane() method where WelcomePane() is first instantiated.
    * The main application window
    * Creation date: (04/01/2002 1:31:20 PM)
    * @author: Yaffin
    public class CjtApp extends JFrame {
    private JTabbedPane tabbedPane;
    private ConnectToDB cdb;
    private Connection dbconn;
    public CjtApp() {
    super("CJT Allocation Application");
    // Closes from title bar
    //and from menu
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    tabbedPane = new JTabbedPane(SwingConstants.TOP);
    tabbedPane.setForeground(Color.white);
    //add menubar to frame
    buildMenu();
    //populate and add the tabbed pane
    populateTabbedPane(dbconn);
    //tabbedPane.setEnabledAt(1, false);
    //tabbedPane.setEnabledAt(2, false);
    getContentPane().add(tabbedPane);
    pack();
    * Build menu bar and menus
    * Creation date: (04/01/2002 2:42:54 PM)
    private void buildMenu() {
    // Instantiates JMenuBar, JMenu,
    // and JMenuItem.
    JMenuBar menubar = new JMenuBar();
    JMenu menu = new JMenu("File");
    JMenuItem item1 = new JMenuItem("Connect");
    JMenuItem item2 = new JMenuItem("Exit");
    //Opens database connection screen
    item1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    //call the ConnectToDb class for a database connection
    ConnectToDB cdb = new ConnectToDB();
    dbconn = cdb.DbConnect();
    }); // Ends buildMenu method
    //Closes the application from the Exit
    //menu item.
    item2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    }); // Ends buildMenu method
    //Adds the item to the menu object
    menu.add(item1);
    menu.add(item2);
    //Adds the menu object with item
    //onto the menu bar     
    menubar.add(menu);
    //Sets the menu bar in the frame
    setJMenuBar(menubar);
    } //closes buildMenu
    public static void main(String[] args) {
    CjtApp mainWindow = new CjtApp();
    mainWindow.setSize(640, 480);
    mainWindow.setBackground(Color.white);
    mainWindow.setVisible(true);
    mainWindow.setLocation(25, 25);
    * Add tabs to the tabbedPane.
    * Creation date: (04/01/2002 2:52:19 PM)
    private void populateTabbedPane(Connection dbconn) {
         Connection dbc = dbconn;
         tabbedPane.addTab(
         "Welcome",
    null,
    new WelcomePane(),
    "Welcome to CJT Allocation Application");
         tabbedPane.addTab(
         "Processing",
    null,
    new ProcessPane(dbc),
    "Click here to process an allocation");
         tabbedPane.addTab(
         "Reporting",
    null,
    new ReportPane(),
    "Click here for reports");
    //End
    Thanks for any assistance you can provide.
    Yaffin

    Thanks gmaurice1. I appreciate the response. I believe I understand your explanation. I am clear that the calling code needs access to the WelcomPane() object. I am assuming that the constructor for the calling class must have the JPanel WelcomePane() instance passed to it as an argument. This way I can refer directly to this specific instance of the object. Is this correct?
    Also, where would you create the set method? I tried to create a set method as part of the WelcomePane() class, and then call it from the calling class, but it didn't seem to work. Lastly, a globally accessible object? Can you explain this concept briefly? Thanks again for your help.
    yaffin

  • Cant Get Text To Show In JTextArea

    Hi guys,
    I'm trying to create a very simplistic GUI where the output of an IRC server is shown in a JTextArea. However for the life of me I can not get any text at all to show in the text area. Here's the class that creates the user interface:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    public class SwingTest extends javax.swing.JFrame implements ActionListener {
         JButton connect = new JButton("Connect");
         JTextArea chat = new JTextArea();
        public SwingTest() {
             //set the title of the frame
             super("Chat Window");
             //set the size of the frame
             setSize(800, 600);
             //set what happens when the close button is clicked
             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             // create the scroll pane to add the text area to
             chat.setLineWrap(true);
             JScrollPane scroll = new JScrollPane(chat, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
             //create the container panel
             JPanel jp = new JPanel();
             //create the layout manager and assign it to the container panel
             BoxLayout horizontal = new BoxLayout(jp, BoxLayout.Y_AXIS);
             jp.setLayout(horizontal);
             //add the text area and button to the container panel
             jp.add(scroll);
             jp.add(connect);
             //add the container panel to the frame
             add(jp);
             //make the frame and its contents visible
             setVisible(true);
             //add an event listener to the connect button
             connect.addActionListener(this);
        public void actionPerformed(ActionEvent event) {
             int temp = 1;
             SockThread mySock = new SockThread();
                 try {
                      Thread.sleep(20000);
                  while(temp == 1) {
                   while(mySock.pinger != false) {
                        chat.append(mySock.getStatus()+ "\n");
                        mySock.pinger = false;
                        break;
                 } catch  (InterruptedException ie) {
                      chat.setText("Error " + ie.getMessage());
        public static void main(String[] arguments)  {
             //create an instance of the SwingTest class and let it do its thing
             SwingTest st = new SwingTest();
    }

    Thanks hiwa, i did what you suggested and created a worker thread, but still I'm getting nothing in that JTextArea. I'm new to working with worker threads though, so if anyone wouldn't taking a look at my code just to see if I'm doing something wrong i would greatly appreciate it.
    Here is my worker class:
    import javax.swing.*;
    public class ChatWorker extends SwingWorker {
         String messages;
         String output;
         JTextArea chat;
         public ChatWorker() {
              super();
         protected String doInBackground() {
              int temp = 1;
              SockThread st = new SockThread();
              try {
                   Thread.sleep(20000);
                   //Perpetual loop needed to keep checking for server messages
                   while(temp == 1) {
                   while(st.pinger != false) {
                        messages = st.getStatus();
                        st.pinger = false;
                        break;
              } catch (InterruptedException ie) {
              return messages;
    }And here is the update gui class to make use of the worker thread:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.beans.*;
    public class SwingTest extends javax.swing.JFrame implements ActionListener, PropertyChangeListener {
         JButton connect = new JButton("Connect");
         JTextArea chat = new JTextArea();
         ChatWorker cw;
        public SwingTest() {
             //set the title of the frame
             super("Chat Window");
             //set the size of the frame
             setSize(800, 600);
             //set what happens when the close button is clicked
             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             // create the scroll pane to add the text area to
             chat.setLineWrap(true);
             JScrollPane scroll = new JScrollPane(chat, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
             //create the container panel
             JPanel jp = new JPanel();
             //create the layout manager and assign it to the container panel
             BoxLayout horizontal = new BoxLayout(jp, BoxLayout.Y_AXIS);
             jp.setLayout(horizontal);
             //add the text area and button to the container panel
             jp.add(scroll);
             jp.add(connect);
             //add the container panel to the frame
             add(jp);
             //make the frame and its contents visible
             setVisible(true);
             //add an event listener to the connect button
             connect.addActionListener(this);
        public void actionPerformed(ActionEvent event) {
             try {
             cw = new ChatWorker();
             cw.addPropertyChangeListener(this);
             cw.execute();
             } catch (Exception exc) {
        public void propertyChange(PropertyChangeEvent event) {
             try {
                  String tempText = (String)cw.get();
                  chat.append(tempText + "\n");
             }catch (Exception exc) {
        public static void main(String[] arguments)  {
             //create an instance of the SwingTest class and let it do its thing
             SwingTest st = new SwingTest();
    }

  • 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];

  • How to get InputStream from JTextArea.getText() string?

    hello,
    well the postname pretty much says it, i need to get an InputStream for the String of a JTextArea.
    thing is, i want to save the string in a textfile, but the new line isnt recognized when i write it to the file.
    FileWriter fw = new FileWriter ("text.txt");
    fw.write(editField.getText());  // editField is my JTextArea instanceso i thought of doing smth like this
    String lineSeparator = System.getProperty("line.separator");
    // somehow getting the InputStream for my editField and save it in "is"
    BufferedReader br = new BufferedReader(new InputStreamReader (is));
    String line;
    while ((line = br.readLine()) != null) {
    fw.write(line);
    fw.write(lineSeparator);
    }

    pSaiko wrote:
    hello,
    well the postname pretty much says it, i need to get an InputStream for the String of a JTextArea.
    thing is, i want to save the string in a textfile, but the new line isnt recognized when i write it to the file.
    FileWriter fw = new FileWriter ("text.txt");
    fw.write(editField.getText());  // editField is my JTextArea instanceso i thought of doing smth like this
    String lineSeparator = System.getProperty("line.separator");
    // somehow getting the InputStream for my editField and save it in "is"
    BufferedReader br = new BufferedReader(new InputStreamReader (is));
    String line;
    while ((line = br.readLine()) != null) {
    fw.write(line);
    fw.write(lineSeparator);
    This is very simple, it isn't buffered, but it should work for you.
    Sting s = editfield.getText();
    for(int i=0; i<s.length();i++) fw.write((int)s.charAt(i));
    fw.flush();
    fw.close();

  • Too much data for JTextArea

    Howdy people, I've been stuck on this problem for a while now. I writing a povvy hex-editor, and it works (yay!), but when I open largish files (>= 20kB) it really chokes on it. Not on the conversion from bytes to hex string, but (you guessed it) displaying it in the JTextArea. I've tried a couple of things. Make it a Thread (so it can update a pretty progress bar), I tried appending the data in sections, instead of one giant setText().... No go.
    Here's what I have so far:
    import javax.swing.JTextArea;
    public class DisplayThread extends Thread
        private static final int BUFSIZE = 100000;
        private FileEditor parent;
        private JTextArea textArea;
        private StringBuffer data;
        private ProgressDialog pd;
        public DisplayThread(FileEditor p, JTextArea jta, StringBuffer s, ProgressDialog pr)
            parent = p;
            textArea = jta;
            data = s;
            pd = pr;
        public void run()
            System.out.println("starting DisplayThread");
            long time = System.currentTimeMillis();
            textArea.setText("");
            int len = data.length();
            for(int i=0;i<len;i+=BUFSIZE)
                int n = (i+BUFSIZE<len)?i+BUFSIZE:len;
                textArea.append(data.substring(i,n));
                pd.setProgress(i, len);
            System.out.println("It took " + (System.currentTimeMillis() - time) + "ms by buffering");
            time = System.currentTimeMillis();
            textArea.setText(data.toString());
            System.out.println("It took " + (System.currentTimeMillis() - time) + "ms directly");
            textArea.setEditable(true);
            pd.setVisible(false);
            System.out.println("finishing DisplayThread");
    }At the moment I've got both the "bit-by-bit" display method, and the "one-shot-setText()" methods going to compare times, but check out these times for a 900k file...
    It took 673439ms by buffering
    It took 137628ms directly
    For the first one, that's over 11 mins!!!!
    Anyway, I did searches on what to do in this scenario, one answer was Don't!, the other was "only display what's necessary".
    So...
    I've tried to create a "BufferedJTextArea", and only set the text according to what will be visible in the scrollpane/scrollbar, but it's not working (all sorts of complications with adding a scrollbar to a JTextArea, or adding a JTextArea to a scrollPane....)
    Also, even after it loads all the data into the JTextArea, it takes it's sweet time to repaint...
    Any ideas on how to make it faster? Continue with the "BufferedJTextArea" (if that's the case, that'll be the next question)?
    Or give up and warn ppl not to load files larger than about 15k?
    Thanks ppl,
    Radish21

    But with a JList, you can only have one column, right? That'd mean I have to break up the String with \n all over the place.
    I did look at JTable first, and even tried to use one, but I've never used them before, and now I know why. Too damn difficult.
    I'm getting closer now, but still having hiccups (or is it hiccoughs? :)
    I had to make the class a JPanel itself, that adds a BufferedTextArea to a JScrollPane... it works, so why fix it? ;)
    import javax.swing.JTextArea;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import java.awt.event.AdjustmentListener;
    import java.awt.event.AdjustmentEvent;
    public class BufferedJTextArea extends JPanel
        protected BJTextArea textArea;
        protected JScrollPane scrollPane;
        public BufferedJTextArea()
            textArea = new BJTextArea();
            scrollPane = new JScrollPane(textArea);
            scrollPane.getVerticalScrollBar().addAdjustmentListener(textArea);
            setVisible(true);
            setLayout(new java.awt.BorderLayout());
            add(scrollPane, "Center");
        public void setText(String s)
            textArea.setText(s);
        private class BJTextArea extends JTextArea implements AdjustmentListener
            protected static final int BUF_SIZE = 4096; // display 4kB at a time
            protected String data;
            protected int len, startIndex = 0, endIndex = 0;
            private java.awt.FontMetrics fontMetrics;
            private int val = 0;
            public BJTextArea()
                super();
                setLineWrap(true);
                setVisible(true);
                fontMetrics = getFontMetrics(getFont());
            public void adjustmentValueChanged(AdjustmentEvent e)
                val = e.getValue();
                adjustView();
            public void setText(String s)
                data = s;
                len = data.length();
                startIndex = 0;
                if(len <= BUF_SIZE)
                    endIndex = len;
                    super.setText(data);
                else
                    endIndex = -1;
                    val = 0;
                    adjustView();
            protected void adjustView()
                if(endIndex == -1 && startIndex == 0)
                    endIndex = java.lang.Math.min(len, BUF_SIZE);
                    super.setText(data.substring(startIndex, endIndex));
                    return;
                if(len <= BUF_SIZE)
                    return;
                int startLine = scrollPane.getVerticalScrollBar().getValue() / getRowHeight();
                int linesVisible = // haven't worked out what goes here yet
                // Some way to work out whether I need to adjust things.
    }Anyway, thanks for the tips, but I think you're right, I'll stick with the BufferedJTextArea....
    If you have any ideas about checking for if the view is about to get out of range, let me know. Also, I've tried setting the vertical scrollbar's maximum value, but it ignores me (because I need it to be reflect the entire data string, not just the segment displayed). If you have any ideas, they'd be greatly appreciated.
    Cheers,
    Radish21

  • How can I assign a text file to JTextArea component??

    Hi every body, does any boody has a code for read a text file and show this text in a JTextArea??? I'm trying with a FileReader but the text doesn't appear well.
    Thanks in advance.
    Juan

    String s = "";
    BufferedReader reader =
                             new BufferedReader(new FileReader(path));
                        String temp = reader.readLine();
                        s += temp + "\n";
                        while (temp != null)
                             temp = reader.readLine();
                             if (temp != null)
                                  s += temp + "\n";
                        reader.close();
    textArea.setText(s);

  • Why does saving text from a jtextarea to a text file result in....?

    one long string that includes square blocks when the new line should be?
    Why can't I read normal text from a text file. It looks like i have to save it first for it to be read.
    Also why is it that my application succesfully reads and displays the contents of a text file that i just saved but when i manually open that file I don't see it. All i can see is what the text that i manually entered into the text file.
    I use a buffered reader so wondered if there was some caching but have no idea.

    one long string that includes square blocks when the new line should be? If you use something like:
    write(textArea.getText())
    then "\n" will be written to the file as a newline string, but on a Windows platform the newline string is "\r\n".
    You should be using the read(...) and write(...) methods of the JTextArea and the newline string will be handled correctly.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    class TextAreaLoad
         public static void main(String a[])
              final JTextArea edit = new JTextArea(5, 40);
              JButton read = new JButton("Read some.txt");
              read.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             FileReader reader = new FileReader( "some.txt" );
                             BufferedReader br = new BufferedReader(reader);
                             edit.read( br, null );
                             br.close();
                             edit.requestFocus();
                        catch(Exception e2) { System.out.println(e2); }
              JButton write = new JButton("Write some.txt");
              write.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             FileWriter writer = new FileWriter( "some.txt" );
                             BufferedWriter bw = new BufferedWriter( writer );
                             edit.write( bw );
                             bw.close();
                             edit.setText("");
                             edit.requestFocus();
                        catch(Exception e2) {}
              JFrame frame = new JFrame("TextArea Load");
              frame.getContentPane().add( new JScrollPane(edit), BorderLayout.NORTH );
              frame.getContentPane().add(read, BorderLayout.WEST);
              frame.getContentPane().add(write, BorderLayout.EAST);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • 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?

  • How do i display an sql SELECT query in a jtextarea?

    Hi,
    I have a program that takes any SQL string from an inputArea JtextArea and displays "command executed successfuly" in the outputArea JTextArea if it works.
    My question is how do i make the outputArea display the actual query of the SELECT statment? Thanks!
            public void create(String SQLCommand) {
                   String query = SQLCommand;
                   try {
                       Statement stmt = con.createStatement();
                       ResultSet rs = stmt.executeQuery(query);
                       outputArea.setText("Command Executed Sucessfully: \n" + query);
                       rs.close();
                       stmt.close();
                   } catch (SQLException sqlex) {
                       outputArea.setText("Unable to Execute Command: \n" + query);
                       sqlex.printStackTrace();
            }

    It's a variation of the sample code I provided on the last post. Use a Vector of Vector of Objects to store the result set data (row and column data) and use another Vector to store the column names (for the JTable header). Then use the JTable constructor that accepts two Vector parameters to create your table. Eventually you'll want to customize your JTable by creating your own table model and custom cell editor and renderer. For now the sample code below will suffice.
    For more on using JTable see the following:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    Vector header = new Vector();
    Vector result = new Vector();
    int columns = rsmd.getColumnCount();
    /* Retrieve column names */
    for (int i = 1; i <= columns; i++)
      header.add(rsmd.getColumnName(i));
    while (rs.next())
    Vector  row = new Vector();
    /* Columns numbers offset from one */  
    for (int i = 1; i <= columns; i++) 
       row.add(rs.getObject(i));  
    result.add(row);
    JTable table = new JTable(result,header);

  • Output Stream to JTextArea

    Hi there,
    I would like to have the output stream coming from the server to the client displayed on a JTextArea. However, because the coming file is a text document that had its file name passed as a local variable in the main method header with String a[ ], I am having difficulty setting this as the area text because of the incompatible types. This text prints on my command prompt window but I cannot figure out how to get this stream into the JTextArea. This is my code. The objective is to ask a file from the server and have the server send this file to the client so the client can then make changes and save.
    import java.io.*;
    import java.net.*;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JScrollPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import java.util.Formatter;
    public class Client extends JFrame{
            public static JTextArea enterArea1;
            public static JTextArea enterArea2;
            public JButton change;
            public JButton save;
      public Client()
            super ("Client to Server");
            Box box = Box.createHorizontalBox();
            enterArea1 = new JTextArea(10, 15);
            enterArea1.setEditable (true);
            box.add (new JScrollPane (enterArea1));
            change = new JButton("Make Changes");
            box.add(change);
            change.addActionListener(
             new ActionListener()
                public void actionPerformed(ActionEvent event)
                Scanner console = new Scanner (System.in);
             System.out.print ("Input File: ");
             String inputFileName = console.next ();
             System.out.print ("Enter the text that you want to change");
             String inputText1 = console.next ();
             System.out.print ( "Output File: ");
             String outputFileName = console.next();
              try
              FileReader reader = new FileReader (inputFileName);
              Scanner in = new Scanner (reader);
              PrintWriter out = new PrintWriter (outputFileName);
                   String line1 = in.nextLine();
                   out.println( " " + inputText1 );
              out.close();
              catch (IOException exception)
              System.out.println ("Error processing file: " + exception);
            save = new JButton("Save to File");
            box.add(save);
            save.addActionListener(
             new ActionListener()
                public void actionPerformed(ActionEvent event)
                enterArea2.setText (enterArea1.getSelectedText());
            enterArea2 = new JTextArea (10, 15);
            enterArea2.setEditable (false);
            box.add (new JScrollPane (enterArea2));
            add (box);
      public static void main(String a[]) throws IOException {
            Socket sock;
            BufferedReader dis;
            PrintWriter dat;
            Client sendServer = new Client();
            sendServer.setSize (500, 200);
            sendServer.setVisible(true);
            sendServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            sock = new Socket("127.0.0.1",4444);
            dis = new BufferedReader( new InputStreamReader(sock.getInputStream()) );
            dat = new PrintWriter( sock.getOutputStream() );
            dat.println(a[0]);
            dat.flush();
            enterArea1.setText(a[0]);
            PrintStream os = new PrintStream (new FileOutputStream ("out.txt"));
            String fromServer = dis.readLine();
            while (fromServer != null )
               System.out.println(fromServer);
               os.println(fromServer);
               fromServer = dis.readLine();
            sock.close();
    }

    I believe that the logic is to append the text to the JTextArea with something along the lines of this, but since String a[0] is passed in my void method, it is not accepted as a string anymore. The question then becomes how to create a variable that is referenced to the output text on the command window so that this variable can be used to append the same text to the JTextArea. I will appreciate any comments. Right now, it sees the String text as null.
    String text = dat.println(a[0]);
                          dat.flush();
            enterArea1.append(text]);

  • Close button in applet

    hi u see in the code that i have made a button an exit button and i did this code but when i run the code is fine but when i click the exit button it dos not clos the applet
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import javax.swing.*;
    public class assignment2_1 extends Applet implements ActionListener {
         JTextField ID, Mark;
              JLabel IdLabel, MarkLabel;
         JButton ExitButton;
    JTextArea Disply;
    String stnum;
    int studentnum;
    int stid;
    int assimak;
    public void init() {
    GridBagLayout GBL = new GridBagLayout();
         GridBagConstraints cr= new GridBagConstraints();
         setLayout(GBL);
         setBackground(Color.lightGray);
         cr.weightx=cr.weighty = 2.0;
         cr.gridx=1; cr.gridy =2;
         cr.gridheight = 1; cr.gridwidth = 2;
    add(IdLabel=new JLabel("Enter Student ID"),cr);
    //     IdLabel.setBackground(Color.lightGray);
         cr.weightx=cr.weighty = 2.0;
         cr.gridx=5; cr.gridy =2;
         cr.gridheight = 1; cr.gridwidth = 2;
         add(ID = new JTextField(9),cr);
    cr.weightx=cr.weighty = 2.0;
         cr.gridx=1; cr.gridy =3;
         cr.gridheight = 1; cr.gridwidth = 2;
         add(MarkLabel=new JLabel("Enter Assignment Mark"),cr);
    //     MarkLabel.setBackground(Color.lightGray);
    cr.weightx=cr.weighty = 2.0;
    cr.gridx=5; cr.gridy =3;
         cr.gridheight = 1; cr.gridwidth = 2;
         add(Mark=new JTextField(9),cr);
         Mark.addActionListener( this );
    cr.weightx=cr.weighty = 2.0;
    cr.gridx=1; cr.gridy =4;
         cr.gridheight = 1; cr.gridwidth = 2;
         add(Disply=new JTextArea(10, 20),cr);
         Disply.setEditable(false);
    //     Disply.setBackground(Color.lightGray);
    cr.weightx=cr.weighty = 1.0;
    cr.gridx=5; cr.gridy =5;
         cr.gridheight = 1; cr.gridwidth = 2;
         add(ExitButton=new JButton("Exit"),cr);
         ExitButton.addActionListener( this );
    /*     Container container = getContentPane();
              container.setLayout( new FlowLayout() );
         IdLabel = new JLabel("Enter Student ID ");
              container.add( IdLabel );
         ID = new JTextField(9);
              container.add( ID );
         MarkLabel = new JLabel("Enter Assignment Mark ");
              container.add( MarkLabel );
                   Mark = new JTextField(5);
                   Mark.addActionListener( this );
              container.add( Mark );
              Disply = new JTextArea( 10, 20);
              Disply.setEditable(false);
                   container.add( Disply );
         ExitButton = new JButton("Exit");
         ExitButton.addActionListener( this );
              container.add( ExitButton );
    stnum = JOptionPane.showInputDialog( "Enter total assignment" );
    public void actionPerformed(ActionEvent evt) {
    studentnum = Integer.parseInt( stnum );
         stid = Integer.parseInt(ID.getText());
              assimak = Integer.parseInt(Mark.getText());
    if (evt.getSource() == Mark)
    showStatus ("heeeea "+ studentnum);
         if (evt.getSource() == ExitButton )
              System.exit(0);

    Are you trying to run this in a browser or using AppletRunner? I don't think you can close a browser window just by calling System.exit(). You have to find some way to close the browser.
    Check for exceptions in the Java console.

Maybe you are looking for