Focusable JTextArea not gaining focus.

I am creating a JTextArea and want to give it the focus when it's created. THis happens twice in the program, and the first time it works, the second time the JTextArea is created but doesn't get the focus until I click on it.
In both cases the code is called from the Swing event queue (see the output below). In both cases the class which creates the jTextArea is the same (an extension of JPanel), and is added to a new tab in a tabbed pane.
Because I know that you need to make sure that the component's been created before it gets focus, the code to create it and give it focus is:
private javax.swing.JTextArea jtaInfo;
// Class constructor for outer class
  public PanelInfo(String s, boolean editable ) {
    initComponents();  // this is the NetBeans call which creates jtaInfo and a few buttons
    jtaInfo.setText(s);
    jtaInfo.setEditable(editable);
    setVisible(true);
    selectTextBox();
  public void selectTextBox() {
    UtilFunctions.tcaProgramInfoMessage("selectTextBox thread="+Thread.currentThread().getName());
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        UtilFunctions.tcaProgramInfoMessage("Runnable thread="+Thread.currentThread().getName());
        UtilFunctions.tcaProgramInfoMessage("Info frame focusable: "+jtaInfo.isFocusable());
        if (!jtaInfo.requestFocusInWindow()) {
          UtilFunctions.tcaProgramInfoMessage("Failed to give info pane focus");
  }The UtilFunctions.tcaProgramInfoMessage call produces output with a timestamp.
The output is:
Sat Nov 11 11:25:38 GMT 2006: selectTextBox thread=AWT-EventQueue-0
Sat Nov 11 11:25:38 GMT 2006: Runnable thread=AWT-EventQueue-0
Sat Nov 11 11:25:38 GMT 2006: Info frame focusable: true
Sat Nov 11 11:25:44 GMT 2006: selectTextBox thread=AWT-EventQueue-0
Sat Nov 11 11:25:44 GMT 2006: Runnable thread=AWT-EventQueue-0
Sat Nov 11 11:25:44 GMT 2006: Info frame focusable: true
Sat Nov 11 11:25:44 GMT 2006: Failed to give info pane focus
So it seems that the threads are OK, and the area is focusable, but I can't work out why one succeeds and the other fails. The program's too huge to post here - I may be able to cut it down to size. But is there anything obvious that I might be doing wrong?

Because I know that you need to make sure that the component's been created before it gets focus,Actually the parent frame or dialog must be "realized" (maybe thats what you mean by "created") before a component can receive focus. This basically means that you've done a pack() or setVisible(true) on the frame. Using setVisible(true) on the actual component does nothing since by default all JComponents are visible.
The program's too huge to post here - I may be able to cut it down to sizeI fail to see why its so difficult to create a short demo program showing the problem. The code you posted doesn't help because we don't know the context of how the code is executed.
Below is a simple demo that shows an incorrect version and a correct version in 10 lines of code. So if this code doesn't help solve the problem you will now need to wait hours again until you post a version of your code that does demonstrate the problem. Whereas if you had spent 5-10 minutes to create a demo that doesn't work I may have been able to help you out right now.
Simplify your problems and the answer will also be simpler.
import java.awt.*;
import javax.swing.*;
public class FocusTest
     public static void main(String[] args)
          JTextField textField1 = new JTextField("One");
          JTextField textField2 = new JTextField("Two");
          JTextField textField3 = new JTextField("Three");
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          frame.getContentPane().add(textField1, BorderLayout.NORTH);
          frame.getContentPane().add(textField2, BorderLayout.CENTER);
          frame.getContentPane().add(textField3, BorderLayout.SOUTH);
          // This doesn't work
          textField3.requestFocusInWindow();
          frame.pack();
          // This does work
//          textField3.requestFocusInWindow();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
}

Similar Messages

  • JTextArea not gaining focus

    I have a tabbed pane consisting of 2 JPanels. Each panel has a text area (within a scrollpane) on both.
    All I want is for the text area to gain focus when its tab has been clicked.
    I've tried adding a changelistener to the tabbedpane:
            tabbedPane.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    if (tabbedPane.getSelectedIndex() == 0) {
                        textArea1.requestFocus();
                    else {
                        textArea2.requestFocus();
            });but the textareas don't get focus. They do when I press <TAB> but this isn't much use.
    Does anyone have any ideas how I can get the textareas to gain focus?

    import javax.swing.*;
    import javax.swing.event.ChangeListener;
    import javax.swing.event.ChangeEvent;
    import java.awt.*;
    public class TestFocusTabbedPane extends JTabbedPane {
         private JTextArea theFirstTextArea;
         private JTextArea theSecondTextArea;
         public TestFocusTabbedPane() {
              super();
              JPanel tabPanel = new JPanel(new BorderLayout());
              tabPanel.add(new JButton("just for test"), BorderLayout.NORTH);
              theFirstTextArea = new JTextArea();
              theFirstTextArea.setFocusable(true);
              tabPanel.add(new JScrollPane(theFirstTextArea), BorderLayout.CENTER);
              addTab("first", tabPanel);
              tabPanel = new JPanel(new BorderLayout());
              tabPanel.add(new JButton("just for test"), BorderLayout.NORTH);
              theSecondTextArea = new JTextArea();
              theSecondTextArea.setFocusable(true);
              tabPanel.add(new JScrollPane(theSecondTextArea), BorderLayout.CENTER);
              addTab("second", tabPanel);
              addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                        int index = getSelectedIndex();
                        if (index == 0) {
                             theFirstTextArea.requestFocus();
                        } else {
                             theSecondTextArea.requestFocus();
         public static void main(String[] args) {
              final JFrame frame = new JFrame(TestPressedButton.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().add(new TestFocusTabbedPane());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.show();
    }This seems to work. I added the JButton just to show that it doesn't get the focus

  • Windows not gaining focus...

    Hello!
    After recent update (I can't recall having this issue before) windows that previously had focus, but lost it after I opened a new window, do not gain focus after I close the new window. This is very irritating, because now I have to click on the old window all the time, even though it is the top window, to give commands to it.
    The same thing happens also when switching spaces - if I have a window with focus in one space, quickly switch to another to check something (without clicking anywhere) and then go back to the first one, I have to click in the window otherwise I can't write or send commands to it. Even though the cursor is in the window and blinking as if it had focus (if it is an input field).
    A concrete example:
    I am writing this text in Firefox in a textbox on a webpage. I switch spaces forth and back. The cursor is still in the textbox and blinking, but whatever I press nothing happens. Firefox is still the active application (it has the menubar).
    I've tried searching, but wasn't lucky to find anything, is it just me?
    BR,
    stormmind

    It work well in my system. Either on appletview and browser.
    Firefox 3 on Debian Lenny, java 1.6.0_07-b06

  • My safari icon vanished from my desk top in a puff of smoke.  I can not gain access to the internet

    I believe I might have accidentally deleted my Safari icon from off my desktop.  I can not gain access to the internet even from a link off an email.  How do I make safari active again?

    1. Finder > Applications > Safari
       Try launching Safari from Application folder.
    2. If this doesn't help, reinstall OS X.

  • Save As dialog box does not gain focus (bring to foreground) with Windows 7?

    Hello,
    I've got several users with Microsoft Windows 7 (64bit) and Adobe Acrobat 9 Standard (OEM) with the same problem.  When you go to Print to your PDF Printer, the Save As... dialog box does not come to the foreground and gain focus.  Most often it just sits in the taskbar blinking to get their attention.
    However the users get frustrated and often don't realize the Save As box popped up at all.  They did not have this problem with Windows XP.
    I actually can replicate the problem on my own PC.
    Any workarounds for this behaviour?
    Thanks,
    -Tim

    This appears to be a Windows 7 focus issue.
    You can back up your registry and try the fix below, it worked for me.
    Fix number 1
    1. Open Start >> Run and type “regedit” (without quotes)
    2. Navigate to the following path:
    [HKEY_CURRENT_USER\Control Panel\Desktop]
    3. Right Click on the empty space and create a new DWORD value, or modify the existing value named ‘ForegroundLockTimeout’, set or modify the value to 0. (this value will cause the application to take the focus instantly.)
    4. That’s it Done, exit registry and restart windows for changes to come into effect.

  • Excel 2010 not gaining focus correctly

    I am seeing this on my own workstation, but I'm being asked about it by more and more clients lately - Excel 2010 seems to have odd focus issues. For example:
    a) When opening an Excel spreadsheet from Windows Explorer, Excel opens, appears to have focus and does correctly open on top of other open windows, displays the file and I can edit cells, but I cannot click anything in the Ribbon bar or menus. In order
    to gain access to menu items I first have to lose focus (by clicking to another open application, the Task Bar or Desktop - anything that takes focus away from Excel) and then click back into Excel, whereupon the menu items now work correctly.
    b) If Excel is already open and I open another Excel file from Windows Explorer, the new window isn't brought forward - it remains behind the previously open spreadsheet. In addition, Excel isn't given focus at all in this situation - it is retained by Windows
    Explorer (which may or may not be open on the same screen as Excel, although it's more obvious if they overlap as Excel clearly remains behind the Explorer window). Additionally, if all existing spreadsheets are closed but Excel remains open and I open a spreadsheet
    from Explorer, the same behaviour occurs (ie Excel fails to gain focus and it is retained by Explorer).
    My personal workstation is running Windows 7 Pro x64 SP1 (this behaviour was evident before SP1's release) and Excel 2010 version 14.0.4760.1000 (32-bit). I have seen it occuring on other PCs using both 32- and 64-bit versions of Windows 7 Pro and Excel
    2010 (all 32-bit). While the workaround is relatively simple, it's still frustrating (and more than a little confusing for many non-technical people - one of my clients has been frustrated by this for weeks before I discovered she was experiencing the issue).
    I find it a little strange that I have been unable to find references to this problem anywhere (and I've been looking on-and-off for several months now). Maybe I'm just looking for the wrong things... Any help that can be provided will be greatly appreciated.
    Trevor Hardy

    I'm really not sure about the ethics of people being able to mark their own replies as accepted answers on here...
    Jennifer, thank you for attempting to assist with this problem. Unfortunately your suggestion doesn't alleviate the issue.
    As I thought I made clear in my first post, this issue is being seen when opening Excel spreadsheets directly from Explorer (or a desktop shortcut or similar, which is just an Explorer instance anyway) - it doesn't occur if you open files from within Excel.
    Therefore, opening Excel in Safe Mode has no effect - you can open one instance of Excel in safe mode, but when you open another Excel file from outside Excel, of course it opens another instance of Excel in normal mode and the same symptoms are evident.
    However, your suggestion regarding add-ins was a sensible one, so I manually removed the two Adobe Acrobat add-ins that were active on my workstation (the only add-ins installed) but unfortunately that hasn't made any difference. I should also point out
    that these add-ins aren't installed on the other PCs that are experiencing this issue, either, as they are used in wholly different environments.
    I'll be setting up Office 2010 on some new PCs in a couple of days, so I'll do some testing of those to see if I can replicate it on virgin systems.

  • JTextField not gaining focus on initialization of Applet

    I originally tried posting this in the Applets forum but was unable to get a response, so I am re-posting here in hopes of finding an answer.
    I have a simple JApplet with a JFrame, a JTextField added to the JFrame, and a WindowListener added to the JFrame that requests focus to the JTextField whenever the JFrame is activated. Upon opening the applet the WindowListener's windowActivated() method is called and requestFocusInWindow() for the JTextField returns true however the focus is never actually given to the JTextField. According to the API for Component,
    "This method returns a boolean value. If false is returned, the request is guaranteed to fail. If true is returned, the request will succeed unless it is vetoed, or an extraordinary event, such as disposal of the Component's peer, occurs before the request can be granted by the native windowing system. Again, while a return value of true indicates that the request is likely to succeed, developers must never assume that this Component is the focus owner until this Component receives a FOCUS_GAINED event"
    I am assuming that the request is getting "vetoed" but I don't understand why or what this even means. If I alt-tab off of the applet window and alt-tab back on then the request is handled properly. This issue only arises on initially opening the applet. Has anyone seen this issue before? Is there a known workaround? Here is the code for my sample applet:
    import javax.swing.*;
    import java.awt.event.*;
    public class MyApplet extends JApplet{
    private JFrame myFrame;
    private JTextField myTextField;
    private FrameWindowListener myListener;
    public void init(){
    myFrame = new JFrame();
    myFrame.setSize(700, 360);
    myFrame.setLocation(100, 100);
    myTextField = new JTextField();
    myFrame.add(myTextField);
    myListener = new FrameWindowListener();
    myFrame.addWindowListener(myListener);
    public void start(){
    myFrame.setVisible(true);
    myFrame.pack();
    public class FrameWindowListener extends WindowAdapter{
    public void windowActivated(WindowEvent e){
    boolean focus = myTextField.requestFocusInWindow();
    if(focus){
    System.out.println("Focus successful");
    } else{
    System.out.println("Focus unsuccessful");
    }

    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting
    Works fine for me using JDK1.4.2 on XP using appletviewer.
    The only suggestion I would make is that you should use pack() before setVisible(...). Also I usually have that code in the init() method instead of the start() method.

  • Bringto front, but while not gaining focus

    hi,
    I wish to create an aplication which runs in the background, and at pre-determined times apears at the front of the screen momentairily (ontop of any other programs running), and then goes to the back again.
    However, what i wish to know is: is it possible to do this, but yet allow whatever program had focus at that time, to keep that focus (for keyboard/ mouse/ and any other devices which might send information to the window with focus.)
    is this possible?
    is there a difrence between weather its possible on windows or on linux?
    hope someone can help.
    cheers
    james

    Not with out JNI.

  • JTextArea: Not thread safe

    I am working on a lobby system with a chat are using Networking, and recently I noticed that occasionally my JTextArea does not append the data I give it, even if I have a System.out.println() directly before which shows me what it is being passed, and it is being passed correct Strings, it is just not appending them.
        Thread updateText = new Thread() {
            public void run()
                for(;;)
                    try {
                        for (int x = 0; x < texts.size(); x++) {
                            System.out.println("ADDED: "+texts.get(x));
                            textArea.append(texts.get(x));
                        texts.clear();
                        scrollToEnd(textArea);
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        };I have an ArrayList texts, which keeps track of what is being typed into the Chat Area. This code displays correctly What I want it to, i.e. "ADDED: Hello guys, etc.", however the JTextArea does not update. Is there something to make the JTextArea thread-safe because I have heard on several sites that JTextAreas are not thread-safe.
    Any help would be greatly appreciated.

    I changed my code to this: and now it does not work at all, i.e., the JTextArea never updates:
        Thread updateText = new Thread() {
            public void run()
                for(;;)
                    try {
                        SwingUtilities.invokeAndWait(update);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InvocationTargetException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        Runnable update = new Runnable() {
            public void run()
                try {
                    texts.clear();
                    scrollToEnd(textArea);
                    for (int x = 0; x < texts.size(); x++) {
                        System.out.println("ADDED: " + texts.get(x));
                        textArea.append(texts.get(x));
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        };

  • JTextArea Not Readable By Jaws - Please Help

    Does anyone know why Jaws can't read the text displayed in a JTextArea. I've tried playing with different settings and properties but nothing sseems to work. The AccessibleText returned by the JTextArea is not null so according to the documentation, this means that JTextArea supports the interface and therefore should make its text accessible to screen readers.
    JAWS works fine for everything else it's just this one problem.
    Does anyone have a solution to this problem?

    Did you ever find a solution to this problem? If so, will you please post it. I am having a similar problem.

  • 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 :(

  • JtextArea not updating

    Hi I have a strange problem with appending text to a JTextArea.
    Basically I have a JinternalFrame with a table. When the user clicks on a particular row, I want that some of the data in that row to be displayed in a dialog which has a JTextArea included.
    here is part of the code of from the JinternalFrame that calls the Dialog
    private JTable getStatTable() {
         if (cTable == null) {
              cTable = new JTable(){
              private static final long serialVersionUID = 1L;
              public TableCellEditor getCellEditor(int row, int column)
                         if (column == 1 && !caseTableEditors.isEmpty())
                             return (TableCellEditor)caseTableEditors.get(row);
                         } else {
                                  return super.getCellEditor(row, column);
               cTable.setSize(new java.awt.Dimension(650,140));
               cTable.setMinimumSize(new java.awt.Dimension(650,140));
               cTable.setMaximumSize(new java.awt.Dimension(650,140));
               cTable.setShowGrid(true);
               cTable.setPreferredSize(new java.awt.Dimension(650,140));
                 cTable.setPreferredScrollableViewportSize(new java.awt.Dimension(650,140));
              cModel= new DefaultTableModel(20,2);
              cTable.setModel(caseModel);
              TableColumnModel cModel = cTable.getColumnModel();
              TableColumn ta=cModel.getColumn(0);
                  ta.setHeaderValue("ID");
                  ta.setPreferredWidth(100);
                  TableColumn tb = cModel.getColumn(1);
                  tb.setPreferredWidth(10);
                  tb.setHeaderValue("Value");
                 cTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                 if (ALLOW_ROW_SELECTION) { // true by default
                     ListSelectionModel rowSM = caseStatTable.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();
                                 displayRow(cTable.getValueAt(selectedRow,0));
                 } else {
                      cTable.setRowSelectionAllowed(false);
              return cTable;
         }the code of the displayRow method is below:
    public void displayRow(Object o){
              if(o instanceof  String){     
                   SDisplay sd=new SDisplay(this,(String)o);
                   sd.display();
         and below is the SDisplay Dialog class:
    public class SDisplay extends JDialog implements Runnable{
         private static final long serialVersionUID = 1L;
         private short selectedOption = -1;
         private JPanel jContentPane = null;
         private JPanel btnPnl = null;
         private JScrollPane displayPnl = null;
         private JTextArea cInfo = null;
         private JButton okBtn = null;
         private JButton cnlBtn = null;
         int x,y;
           String cr=null;
         public SDisplay(Frame owner, boolean modal) {
              super(owner);
              initialize();
           //PreviousClass is a user defined class that extends JInternalFrame
         public SDisplay(PreviousClass jp, String cr){
              x=jp.getLocationOnScreen().x;
              y=jp.getLocationOnScreen().y;
              this.cr=cr;
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(500, 400);
              this.setModal(true);
              this.setTitle("Display");
              this.setMaximumSize(new Dimension(500, 400));
              this.setMinimumSize(new Dimension(500, 400));
              this.setPreferredSize(new Dimension(500, 400));
              this.setLocation(x,y);
              this.setContentPane(getJContentPane());
              this.setVisible(true);
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
                   gridBagConstraints1.fill = GridBagConstraints.BOTH;
                   gridBagConstraints1.gridy = 0;
                   gridBagConstraints1.weightx = 1.0;
                   gridBagConstraints1.weighty = 1.0;
                   gridBagConstraints1.gridx = 0;
                   GridBagConstraints gridBagConstraints = new GridBagConstraints();
                   gridBagConstraints.gridx = 0;
                   gridBagConstraints.gridy = 1;
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new GridBagLayout());
                   jContentPane.setPreferredSize(new Dimension(500, 400));
                   jContentPane.setMaximumSize(new Dimension(500, 400));
                   jContentPane.setMinimumSize(new Dimension(500, 400));
                   jContentPane.add(getBtnPnl(), gridBagConstraints);
                   jContentPane.add(getDisplayPnl(), gridBagConstraints1);
              return jContentPane;
          * This method initializes btnPnl     
          * @return javax.swing.JPanel     
         private JPanel getBtnPnl() {
              if (btnPnl == null) {
                   try {
                        GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
                        gridBagConstraints3.gridx = 1;
                        gridBagConstraints3.insets = new Insets(0, 50, 0, 0);
                        gridBagConstraints3.gridy = 0;
                        GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
                        gridBagConstraints2.gridx = 0;
                        gridBagConstraints2.insets = new Insets(0, 0, 0, 50);
                        gridBagConstraints2.gridy = 0;
                        btnPnl = new JPanel();
                        btnPnl.setLayout(new GridBagLayout());
                        btnPnl.setMinimumSize(new Dimension(500, 50));
                        btnPnl.setMaximumSize(new Dimension(500, 50));
                        btnPnl.setPreferredSize(new Dimension(500, 50));
                        btnPnl.add(getOkBtn(), gridBagConstraints2);
                        btnPnl.add(getCnlBtn(), gridBagConstraints3);
                   } catch (java.lang.Throwable e) {
                        // TODO: Something
              return btnPnl;
          * This method initializes displayPnl     
          * @return javax.swing.JScrollPane     
         private JScrollPane getDisplayPnl() {
              if (displayPnl == null) {
                   try {
                        displayPnl = new JScrollPane();
                        displayPnl.setPreferredSize(new Dimension(500, 350));
                        displayPnl.setMaximumSize(new Dimension(500, 350));
                        displayPnl.setViewportView(getCInfo());
                        displayPnl.setMinimumSize(new Dimension(500, 350));
                   } catch (java.lang.Throwable e) {
                        // TODO: Something
              return displayPnl;
          * This method initializes cInfo     
          * @return javax.swing.JTextArea     
         private JTextArea getCInfo() {
              if (cInfo == null) {
                   try {
                        cInfo = new JTextArea();
                        cInfo.setSize(new Dimension(500, 350));
                        cInfo.setMaximumSize(new Dimension(500, 350));
                        cInfo.setPreferredSize(new Dimension(500, 350));
                        cInfo.setEditable(true);
                        cInfo.setLineWrap(true);
                        cInfo.setRows(100);
                        cInfo.setDoubleBuffered(true);
                        cInfo.setMinimumSize(new Dimension(500, 350));
                   } catch (java.lang.Throwable e) {
                        // TODO: Something
              return cInfo;
          * This method initializes okBtn     
          * @return javax.swing.JButton     
         private JButton getOkBtn() {
              if (okBtn == null) {
                   try {
                        okBtn = new JButton();
                        okBtn.setPreferredSize(new Dimension(70, 20));
                        okBtn.setMaximumSize(new Dimension(70, 20));
                        okBtn.setText("OK");
                        okBtn.setMinimumSize(new Dimension(70, 20));
                        okBtn.addActionListener(new ActionListener() {
                          public void actionPerformed(ActionEvent event) {
                              SDisplay.this.setVisible(false);
                   } catch (java.lang.Throwable e) {
                        // TODO: Something
              return okBtn;
          * This method initializes cnlBtn     
          * @return javax.swing.JButton     
         private JButton getCnlBtn() {
              if (cnlBtn == null) {
                   try {
                        cnlBtn = new JButton();
                        cnlBtn.setMinimumSize(new Dimension(70, 20));
                        cnlBtn.setPreferredSize(new Dimension(70, 20));
                        cnlBtn.setText("Close");
                        cnlBtn.setMaximumSize(new Dimension(70, 20));
                        cnlBtn.addActionListener(new ActionListener() {
                          public void actionPerformed(ActionEvent event) {
                              SDisplay.this.setVisible(false);
                   } catch (java.lang.Throwable e) {
                        // TODO: Something
              return cnlBtn;
         public void run(){
                    cInfo.append("String to append: "+cr);
              caseInfo.append("\n");
         public void display(){
              new Thread(this).start();
    }I implemented The SDisplay to use a Thread to append the text, so that appending is independent of any other process.
    When I execute this code, the jtextarea does not display any appended text. Can anyone explain what i am doing wrong?
    Regards

    Re-Hi,
    I have arranged a bit the code and here I provide a better/shorter working example:
    import javax.swing.UIManager;
    import java.awt.*;
    public class Main {
      boolean packFrame = false;
      //Construct the application
      public Main() {
        Display frame = new Display();
        //Validate frames that have preset sizes
        //Pack frames that have useful preferred size info, e.g. from their layout
        if (packFrame) {
          frame.pack();
        else {
          frame.validate();
        //Center the window
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if (frameSize.height > screenSize.height) {
          frameSize.height = screenSize.height;
        if (frameSize.width > screenSize.width) {
          frameSize.width = screenSize.width;
        frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
        frame.setVisible(true);
      //Main method
      public static void main(String[] args) {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch(Exception e) {
          e.printStackTrace();
        new Main();
    import javax.swing.JPanel;
    import java.awt.Frame;
    import java.awt.BorderLayout;
    import javax.swing.JDialog;
    import java.awt.Dimension;
    import java.awt.GridBagLayout;
    import javax.swing.JTextArea;
    import java.awt.GridBagConstraints;
    import javax.swing.JButton;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.Insets;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import java.util.*;
    public class Display extends JDialog implements Runnable{
            private static final long serialVersionUID = 1L;
            public static short ADD_OPTION = 0;
            public static short CANCEL_OPTION = 1;
            private short selectedOption = -1;
            private JPanel jContentPane = null;
            private JPanel btnPnl = null;
            private JScrollPane displayPnl = null;
            private JTextArea caseInfo = null;
            private JButton okBtn = null;
            private JButton cnlBtn = null;
            int x,y;
             * @param owner
            public Display(Frame owner, boolean modal) {
                    super(owner);
                    initialize();
            public Display(){
                    initialize();
             * This method initializes this
             * @return void
            private void initialize() {
                    this.setSize(500, 400);
                    this.setModal(true);
                    this.setTitle("Case Display");
                    this.setLocation(x,y);
                    this.setContentPane(getJContentPane());
                    //this.setVisible(true);
             * This method initializes jContentPane
             * @return javax.swing.JPanel
            private JPanel getJContentPane() {
                    if (jContentPane == null) {
                            GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
                            gridBagConstraints1.fill = GridBagConstraints.BOTH;
                            gridBagConstraints1.gridy = 0;
                            gridBagConstraints1.weightx = 1.0;
                            gridBagConstraints1.weighty = 1.0;
                            gridBagConstraints1.gridx = 0;
                            GridBagConstraints gridBagConstraints = new GridBagConstraints();
                            gridBagConstraints.gridx = 0;
                            gridBagConstraints.gridy = 1;
                            jContentPane = new JPanel();
                            jContentPane.setLayout(new GridBagLayout());
                            jContentPane.setPreferredSize(new Dimension(500, 400));
                            jContentPane.setMaximumSize(new Dimension(500, 400));
                            jContentPane.setMinimumSize(new Dimension(500, 400));
                            jContentPane.add(getBtnPnl(), gridBagConstraints);
                            jContentPane.add(getDisplayPnl(), gridBagConstraints1);
                    return jContentPane;
             * This method initializes btnPnl
             * @return javax.swing.JPanel
            private JPanel getBtnPnl() {
                    if (btnPnl == null) {
                            try {
                                    GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
                                    gridBagConstraints3.gridx = 1;
                                    gridBagConstraints3.insets = new Insets(0, 50, 0, 0);
                                    gridBagConstraints3.gridy = 0;
                                    GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
                                    gridBagConstraints2.gridx = 0;
                                    gridBagConstraints2.insets = new Insets(0, 0, 0, 50);
                                    gridBagConstraints2.gridy = 0;
                                    btnPnl = new JPanel();
                                    btnPnl.setLayout(new GridBagLayout());
                                    btnPnl.setMinimumSize(new Dimension(500, 50));
                                    btnPnl.setMaximumSize(new Dimension(500, 50));
                                    btnPnl.setPreferredSize(new Dimension(500, 50));
                                    btnPnl.add(getOkBtn(), gridBagConstraints2);
                                    btnPnl.add(getCnlBtn(), gridBagConstraints3);
                            } catch (java.lang.Throwable e) {
                                    // TODO: Something
                    return btnPnl;
             * This method initializes displayPnl
             * @return javax.swing.JScrollPane
            private JScrollPane getDisplayPnl() {
                    if (displayPnl == null) {
                            try {
                                    displayPnl = new JScrollPane();
                                    displayPnl.setPreferredSize(new Dimension(500, 350));
                                    displayPnl.setMaximumSize(new Dimension(500, 350));
                                    displayPnl.setViewportView(getCaseInfo());
                                    displayPnl.setMinimumSize(new Dimension(500, 350));
                            } catch (java.lang.Throwable e) {
                                    // TODO: Something
                    return displayPnl;
             * This method initializes caseInfo
             * @return javax.swing.JTextArea
            private JTextArea getCaseInfo() {
                    if (caseInfo == null) {
                            try {
                                    caseInfo = new JTextArea();
                                    caseInfo.setSize(new Dimension(500, 350));
                                    caseInfo.setMaximumSize(new Dimension(500, 350));
                                    caseInfo.setPreferredSize(new Dimension(500, 350));
                                    caseInfo.setEditable(true);
                                    caseInfo.setLineWrap(true);
                                    caseInfo.setRows(100);
                                    caseInfo.setDoubleBuffered(true);
                                    caseInfo.setMinimumSize(new Dimension(500, 350));
                            } catch (java.lang.Throwable e) {
                                    // TODO: Something
                    return caseInfo;
             * This method initializes okBtn
             * @return javax.swing.JButton
            private JButton getOkBtn() {
                    if (okBtn == null) {
                            try {
                                    okBtn = new JButton();
                                    okBtn.setPreferredSize(new Dimension(70, 20));
                                    okBtn.setMaximumSize(new Dimension(70, 20));
                                    okBtn.setText("OK");
                                    okBtn.setMinimumSize(new Dimension(70, 20));
                                    okBtn.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent event) {
                                    Display.this.setVisible(false);
                                    Display.this.dispose();
                            } catch (java.lang.Throwable e) {
                                    // TODO: Something
                    return okBtn;
             * This method initializes cnlBtn
             * @return javax.swing.JButton
            private JButton getCnlBtn() {
                    if (cnlBtn == null) {
                            try {
                                    cnlBtn = new JButton();
                                    cnlBtn.setMinimumSize(new Dimension(70, 20));
                                    cnlBtn.setPreferredSize(new Dimension(70, 20));
                                    cnlBtn.setText("Close");
                                    cnlBtn.setMaximumSize(new Dimension(70, 20));
                                    cnlBtn.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent event) {
                                    Display.this.setVisible(false);
                                     Display.this.dispose();
                            } catch (java.lang.Throwable e) {
                                    // TODO: Something
                    return cnlBtn;
            public void run(){
                caseInfo.append("ID: ");
                    caseInfo.append("\n");
                    caseInfo.append("Value: ");
                    caseInfo.append("\n");
                    caseInfo.append("New ID: ");
                    caseInfo.append("\n");
            public void display(){
                    new Thread(this).start();
    }The append still does not seem to be working here...
    thanks

  • JTextArea not working

    hi, I have a problem whereby the text area does not append the sentence "File not available" when there's no filename "myfile.pps" in the "f " drive folder. can i know what's wrong with the code i did below?
    public void create() {
    final JTextArea ta = new JTextArea(10,20);
    ta.append("Searching USB disk drive\n\n");
    final File f = new File("F://");
    String filename = "f:\\myfile.pps";
    if(f.exists()) {
    ta.append("Drive inserted!\n");
    try {
    Runtime.getRuntime().exec(new String[] {"cmd", "/c", "start", "f:\\myfile.pps"});
    catch (Exception x) {
    x.printStackTrace();
    catch (Error r) {
    e.printStackTrace();
    if(filename!="f:\\myfile.pps") {
    ta.append("File not available!\n");
    else {
    ta.append("Detection failed!\n");
    }thanks alot,
    jp

    Are you updating/repainting/revalidating/whatever (why not ask in the Swing forum?) the component after the chainge?

  • JTextArea not scrolling

    Hi everyone,
    I have looked at many of teh posts in this forum and have yet to find an answer that seems to work for me. My problem if that i have a JTextArea that is in a JScrollPane, but as things are added to the JTextArea via the append() method, it does not scroll once tthe viewable window if full. here is some of teh code which builds the panel which contains it :
    private void buildChatPanel(){
          chatPanel=new JPanel();
          JTextField outbox = new JTextField(20);
          JButton sendButton = new JButton("Send");
          inbox = new JTextArea();
          chatPanel.setLayout(new GridBagLayout());
          //chatPanel.setBackground(Color.BLACK);
          GridBagConstraints gbc = new GridBagConstraints();
          // Build the text input field
            setBackground(new java.awt.Color(51, 51, 51));
            outbox.setText("Enter Chat");
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = 3;
            gbc.ipadx = 14;
            gbc.insets = new Insets(3, 3, 3, 3);
            chatPanel.add(outbox, gbc);
            //build the send button      
            sendButton.setToolTipText("Click to send chat message");
            sendButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
            sendButton.setPreferredSize(new Dimension(75, 25));
            sendButton.setRolloverEnabled(true);
            gbc = new java.awt.GridBagConstraints();
            gbc.gridx = 2;
            gbc.gridy = 2;
            gbc.insets = new Insets(3, 3, 3, 3);
            chatPanel.add(sendButton, gbc);
            //build the text area
            inbox.setEditable(false);
            inbox.setPreferredSize(new Dimension(200, 20));
            inbox.setLineWrap(true);
            inbox.setWrapStyleWord(true);
            gbc = new java.awt.GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 4;
            gbc.gridwidth = 3;
            gbc.ipadx = -20;
            gbc.ipady = 493;
            gbc.insets = new Insets(3, 3, 3, 3);
            JScrollPane jsp = new JScrollPane(inbox,
                            ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            chatPanel.add(jsp, gbc);
      }I tried to used inbox.setCaretPosition(inbox.getText().getLength()) right after any call to the append() method, but that did nto seem to work either. Any Ideas at all would be great!
    THANK YOU ALL!!

    I don't know if you ever figure out what was causing this. But I came across the same problem. The IDE that I was using had auto generated the following two lines in my source code:
    jTextArea1.setMinimumSize(new Dimension(70, 70));
    jTextArea1.setPreferredSize(new Dimension(70, 70));
    I commented out both of these and the jTextArea began to scroll both vertically and horizontally.
    Good Luck,

  • JTextArea not showing

    I can get my first set of JScrollPane and JTextArea to appear, but the second just will not. Here is all my code refering to the frame. I hope you can find what I cannot.
            public Frame(){
                Object[] items={"Choose One","1","2","3","4","5","6","7","8","9","10"};
                JPanel c=(JPanel)getContentPane();
                JOptionPane jOpt=new JOptionPane();
                ImageIcon icon=new ImageIcon();
                jArea=new JTextArea();
                JScrollPane jScroll=new JScrollPane(jArea);
                jArea2=new JTextArea();
                JScrollPane jScroll2=new JScrollPane(jArea2);
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                setSize(new Dimension(250, 500));
                setTitle("Towers Of Hanoi");
                //setResizable(false);
                setLocationRelativeTo(null);
                jScroll.setPreferredSize(new Dimension(125, 500));
                jScroll.setPreferredSize(new Dimension(125,500));
                jScroll.setViewportView(jArea);
                jScroll2.setViewportView(jArea2);
                c.setLayout(new BorderLayout());
                c.add(jOpt);
                jOpt.setVisible(false);
                c.add(jScroll, java.awt.BorderLayout.WEST);
                c.add(jScroll2, java.awt.BorderLayout.EAST);
                jScroll2.setVisible(true);
                boolean done=false;
                String s="";
                while(done==false){
                    s=(String)jOpt.showInputDialog(this,"How many disks should be used?","",jOpt.PLAIN_MESSAGE,icon,items,"Choose One");
                    if(!s.equals("Choose One"))
                        done=true;
                height=Integer.parseInt(s);
                show();
            }//Close Frame Constructor

    maybe
    setLocationRelativeTo(null);
    jScroll.setPreferredSize(new Dimension(125, 500));
    jScroll.setPreferredSize(new Dimension(125,500));//should be jScroll2.setPreferredSize(...)
    jScroll.setViewportView(jArea);

Maybe you are looking for

  • Stuck with a horrible phone

    I started a contract with Verizon on the 25th of June, and was told I had two weeks to return the device for an exchange. My Droid 2 is constantly freezing, rebooting, and will stop recieving calls and texts. So when I show up 2 weeks later, they tel

  • Hp webcam

    Hello, i have the laptop hp dv7 310 ev and i dont have warranty, i have a problem with my camera. Suddenly when it working at skype or at something webcam program it stop and you hear the noise of windows when you unplug and plug a usb device and the

  • I cant update message says i dont own major version

    I have a brand new imac and the app store says I need to update iPhoto.  When I try to do so, I get a message that says "you cannot update this software because you have not owned a major version of this software".  I tried logging back in but get th

  • Using the functional methods with workflows

    Hi All, I'm passing the plant number to a workflow by triggering an event in a user-exit. The workflow uses a functional method of an ABAP class and retrives the plant details. While binding the functional method back to the workflow, the binding inc

  • App will not install on iPhone 4S

    Hi, I try to install an app from App store, and it only shows a big cloud, as if it's in iCloud. However, when I push the iCloud button to download it, nothing happens. I have iOs 8.1.2 installed.