JTextArea setLocation problem?

The JTextArea setLocation method is not sticking after the call to repaint(). The JTextArea is going back to it's original location; the repaint() method is acting like the pack() method.
I've written a test application to show what I'm talking about. (The test Application is in two files.)
The following program draws a circle and has 5 JTextAreas, you can drag the text areas anywhere on the screen. On the repaint() method call the text areas get reset to their original positions. If you remark the repaint() calls out the text areas stay where you place them. Try to place one of the text areas over the circle with and without the repaint calls commented out, the circle gets erased. This is why I need to call repaint.
This behavior only occurs if the following program is an application. The setLocation method works fine if this is placed in an Applet. This behavior was discovered when I tried to make my Applet an Application. If anyone can provide a work around I'd appreciate it.
Thanks,
Andrew
package test;
import java.awt.Toolkit;
import javax.swing.*;
import javax.swing.UIManager;
import java.awt.Dimension;
public class Test {
boolean packFrame = false;
public static void main(String[] args) {
JFrame frame = new Frame1();
frame.setTitle("Application");
frame.setSize(600, 550);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation( (d.width - frame.getSize().width) / 2,
(d.height - frame.getSize().height) / 2);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
frame.setResizable(false);
---------------------New File---------------------------
package test;
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import javax.swing.border.LineBorder;
public class Frame1
extends JFrame implements MouseMotionListener {
Image aFrame = null;
JPanel contentPane;
BorderLayout borderLayout1 = new BorderLayout();
JLabel statusBar = new JLabel();
JTextArea[] display = null;
JPanel centerPanel = null;
JPanel moviePanel = null;
public Frame1() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
catch (Exception exception) {
exception.printStackTrace();
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(borderLayout1);
setSize(new Dimension(400, 300));
setTitle("Frame Title");
statusBar.setText(" ");
contentPane.add(statusBar, BorderLayout.SOUTH);
centerPanel = new JPanel(new BorderLayout());
moviePanel = new JPanel(new GridBagLayout());
display = new JTextArea[5];
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx=gbc.RELATIVE;
gbc.gridy=gbc.RELATIVE;
for (int i=0; i < display.length; i++) {
display[i] = new JTextArea(" ",3,15);
moviePanel.add(display, gbc);
display[i].setBorder(new LineBorder(Color.lightGray));
display[i].addMouseMotionListener(this);
centerPanel.add(moviePanel, BorderLayout.CENTER);
contentPane.add(centerPanel, BorderLayout.CENTER);
moviePanel.addMouseMotionListener(this);
centerPanel.addMouseMotionListener(this);
contentPane.addMouseMotionListener(this);
public void update(Graphics g) {
paint(g);
public void paint(Graphics g) {
for (int i=0; i < display.length; i++) {
display[i].setText("i: "+Integer.toString(i));
Graphics2D offscreenG = ((Graphics2D)moviePanel.getGraphics());
int w = centerPanel.getWidth();
int h = centerPanel.getHeight();
background(w,h);
offscreenG.drawImage(aFrame,0,0,this);
public void background(int width, int height) {
aFrame = createImage(width, height);
Graphics2D aFrameG = ((Graphics2D) aFrame.getGraphics());
aFrameG.setColor(Color.cyan);
aFrameG.fillOval(5,5,width/2,height/2);
public void mouseDragged(MouseEvent e) {
if (e.getSource() instanceof JTextArea) {
JTextArea temp = ((JTextArea)e.getSource());
int x = e.getX();
int y = e.getY();
((JTextArea)e.getSource()).setLocation(temp.getX() + x, temp.getY() + y);
repaint(); // Remark me out
public void mouseMoved(MouseEvent e) {
repaint(); // Remark me out

Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.
Well, the basic answer is that Swing is different than AWT so you need to learn how to code using Swing. Start by reading the [Swing tutorial|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html] for examples and explanations.
a) the setLocation doesn't work, because the Layout Manager overrides that value based on the rules of the layout manager. This is a good thing. You should always use layout managers and not set the location manually. The tutorial gives examples of using a layout manager.
b) don't override the update() method in Swing, that is an old AWT trick
c) don't override the paint() method of the frame. Custom painting, if required, is done by overriding the paintComponent() method. Again the tutorial gives an example.
If you are tying to add an image to the background of the frame then there are better ways to do it. Search the forum using "background-image" (without the "-") to find postings on this topic.

Similar Messages

  • JTextArea append problem

    I have the following problem:
    I am creating a JFrame with a JTextArea in it.
    After all components are added to the JFrame
    I call:
    setLocation(100, 100);
    pack();
    setVisible(true);
    Then a method is called that generates files and uses
    jTextArea.append(".");
    to add a "." to the JTextArea for each created file
    to show the progress.
    Now the problem is that the dots are not shown one after the other.
    The window pops up AFTER all the dots are written and not when
    setVisible(true);
    is called.
    What do I have to do that every single dot is shown in the
    JTextArea right after it is appended ?

    Move your actual file generating process to a different thread. The best way to do it is using SwingWorker. There is a tutorial on the Sun's web site at http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html that demonstrates how to use SwingWorker.
    Hope this helps
    Sai Pullabhotla

  • JDialog setLocation problem

    Hi,
    I am stuck in very weird problem:
    I have an Jinternal frame that invokes a non-modal Jdialog box.
    I need to set the location of the dialog box from my code.
    The setLocation takes effect until I drag my window to a new location with my mouse.
    Any calls to setLocation after dragging fails. I see that the dialog box is temporarily drawn at the new position but it quickly moves back to its last known position.(I can see a sort of flicker...)
    I tried SetBounds, reshape also - same behaviour...
    I am so puzzled.
    Any help will be appreciated.

    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.

  • JTextArea scrolling problem

    Hello!
    I have a JTextArea inside a JScrollPane and i'm sending it lots of text that makes the scrollbars appear when it stops fitting the JTextArea. The thing is the scrollbars don't scroll along with the text, and instead stay put on top of the JTA. If I go to the end of the JTA and hit [ENTER] it starts scrolling beautifuly from that point on. So I always send "\n" at the end of the text to make it scroll. But it doesn't do the trick...
    Is there something i can do to get it going? I've looked at the API but I didn't find anything that solved the problem...
    Thank you very much for your help!

    As you said when u pressed ENTER it scrolls, its mean there is no problem with your JTextArea. Actually, when your Application Executes JTextArea in it, appears without the scrollbars(hor,ver) until you enter text in it at runtime. There is no problem, so work with it .

  • JTextArea Wraping problem!

    Hi, i am using a JTextArea do display diferent length text, this text area is inside a JSplitPane, my problem is that when the text is too wide, the JTextArea does not divide the text in lines, this way, only a part of the text is visible.
    There is a solution, invoke the setLineWrap(TRUE) method, it seems good, but it does not work for me, when i envoke this method the text is not shown......crazy
    anyone....
    thanks

    Try placing the JTextArea inside a JScrollPane

  • JFrame setlocation problems on linux

    When you drag a JFrame, you can move it anywhere you want, even if some of its boundary goes outside the screen...
    Fortunately It's true on windows, mac and linux SUN JREs.
    On windows and mac, you get the same effect if you decide to do it programatically with for example :
    package testframe;
    import javax.swing.JFrame;
    public class Main {
        public static void main(String[] args) {
        JFrame jf=new JFrame();
        jf.setVisible(true);
        jf.setSize(400, 400);
        jf.setLocation(-300, 50);
    }But this code doesn't work as expected on linux distros. I tried on kde, gnome and xfce, and I always get the same problem : the JRE (probably because of calls to window manager) refuses to place the window a little bit outside the screen boundaries. So in my example, jf.setLocation(-300,50) have the same effect as jf.setLocation(0,50).
    Of course, when the windows appear at the (0,50) coordinates, it's always possible on linux to move it manually to a negative x-coordinate place.
    setBounds method will lead to the same trouble...
    Of course this piece of code is only here to show exactly what's wrong on linux sun jre's. In my "real code", I need to deal with undecorated Jframes, so I have to manage myself the mousepressed and mousedragged events on my custom titlebar, and I would really want the linux version of my application behave the same as windows and mac versions ...
    The weird thing is that if I try to do that with JWindows in place of JFrames, it work's fine on Linux as well. But the problem is not here : in my case I need JFrames...
    Anyone knows how to fix this on linux ?

    When you drag a JFrame, you can move it anywhere you want, even if some of its boundary goes outside the screen...
    Fortunately It's true on windows, mac and linux SUN JREs.
    On windows and mac, you get the same effect if you decide to do it programatically with for example :
    package testframe;
    import javax.swing.JFrame;
    public class Main {
        public static void main(String[] args) {
        JFrame jf=new JFrame();
        jf.setVisible(true);
        jf.setSize(400, 400);
        jf.setLocation(-300, 50);
    }But this code doesn't work as expected on linux distros. I tried on kde, gnome and xfce, and I always get the same problem : the JRE (probably because of calls to window manager) refuses to place the window a little bit outside the screen boundaries. So in my example, jf.setLocation(-300,50) have the same effect as jf.setLocation(0,50).
    Of course, when the windows appear at the (0,50) coordinates, it's always possible on linux to move it manually to a negative x-coordinate place.
    setBounds method will lead to the same trouble...
    Of course this piece of code is only here to show exactly what's wrong on linux sun jre's. In my "real code", I need to deal with undecorated Jframes, so I have to manage myself the mousepressed and mousedragged events on my custom titlebar, and I would really want the linux version of my application behave the same as windows and mac versions ...
    The weird thing is that if I try to do that with JWindows in place of JFrames, it work's fine on Linux as well. But the problem is not here : in my case I need JFrames...
    Anyone knows how to fix this on linux ?

  • JTextArea.getSelectedText Problem

    hello
    i need to capture a line from a jtext area with a double-click.
    im using getSelectedText whenever someone double-clicks on some text.
    the problem is that the double-click only selects one word of the line.
    can anyone help me?
    thanks

    Swing releated questions should be posted in the Swing forum.
    Check out my example in this posting:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=605026
    If currently selects the line on a single mouse click but that is easily changed.

  • ActionListener / JTextArea Update Problem

    I have a JFrame that implements ActionListener, and the actionPerformed method looks like so:
    public void actionPerformed(ActionEvent myEvent){
         if ("abc".equals(myEvent.getActionCommand()) {
              //new window is created, etc
         } else if ("def".equals(myEvent.getActionCommand()) {
              //new window is created, etc
         someJTextArea.setText(newText);
         repaint();
    }The problem is, the newText relies on the other windows for its content, but for some unknown reason setText() is called before the new windows are closed, and also before newText has been set. I have a feeling this has something to do with the new windows launching their own threads, but I'm lost on how to wait for those windows to close before setting the text.
    Thanks for any help.

    I don't think that it's an issue of new threads being produced, since Swing GUIs and all actionPerformed code gets called on one thread, the EDT.
    More importantly to me: what exactly are your "new window"s? JFrames? If so, they likely need to be modal JDialogs. This will stop execution of any further method calls in your actionPerformed method until the dialogs have been fully dealt with.

  • JTextArea - Tab problem

    When I'm in the text area when I press Tab key it's inserted into the text area but I want it to go to the next focusable component. Could you help? How do I do it?

    I incorporated a more generic solution of Michaels suggestion with some other examples I have found:
        This is my understanding of how tabbing works. The focus manager
        recognizes the following default KeyStrokes for tabbing:
        forwards:  TAB or Ctrl-TAB
        backwards: Shift-TAB or Ctrl-Shift-TAB
        In the case of JTextArea, TAB and Shift-TAB have been removed from
        the defaults which means the KeyStroke is passed to the text area.
        The TAB KeyStroke inserts a tab into the Document. Shift-TAB seems
        to be ignored.
        This example shows different approaches for tabbing out of a JTextArea
        Also, a text area is typically added to a scroll pane. So when
        tabbing forward the vertical scroll bar would get focus by default.
        Each approach shows how to prevent the scrollbar from getting focus.
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextAreaTab extends JFrame
        public TextAreaTab()
            Container contentPane = getContentPane();
            contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
            contentPane.add( nullTraversalKeys() );
            contentPane.add( writeYourOwnAction() );
            contentPane.add( useKeyListener() );
            contentPane.add( addTraversalKeys() );
        //  Reset the text area to use the default tab keys.
        //  This is probably the best solution.
        private JComponent nullTraversalKeys()
            JTextArea textArea = new JTextArea(3, 30);
            textArea.setText("Null Traversal Keys\n2\n3\n4\n5\n6\n7\n8\n9");
            JScrollPane scrollPane = new JScrollPane( textArea );
            scrollPane.getVerticalScrollBar().setFocusable(false);
            textArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
            textArea.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
            return scrollPane;
        //  Replace the Tab Actions. A little more complicated but this is the
        //  only solution that will place focus on the component, not the
        //  vertical scroll bar, when tabbing backwards (unless of course you
        //  have manually prevented the scroll bar from getting focus).
        private JComponent writeYourOwnAction()
            JTextArea textArea = new JTextArea(3, 30);
            textArea.setText("Write Your Own Tab Actions\n2\n3\n4\n5\n6\n7\n8\n9");
            JScrollPane scrollPane = new JScrollPane( textArea );
            InputMap im = textArea.getInputMap();
            KeyStroke tab = KeyStroke.getKeyStroke("TAB");
            textArea.getActionMap().put(im.get(tab), new TabAction(true));
            KeyStroke shiftTab = KeyStroke.getKeyStroke("shift TAB");
            im.put(shiftTab, shiftTab);
            textArea.getActionMap().put(im.get(shiftTab), new TabAction(false));
            return scrollPane;
        //  Use a KeyListener
        private JComponent useKeyListener()
            JTextArea textArea = new JTextArea(3, 30);
            textArea.setText("Use Key Listener\n2\n3\n4\n5\n6\n7\n8\n9");
            JScrollPane scrollPane = new JScrollPane( textArea );
            scrollPane.getVerticalScrollBar().setFocusable(false);
            textArea.addKeyListener(new KeyAdapter()
                public void keyPressed(KeyEvent e)
                    if (e.getKeyCode() == KeyEvent.VK_TAB)
                        e.consume();
                        KeyboardFocusManager.
                            getCurrentKeyboardFocusManager().focusNextComponent();
                    if (e.getKeyCode() == KeyEvent.VK_TAB
                    &&  e.isShiftDown())
                        e.consume();
                        KeyboardFocusManager.
                            getCurrentKeyboardFocusManager().focusPreviousComponent();
            return scrollPane;
        //  Add Tab and Shift-Tab KeyStrokes back as focus traversal keys.
        //  Seems more complicated then just using null, but at least
        //  it shows how to add a KeyStroke as a focus traversal key.
        private JComponent addTraversalKeys()
            JTextArea textArea = new JTextArea(3, 30);
            textArea.setText("Add Traversal Keys\n2\n3\n4\n5\n6\n7\n8\n9");
            JScrollPane scrollPane = new JScrollPane( textArea );
            scrollPane.getVerticalScrollBar().setFocusable(false);
            Set set = new HashSet( textArea.getFocusTraversalKeys(
                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS ) );
            set.add( KeyStroke.getKeyStroke( "TAB" ) );
            textArea.setFocusTraversalKeys(
                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set );
            set = new HashSet( textArea.getFocusTraversalKeys(
                KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS ) );
            set.add( KeyStroke.getKeyStroke( "shift TAB" ) );
            textArea.setFocusTraversalKeys(
                KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set );
            return scrollPane;
        class TabAction extends AbstractAction
            private boolean forward;
            public TabAction(boolean forward)
                this.forward = forward;
            public void actionPerformed(ActionEvent e)
                if (forward)
                    tabForward();
                else
                    tabBackward();
            private void tabForward()
                final KeyboardFocusManager manager =
                    KeyboardFocusManager.getCurrentKeyboardFocusManager();
                manager.focusNextComponent();
                SwingUtilities.invokeLater(new Runnable()
                    public void run()
                        if (manager.getFocusOwner() instanceof JScrollBar)
                            manager.focusNextComponent();
            private void tabBackward()
                final KeyboardFocusManager manager =
                    KeyboardFocusManager.getCurrentKeyboardFocusManager();
                manager.focusPreviousComponent();
                SwingUtilities.invokeLater(new Runnable()
                    public void run()
                        if (manager.getFocusOwner() instanceof JScrollBar)
                            manager.focusPreviousComponent();
        public static void main(String[] args)
            TextAreaTab frame = new TextAreaTab();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • JTextArea display problem

    Hi,
    When I use a JtextArea , and set it s row to a number, say 2. Howver, I also use lineWrap, that is if a string is too long, then JTextArea will wrap it to the next line.
    But then the displaying line numbers are bigger than the row numbers of the textArea, therefore, some of the text at bottom are missing.
    Could anyone come up with an idea to solve this?
    Thanks in advance

    Maybe this will help you. My idea is : use JTable's method setRowHeight( row,rowHeight ) in order to adapt the cell-size when the text to be displayed is to long to fit into the cell.
            int height = getHeight( table, text, row, column );
            if( height > 0 ){
                table.setRowHeight( row, height );
        private int getHeight( JTable table, String text, int row , int column){
            FontMetrics fm = table.getFontMetrics(getFont());
            int numberOfTextRows = 2;
            int textWidth=0;
            if( fm != null ){
                textWidth = fm.stringWidth(text);
            if( textWidth > 0 ){
                TableColumn tableColumn = table.getColumnModel().getColumn(column);
                numberOfTextRows = ( textWidth / tableColumn.getWidth() + 1 );
            int rowHeight = MINIMAL_ROW_HEIGHT * numberOfTextRows;
            if( rowHeight > table.getRowHeight(row) ){
                return rowHeight;
            return 0;
        final static private int MINIMAL_ROW_HEIGHT = 16;

  • JTextArea output problem

    When i create a text file and then open it back up with the below applcation,
    i get little squares appended to the end of the text.
    the application
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class FileIO extends JFrame implements ActionListener
         JButton btn_open;
         JButton btn_save;
         JButton btn_clear;
         JTextField file_path;
         JTextArea stuff;
          ///  Edited for size  ///
         //Methods
         private void Read_File()
              File input = new File(file_path.getText());
              FileReader reader;
              JDialog msg;
              char[] lines = new char[80];
              try {
                   reader = new FileReader(input);
                   while(reader.read(lines) != -1)
                        stuff.append(new String(lines));
                   reader.close();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE NOT FOUND ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);     
              } catch (IOException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE IO ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);
         private void Write_File()
              File output = new File(file_path.getText());
              FileWriter w;
              JDialog msg;
              try {
                   w = new FileWriter(output);
                   stuff.write(w);
                   w.close();
              } catch (IOException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE IO ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);
         //ActionListener
         public void actionPerformed(ActionEvent evt)
              Object source = evt.getSource();
              if(source == btn_open)
                   Read_File();
              else if(source == btn_save)
                   Write_File();
              else if(source == btn_clear)
                   stuff.setText("");
            ///  Edited for size  ///
    }

    using sun-jdk 1.6.0.20 on Gentoo 32 bit
    source code:(copy/paste/run)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class FileIO extends JFrame implements ActionListener
         JButton btn_open;
         JButton btn_save;
         JButton btn_clear;
         JTextField file_path;
         JTextArea stuff;
         public FileIO()
              super("FILE IO Example");
              setSize(300, 300);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              GridBagLayout bag_layout = new GridBagLayout();
              setLayout(bag_layout);
              GridBagConstraints c = new GridBagConstraints();
              //TextField file_path
              file_path = new JTextField(40);
              c.fill = GridBagConstraints.HORIZONTAL;
              c.gridx = 0;
              c.gridwidth = 4;
              c.gridy = 0;
              c.gridheight = 1;
              c.weightx = 1.0;
              add(file_path, c);
              //TextArea stuff and JScrollPane scroll
              stuff = new JTextArea(40, 40);
              JScrollPane scroll = new JScrollPane(stuff,
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              c.fill = GridBagConstraints.BOTH;
              c.gridy++;
              c.gridheight = 4;
              c.weighty = 1.0;
              add(scroll, c);
              //JButton btn_open
              btn_open = new JButton("Open File");
              btn_open.addActionListener(this);
              c.fill = GridBagConstraints.HORIZONTAL;
              c.gridy = 5;
              c.gridheight = 1;
              c.gridwidth = 1;
              c.weightx = 1.0;
              c.weighty = 0.0;
              add(btn_open, c);
              //JButton btn_save
              btn_save = new JButton("Save File");
              btn_save.addActionListener(this);
              c.gridx++;
              add(btn_save, c);
              //JButton btn_clear
              btn_clear = new JButton("Clear");
              btn_clear.addActionListener(this);
              c.gridx++;
              add(btn_clear, c);
              setVisible(true);
         //Methods
         private void Read_File()
              File input = new File(file_path.getText());
              FileReader reader;
              JDialog msg;
              char[] lines = new char[80];
              try {
                   reader = new FileReader(input);
                   while(reader.read(lines) != -1)
                        stuff.append(new String(lines));
                   reader.close();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE NOT FOUND ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);     
              } catch (IOException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE IO ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);
         private void Write_File()
              File output = new File(file_path.getText());
              FileWriter w;
              JDialog msg;
              try {
                   w = new FileWriter(output);
                   stuff.write(w);
                   w.close();
              } catch (IOException e) {
                   e.printStackTrace();
                   msg = new JOptionPane("FILE IO ERROR", JOptionPane.ERROR_MESSAGE,
                             JOptionPane.DEFAULT_OPTION).createDialog("ERROR_MESSAGE");
                   msg.setVisible(true);
         //ActionListener
         public void actionPerformed(ActionEvent evt)
              Object source = evt.getSource();
              if(source == btn_open)
                   Read_File();
              else if(source == btn_save)
                   Write_File();
              else if(source == btn_clear)
                   stuff.setText("");
         //Main
         public static void main(String[] args)
              new FileIO();
    }the appended nonprintable characters show up as little squares in the JTextArea, but they do not show up in any file editors on my computer.
    Edited by: grimx on Jul 3, 2010 7:24 PM
    Edited by: grimx on Jul 3, 2010 7:31 PM

  • Settting JTextArea size problem

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Menu implements ActionListener {
         // **************Constants**************
         private static final int WIDTH = 700;
         private static final int HEIGHT = 700;
         // **************Instance Variables*********
         Dimension scoreSize = new Dimension(3, 4);
         Dimension ratingSize = new Dimension(4, 4);
         Dimension slopeSize = new Dimension(3, 4);
         Dimension dateSize = new Dimension(8, 4);
         Dimension courseSize = new Dimension(15, 4);
         JTextField[] scores = new JTextField[20];
         JTextField[] ratings = new JTextField[20];
         JTextField[] slopes = new JTextField[20];
         JTextField[] dates = new JTextField[20];
         JTextField[] courses = new JTextField[20];
         JLabel[] numberLabel = new JLabel[20];
         JFrame window = new JFrame("USGA Index Calculator");
         JPanel grid = new JPanel(new GridLayout(0, 5, 5, 5));
         JPanel label = new JPanel(new GridLayout(0, 5));
         JPanel numbers = new JPanel(new GridLayout(0, 1));
         JPanel index = new JPanel(new FlowLayout());
         JLabel scoreLabel = new JLabel("Score");
         JLabel slopeLabel = new JLabel("Slope");
         JLabel ratingLabel = new JLabel("Rating");
         JLabel dateLabel = new JLabel("Date");
         JLabel courseLabel = new JLabel("Course Name/Description");
         JLabel indexLabel = new JLabel("Current Index:");
         JTextField Index = new JTextField();
         // **************Constructors**************
         public Menu(Golfer g) {
              Golfer golfer = g;
              viewGrid(golfer);
              window.setSize(WIDTH, HEIGHT);
              window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              window.setLayout(new BorderLayout());
              // Add JTextFields to 'grid' JPanel
              for (int i = 0; i < 20; i++) {
                   grid.add(scores);
                   grid.add(ratings[i]);
                   grid.add(slopes[i]);
                   grid.add(dates[i]);
                   grid.add(courses[i]);
              // Add JLabels to 'number' JLabel
              for (int i = 0; i < 20; i++) {
                   numbers.add(numberLabel[i]);
              // Add JLabels to 'label' JPanel
              label.add(scoreLabel);
              label.add(ratingLabel);
              label.add(slopeLabel);
              label.add(dateLabel);
              label.add(courseLabel);
              index.add(indexLabel);
              index.add(Index);
              // Add Panels to JFrame
              window.add(grid, BorderLayout.CENTER);
              window.add(numbers, BorderLayout.WEST);
              window.add(index, BorderLayout.SOUTH);
              window.add(label, BorderLayout.NORTH);
              window.setLocationRelativeTo(null);
              window.setVisible(true);
         // ***********Member functions***********
         public void viewGrid(Golfer g) {
              for (int i = 0; i < 20; i++) {
                   numberLabel[i] = new JLabel();
                   numberLabel[i].setText(String.valueOf(i + 1));
                   scores[i] = new JTextField(3);
                   ratings[i] = new JTextField(4);
                   slopes[i] = new JTextField(3);
                   dates[i] = new JTextField(8);
                   courses[i] = new JTextField(15);
                   scores[i].setEditable(false);
                   ratings[i].setEditable(false);
                   slopes[i].setEditable(false);
                   dates[i].setEditable(false);
                   courses[i].setEditable(false);
                   scores[i].setSize(scoreSize);//<-------Here is where i resize the text fields
                   ratings[i].setSize(ratingSize);
                   slopes[i].setSize(slopeSize);
                   dates[i].setSize(dateSize);
                   courses[i].setSize(courseSize);
              for (int i = 0; i < g.rounds.size(); i++) {
                   scores[i].setText(String.valueOf(g.rounds.get(i).getScore()));
                   ratings[i].setText(String.valueOf(g.rounds.get(i).getRating()));
                   slopes[i].setText(String.valueOf(g.rounds.get(i).getSlope()));
                   dates[i].setText(String.valueOf(g.rounds.get(i).dateString()));
                   courses[i].setText(String.valueOf(g.rounds.get(i).getCourse()));
         public void actionPerformed(ActionEvent e) {
    }Even though i called the setSize() function on all of the text fields they don't change size.  This is probably a problem with the GridLayout, but im not sure.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Even though i called the setSize() function on all of the text fields they don't change size. When using layout managers you use the setPreferredSize() method, NOT setSize().
    This is probably a problem with the GridLayout, but im not sure. However, even if you set the preferred size the GridLayout will size the component based on the space available.
    Read the "Swing Tutorial". There is a section on how layout management works in general and on how each layout manager works specifically.
    You can't code in Swing until you've read the tutorial.

  • A strange Jtextarea resize problem

    Hello everybody:
    I have a jTextArea without Jscrollpane ( I want to do my own scroll)
    For example, the initial height of my jTextArea is 281 pixels
    I divide the height by the rowheight (calculated using getFontMetrics(myfont).getHeight();)
    so, 281/17 = 16.52 possible rows
    When I resize the Frame of my application I recalculate the last values in order to know how many rows are possible
    If I increase the height of the Frame everything is ok, but if I decrease it, the jTextarea makes some 'autoscroll' and the height of the JtextArea not change ????
    Repeat, I'm not using no Jscrollpane linked with the JtextArea.
    So, in this situation the last calculation gives me a wrong value ( height / rowheight).
    I'm using Gridbaglayout, and I think this is the responsible of the situation
    I supose that gridbaglayout says to Jtextarea ' Hey , your new height is least' and the JtextArea makes some 'autoscroll' , so Is there any way to avoid this AutoScroll ?
    Thanks

    I want to edit a file which has 2.000.000 rows of data.
    I have developed a special way to edit it, showing only the number of lines that can be showed in the JtextArea. I only wnat to have a Horizontal scroll, but I dont want Vertical scroll ( I have my own vertical scrollbar)
    When I resize the Jframe, the Jtextarea also resize.
    But if it has content, when I decrease the vertical size of my frame 'somebody' moves the JtextArea, because it is as if the 'y' coordinate of the JtextArea was negative
    The size of my JtextArea is the same before resize !!!???, this is the 'autoscroll' I mentioned in the original post.
    Why is the reason because the increase resize works fine (the Jtextarea grows verticaly) and the decrease not ?
    Thanks

  • JTextArea - selectall problem

    Hi,
    I have a JTextArea, and when a user clicks a button, it should select all the text in the text area. The action listener for the button is...
    myTextArea.selectAll();
    ...now this actually selects the textarea...b/c i can copy and paste it....but the text doesnt look selected. Usually when u select the text, with the mouse for example, the color of the selection changes....make sense??
    so why is the selection color not happening??
    thanks

    I have a JTextArea, and when a user clicks a button....
    so why is the selection color not happening??Selected text is only shown when the component has focus. Focus is now on the button.

  • JTextArea - need event rised on text changed.

    I am making an application which contains a JTextArea. when user writes some data on in, some event must be invoked changing the text of the same JtextArea.
    Problem is, when i change the text, Java automatically adds to JtextArea typed character, what i don't want.
    program works in this way:
    user presses "d" on keyboard -> on JTextArea "e" appears.
    thanks for help.

    This is an example of a text area that forces upper case.
    You can modify it to your needs.
         private static class UpperCaseTextArea extends JTextArea {                
              protected Document createDefaultModel() {
                     return new UpperCaseDocument();
              static class UpperCaseDocument extends PlainDocument {
                  public void insertString(int offs, String str, AttributeSet a)
                         throws BadLocationException {
                         if (str == null) {
                              return;
                         if (str.length() == 1) {
                              char c = str.charAt(0);
                              char cUpper = Character.toUpperCase(c);
                              super.insertString(offs, Character.toString(cUpper), a);
                         else
                             super.insertString(offs, str, a);
          }

Maybe you are looking for