BoxLayout and JTextArea

Ok...here's my senario. I need a JTextArea to take up as much space as needed without using a vertical or horizontal scrollbar I do have a constant width in pixels (500 in most cases) so it should expand by adding more rows. This JTextArea is in a BoxLayout. Here's the problem: I need to set the maximum size for the boxlayout to display it properly, but how do I compute that?
This is in a JPanel used only for printing so I manually call doLayout at the end if that affects anything.
Some code:
JPanel panel=new JPanel();
BoxLayout layout=new BoxLayout(panel,BoxLayout.Y_AXIS);
panel.setBackground(Color.WHITE);
panel.setLayout(layout);
panel.setBounds(0,0,(int)(pf.getImageableWidth()),(int)(pf.getImageableHeight()));
for(int i=0;i<fields.size();i++)
if(fields.shouldPrint())
System.out.println(f.getLabelText()+"\t"+totalChars+"\t"+viewableChars);
panel.add(new JLabel("<html><b>"+f.getLabelText()));
JTextArea area=new JTextArea(f.getText());
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setBorder(BorderFactory.createEtchedBorder());
panel.add(area);
if(panel.getComponentCount()>0)
panel.doLayout();
((Graphics2D)g).translate(pf.getImageableX(),pf.getImageableY());
panel.printAll(g);
return Printable.PAGE_EXISTS;
}

area.setAlignmentX(0);

Similar Messages

  • JTextField and JTextArea don't get focus occuasionally

    I am developing a Java Swing Applet. At edit mode, JComboBox, JCheckBox, JRadioBox, and JButton work fine, but JTextField and JTextArea can't get focus occuasionally while I click them.
    Anyone has idea?
    Thanks

    Thank you Himanshu,
    but that's not exactly what my issue is. This link describes the undesired effect of ending up outisde of the player window and in the browser.
    My problem is kind of the opposite. When I launch the page in the html file I cannot use the tab key to get to any of the controls in the captivate window. I'm stuck in the browser unless I click on the captivate window. That is not acceptable if we want it accessible without using a mouse. I found a way to make it work for chrome like I stated above, but not in FF. Do you have any ideas for this?
    Thanks!
    Monique

  • JTabbedPane and JTextArea

    I have a problem, and I can't find what I need.
    I have an application that is suppose to be an address book. I've created 26 tabs (lettered A - Z) and in each tab, I've placed a JPanel (e.g. panelA, panelB, etc) and on each panel I've placed a JTextArea and a JList . I load my data from a file into a Vector.
    Here's my dilemma, I don't know how to get my data from my Vector to my JTextArea or my JList. If I instantiate a new JList and place it on the tab, it adds it as a new JList.
    I can get the tab via getSource(), but I don't know how to access the JTextArea or the JList in the tab.
    I can sort my Vector, print it out via System.out.println's, shoot, I can even pull out specific elements that correspond to a specific letter (the person who's last name starts with "M" for instance), but getting it into the JList or putting it in the JTextArea eludes me. Any help would be greatly appreciated.

    1) Create a custom panel (MyAddressPanel). Add the JList and JTextArea to the Panel
    2) Create a couple of accessor method (getAddressList, getAddressTextArea) to access any component you add to the panel
    3) Add each panel to the tabbed pane
    Now whenever you want to access the data from a specific tab you would do something like:
    int selected = tabbedPane.getSelectedIndex()
    MyAddressPanel panel = (MyAddressPanel)tabbedPane.getComponentAt(selected);
    JList list = panel.getAddressList();
    ...

  • How to make a frame with components and JTextAreas on it?

    on the Window 98 System, when you press F1 on the keyboard, you will get a window(frame) where there are "buttons" and "textAreas".
    i would like to create a JFrame like that, but how to realize it?
    thanks a lot!!!

    What do you want to do?
    You can easily create a JFrame, and then create JButtons and JTextAreas and then add() them to the JFrame's content pane.
    But you must know that already, so it must be something different you are confused about. What is it?

  • Using JCheckBox, JButton and JTextArea with JDBC

    Hello shlumph and SoulTech2012.
    thanks for the reply. I�m wondering do any of you have links to web pages that include tutorials and source code on using JCheckBox, JButton and JTextArea with JDBC. would any of you who have experience with using JCheckBox, JButton, JTextArea and JDBC together be able to give me a few tips on how to select certain data from a table using JCheckBox, JButton and display the data in a JTextArea? examples of such data could be CD/DVD/Game data - i want users of my video library system to be able to view CD/DVD/Game information by name, age category, type and year. Users should be able to click on a check box (e.g. view by name, age category, type or year) and press a button. What would happen then is that data from the Product table would appear in the text area (which could be placed beneath the check box + button inside a frame and/or panel).
    Thank you very much for your help.

    Quit triple posting and cross posting your questions all over the forum. You already have a posting in this forum on this topic and another posting in the Swing forum and another posting in the Programming forum.

  • Regarding_Height in JSplitPane in which JList And JTextArea

    Hi All,
    I have JSplitPane in which two components Jlist and JTextArea
    placed . Here when I type the text in JTextArea respective row no
    is appeared in JList.Here my problem is how to set the row hieght
    of both JTextArea and JList to equal size ....
    Can any body have the idea pls help me.
    Thanks in advance

    have you experimented with JTextArea's getRowHeight() and
    JLists's get/setFixedCellHeight()?

  • System clipboard, AWT TextAreas, and JTextAreas

    This code makes a JApplet with a Swing JTextArea and an AWT TextArea. The JTextArea won't accept pasted text that was copied from another application. The AWT TextArea will. Why is this, and how can I get a JTextArea to accept pasted input?
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    public class TextAreaTest extends JApplet {
         Container cp = getContentPane();
         JTextArea TextIn = new JTextArea("You can't paste from the system clipboard into this box.",4,44);
         JScrollPane aScrollPane = new JScrollPane(TextIn);
         TextArea awtTextIn = new TextArea("Pasting into this box does work!",4,44);
         public void init() {
              cp.setLayout(new FlowLayout());
              cp.add(new Label("Copy some text from another program."));
              cp.add(new Label("Click in the upper box and press Shift+Insert."));
              cp.add(new Label("Why is nothing pasted?"));
              cp.add(aScrollPane);
              cp.add(awtTextIn);
    //<applet width="500" height="240" code="TextAreaTest.class"></applet>

    Thanks for checking this and replying. Pasting into the JTextArea from outside doesn't work for me, even when I'm running the applet locally. Even when I run the applet with appletviewer from the command prompt, I still can't paste from the outside into the JTextArea. If I cut from the TextArea or from an outside application and try to paste into the JTextArea, nothing happens. I can't go the other way either: If I cut from the JTextArea and try to paste into the TextArea, nothing happens. The only cutting and pasting that works with the JTextArea is that if I cut from within the JTextArea, I can paste back into the JTextArea.
    I wonder why pasting works for you and not for me. I'm using the latest JDK (1.4.2_03) and JRE on Windows XP. I have the same behavior on a Windows 2000 machine with the 1.4.1 JRE.

  • Regular expressions and JTextArea

    Hi,
    The aim of the code below is to match the String "one" to the text that is entered
    in the JTextArea (editor) using the regular expression syntax. When i add a String ("one")
    as an argument to p.matcher then the flow of control is passed
    to the System.out.println method, to indicate that the regular expression is mathced.
    However, when i add editor (editor = JTextArea)
    as an argument to p.matcher then the flow of control is not passed to the System.out.println
    method. Since, what is added to the JTextArea (editor) is a String of text, why does this not work?
    and what method or alteration can be used in order to get this working??
    Thanks very much for any help in advance
    Much appreciated
    import java.util.*;
    import java.util.regex.*;
    import java.io.*;
    import java.lang.*;
    import javax.swing.*;
    public class ExpressReg{
    public String Edit;
    public ExpressReg(String editor){
    editor = Edit;
    String regrex = "one";
    Pattern p = Pattern.compile(regrex);
    Matcher m = p.matcher(editor);
    boolean result = m.matches();
    while(result){
    System.out.println("this works");
    }

    you have your assignment round the wrong way, i think
    u want Edit = editor ?Cheers for the help,
    much appreciated

  • Scroll position and JTextArea

    I hava a JFrame with a JScrollPane/JTextArea in it.
    I frequently update the textarea with a setText(string), but for every update the scrollbar jumps to the bottom. The things is that I want the scrollbar to remember its position and not change its position after an update.
    The string in setText varies in length.
    Any ideas, please.
    Thanks!!

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollingTest {
      static JTextArea textArea;
      static int updateCount = 0;
      static int i;
      public static void main(String[] args) {
        JButton button = new JButton("add data");
        button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            updateDisplay();
        JPanel panel = new JPanel();
        panel.add(button);
        textArea = new JTextArea();
        textArea.setMargin(new Insets(10,10,10,10));
        textArea.setLineWrap(true);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel, "North");
        f.getContentPane().add(new JScrollPane(textArea));
        f.setSize(400,300);
        f.setLocation(400,300);
        f.setVisible(true);
      private static void updateDisplay() {
        String text = "";
        for(i = updateCount; i < 40 + updateCount; i++)
          text += String.valueOf(i) + "\n";
        int caretPosition = textArea.getDocument().getLength();
        textArea.setText(textArea.getText() + text);
        updateCount = i;
        textArea.setCaretPosition(caretPosition);
    }

  • BoxLayout and Container.validate()

    I noticed that if a BoxLayout (or any other layout) is set for a Container, its explicit sizes (maximum and minimum) are ignored after validate() is called on that Container, meaning that the object is resized to values other than what it was configured with.
    Am I missing something? How do I prevent that from happening?
    thank you
    mike

    That matches our experience witth Box/BoxLayout.
    GridBagLayout has not such problem.

  • JFileChooser and JTextArea question

    Hello NG !!!
    I Have to questions about the GUI with Swing:
    1.) JFileChooser: I have a JFrame with my JFileChooser (OpenDialog). How can I realize, that my OpenDialog shows me just the ".txt" files ?
    2.) JTextArea: I want use my JTextArea fro infromation the user about the result. How can I realize, that the JTextArea is deeper or has a frame ?
    Lot of thanks for your help !!!
    schaf77
    PS: Happy new Year !!!!

    1.) JFileChooser: I have a JFrame with my JFileChooser
    (OpenDialog). How can I realize, that my OpenDialog
    shows me just the ".txt" files ?Set a filefiler on your filechooser like this:
    myJFileChooser.setFileFilter(new MyFileFilter() );
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class MyFileFilter extends FileFilter {
        // Accept all directories and all txt files.
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            String extension = getExtension(f);
         if (extension != null) {
                if (extension.equals("txt") ) {
                        return true;
                } else {
                    return false;
            return false;
        private static String getExtension(File f) {
              String ext = null;
             String s = f.getName();
             int i = s.lastIndexOf('.');
             if (i > 0 &&  i < s.length() - 1) {
                   ext = s.substring(i+1).toLowerCase();
             return ext;
        // The description of this filter
        public String getDescription() {
            return "Textfile (*.txt)";
    2.) JTextArea: I want use my JTextArea fro infromation
    the user about the result. How can I realize, that the
    JTextArea is deeper or has a frame ?What do you mean?

  • JTextField and JTextArea in Mac with Java 6 does not work

    Hi there,
    I just installed the new version of Java 6 for Mac and I my text fields and text areas just stoped working. I can paste text to them, but they do not respond to my typing (only backspace works!!). Did anyone have this problem?
    I guess it is still beta and they are going to fix it in time. But I would be happy if I was not the only one and if there is any way to fix it for now.
    I just tried simple code like:
    main... {
      JFrame f = new JFrame();
      f.add(new JTextField(10), BorderLayout.NORTH));
      f.add(new JTextArea(5,2), BorderLayout.CENTER));
      f.pack();
      f.setVisible(true);
    }All the best,
    RC

    ...hm, nope, works for me...

  • KeyEvent and JTextArea

    Hi JDC gurus !!! I have a big problem I can dispatch an keyEvent in awt components but I get a long list of Exceptions when I try the same in swing components.
    My code : (AWT)(tf is a textfield)
    tf.dispatchEvent(new
    KeyEvent(tf,KeyEvent.KEY_TYPED,0,0,KeyEvent.VK_UNDEFINED,'A'));
    And also when I try to use processKeyEvent() function of the JTextArea class I get an Error which says that the method is protected. How do I solve the problem.

    Try this program:
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class Dispat extends JFrame 
         JTextArea ta = new JTextArea("");
         JButton   jb = new JButton("Press this key to dispatch");
         int       ji = 0;
    public Dispat()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         setBounds(1,1,600,350);
         getContentPane().setLayout(null);
         ta.setBackground(Color.pink);
         ta.setBounds(10,60,400,200);
         getContentPane().add(ta);
         jb.setBounds(10,20,200,20);
         getContentPane().add(jb);
         setVisible(true);
         jb.addActionListener(new ActionListener()
            {     public void actionPerformed(ActionEvent be) 
                   char c = jb.getText().charAt(ji++);
                   ta.dispatchEvent(new
                        KeyEvent(ta,KeyEvent.KEY_TYPED,0,0,KeyEvent.VK_UNDEFINED,c));
    public static void main(String[] args )
         new Dispat();
    Noah

  • KeyListener and JTextArea

    Hi
    I am writing a program that takes a users key stroke, translates it (based on the key pressed) and inputs a new character into a JTextArea. However, this currently results in two characters being input into the JTextArea every time one key is pressed - the actual key pressed and the character I want to insert based on the key pressed. Does anyone know how to prevent the first character being input into the JTextArea?
    Put more simply, does anyone know how to prevent a key press from inserting the character into a JTextArea?
    Many thanks,
    David Saunders

    change the character in keyPressed(), consume it in keyTyped()
    something like this
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        final JTextArea ta = new JTextArea(10,25);
        JFrame f = new JFrame();
        f.getContentPane().add(new JScrollPane(ta));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        ta.addKeyListener(new KeyAdapter(){
          public void keyPressed(KeyEvent ke){
            ta.append(""+(char)(ke.getKeyCode()+10));
          public void keyTyped(KeyEvent ke){
            ke.consume();
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Sharing Document between TableEditor and JTextArea

    hi,
    i'm trying to share a javax.swing.text.Document between a TableCellEditor and a JTextArea, so that both, the textarea and the tableeditor show the same text, regardless of where the user is typing.
    At the moment I'm doing this: every time the selection of the table changes, i get the document from the table editor and assign it to the textarea. This construct seems wo work, but only in one direction: if i type text into the table cell, the textarea gets updated, but not the other way round.
    any idea, what could be wrong?
    some code:
    public void valueChanged(ListSelectionEvent e) {
        if(e.getValueIsAdjusting()) {
            int row = table.getSelectedRow();
            JTextComponent txtComp = (JTextComponent) table.getCellEditor(row, TRANSLATED_COL).getTableCellEditorComponent(table, "", true, row, TRANSLATED_COL);
            translatedTextArea.setDocument(txtComp.getDocument());
            showItem(row);
    }

    sorry for my late response. here is an example:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.util.Enumeration;
    import java.util.Properties;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.text.JTextComponent;
    public class TranslatorPanel extends JPanel implements TableModelListener, ListSelectionListener {
         public static final int ITEM_COL = 0;
         public static final int TRANSLATED_COL = 1;
        private JTable table;
        private DefaultTableModel model;
        private JTextArea translatedTextArea = new JTextArea();
        public TranslatorPanel() {
            initGUI();
        private void initGUI() {
            model = new DefaultTableModel(new Object[][] {}, new String[] {"Key","Value"});
            model.addTableModelListener(this);
            table = new JTable(model) {
                 public boolean isCellEditable(int row, int col) {
                      return col == TRANSLATED_COL;
            table.setSurrendersFocusOnKeystroke(true);
            table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table.getSelectionModel().addListSelectionListener(this);
            setLayout(new BorderLayout());
            add(new JScrollPane(table), BorderLayout.CENTER);
            add(new JScrollPane(translatedTextArea), BorderLayout.SOUTH);
            setSize(800,600);
            translatedTextArea.setPreferredSize(new Dimension(800, 300));
            TranslationItem item = new TranslationItem("key1");
            item.setTranslations("value1", "en");
            model.addRow(new Object[] {item, item.getTranslation("en")});
            item = new TranslationItem("key2");
            item.setTranslations("value2", "en");
            model.addRow(new Object[] {item, item.getTranslation("en")});
            item = new TranslationItem("key3");
            item.setTranslations("value3", "en");
            model.addRow(new Object[] {item, item.getTranslation("en")});
        // called, if the content of the table has changed
         public void tableChanged(TableModelEvent e) {
            int row = e.getLastRow();
            if (e.getType() == TableModelEvent.UPDATE) {
                 // store the new value in the item
                 TranslationItem item = (TranslationItem) model.getValueAt(row, ITEM_COL);
                 item.setTranslations((String)model.getValueAt(row, TRANSLATED_COL), "en");
         // called if selection of the table changes
         public void valueChanged(ListSelectionEvent e) {
              if(e.getValueIsAdjusting()) {
                   int row = table.getSelectedRow();
                   JTextComponent txtComp = (JTextComponent) table.getCellEditor(row, TRANSLATED_COL).getTableCellEditorComponent(table, "", true, row, TRANSLATED_COL);
                   translatedTextArea.setDocument(txtComp.getDocument());
                   showItem(row);
         private void showItem(int row) {
              TranslationItem item = (TranslationItem) model.getValueAt(row, ITEM_COL);
              translatedTextArea.setText(item.getTranslation("en"));
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setSize(800,600);
            frame.add(new TranslatorPanel());
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        private class TranslationItem implements Comparable {
            private String key = null;
            private Properties translations = new Properties();
            public TranslationItem(String key) {
                this.key = key;
            public String getKey() {
                return key;
            public void setKey(String key) {
                this.key = key;
            public String getTranslation(String locale) {
                String value = translations.getProperty(locale);
                return value == null ? "" : value;
            public boolean translatedForLocale(String locale) {
                String translation = getTranslation(locale);
                if(translation == null || translation.length() <= 0) {
                    return false;
                } else {
                    return true;
            public void setTranslations(String translation, String locale) {
                translations.setProperty(locale, translation);
            public String toString() {
                return key;
            public void print() {
                System.out.println("key " + key);
                Enumeration en = translations.propertyNames();
                while (en.hasMoreElements()) {
                    String locale = (String) en.nextElement();
                    String translation = translations.getProperty(locale);
                    System.out.println("\t"+locale+" = " + translation);
            public int compareTo(Object o) {
                if(o instanceof TranslationItem) {
                    TranslationItem ti = (TranslationItem) o;
                    return ti.getKey().compareTo(getKey());
                return 0;
    }

Maybe you are looking for