Showing posts with label JTextArea. Show all posts
Showing posts with label JTextArea. Show all posts

Wednesday, July 27, 2016

Solved - JTable: wrap text in a cell, column, or row

To wrap text in a JTable, you need to create a TableCellRenderer and TableCellEditor that use the JTextArea as the component. Then, use them for the cell, column, row, or the whole table where you want to wrap text. Following is a sample code.


public class TableWrapText extends JFrame {
    private DefaultTableModel tableModel = null;
 
    public TableWrapText() {
        String[][] data = new String[][]{
            new String[]{"Travel", "Go to somewhere else from where you live to enjoy spending money and getting lost in the esoterics."},
            new String[]{"Help", "Do something to make the person get what he or she wants for pay or for free, it is upto you."},
            new String[]{"Sleep", "A state of temperary unconscious due to the nerves system is busy with something else."}
        };
        tableModel = new DefaultTableModel(data, new String[]{"Name", "Content"});

        JTable table = new JTable(tableModel){
            public TableCellRenderer getCellRenderer(int row, int col){
                //Wrap text in a specific cell
                if (row == 0 && col == 1){
                    return new MyRenderer();
                //Wrap text in a particular column  
          //    if (col == 1) {
//                    return new MyRenderer();
//              }
                //Wrap text in a row
//              if (row == 0) {
//                    return new MyRenderer();
//              }    
                } else {
                    return new DefaultTableCellRenderer();
                }
            }

            public TableCellEditor getCellEditor(int row, int col){
                //Wrap text in a specific cell
                if (row == 0 && col == 1){
                    return new MyEditor();
                //Wrap text in a particular column  
          //    if (col == 1) {
//                    return new MyEditor();
//              }
                //Wrap text in a row
//              if (row == 0) {
//                    return new MyEditor();
//              }    
                } else {
                    return new DefaultCellEditor(new JTextField());
                }
            }
        };
        table.setRowHeight(0, table.getFont().getSize()*3);
//        table.setRowHeight(table.getFont().getSize()*3);
        JScrollPane sp = new JScrollPane(table);
        getContentPane().add(sp);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(600, 400);
        this.setVisible(true);
    }
 
    private class MyRenderer extends JTextArea implements TableCellRenderer{
        public MyRenderer() {
            setOpaque(true);
            setLineWrap(true);
            setWrapStyleWord(true);
        }
     
        public Component getTableCellRendererComponent(JTable table,Object value,
            boolean isSelected, boolean hasFocus, int row,int column) {
         
            this.setText(value == null ? "" : value.toString());
            return this;
        }

    }

    private class MyEditor extends AbstractCellEditor implements TableCellEditor {
        JTextArea comp = new JTextArea();
        JTable table;
        int row;
     
        public MyEditor() {
            comp.setLineWrap(true);
            comp.setWrapStyleWord(true);
            comp.addComponentListener(new ComponentAdapter() {
                public void componentResized(ComponentEvent e) {
                    super.componentResized(e);
                    table.setRowHeight(row, (int) (comp.getPreferredSize().getHeight()));
                }
            });
            comp.addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e) {
                    super.keyTyped(e);
                    table.setRowHeight(row, (int) (comp.getPreferredSize().getHeight()));
                }
            });
        }

        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
            this.table = table;
            this.row = row;

            comp.setText((String) value);
            comp.setFont(table.getFont());

            return comp;
        }

        public Object getCellEditorValue() {
            return comp.getText();
        }
    }
 
    public static void main(String[] args){
        new TableWrapText();
    }
}

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Friday, October 3, 2014

setSize vs setPreferredSize in JTextArea, JTextField, JButton, JLabel, JPanel and JFrame

For JFrame:
          Always use setSize for setPreferredSize does nothing.

For JPanel, JButton and JLabel:
          No need to set their sizes for their sizes are always expanding to the space available. You need to use some invisible components or fillers to occupy the space that you don't want these components to be.

For JTextField:
         The setColumns method designates the size of the JTextField.
         The setPreferredSize makes the JTextField disappear, while the setSize does nothing.

For JTextArea:
          The setRows and setColumns methods designate the size of the JTextArea.

         The setPreferredSize fixes the displaying area. If the setLineWrap(true) method is not called, the input characters will keep adding to the end of the line, however the width of the JTextArea will not expand and it only displays the number of characters its width can hold. If the setLineWrap(true) method is called, the input characters will be displayed in a new line when the width of the displaying area is reached. However, when the height of the displaying area is reached, the height of the displaying area will not expand even though the input characters are keeping adding to the end of the text.

        When setSize is used instead of setPreferredSize, the behavior of the JTextArea is the same as it is not used, if the setLineWrap(true) method is not called, the input characters will keep adding to the end of the line and the width of the JTextArea expands accordingly. If the setLineWrap(true) method is called, the input characters will be displayed in a new line when the width of the displaying area is reached and when the height of the displaying area is reached, the height of the displaying area will expand accordingly.

          If you really want to use the setPreferredSize or the setSize to set the size of the JTextArea instead of using setRows and setColumns, do not call the setRows and setColumns methods and call the setLineWrap(true) before you call the setPreferredSize or the setSize method.

           The setPreferredSize mthod will set the size of the JTextArea to the size specified in the method. The size is fixed and will not expand according to the size of the text you put in it.

           The setSize method will set the width to the specified amount, but will not set the height. The height dynamically expands according to the the text put in the text area.

When the JTextArea is put in a JScrollPane:
          No matter whether the setRows and setColumns or the setPreferredSize or the setSize is used, the size of the JTextArea will occupy the whole available space in the JScrollPane. When setSize is used, it will automatically scroll, where else when setPreferredSize is used the JScrollPane will not scroll.

           However, when a JTextArea is put in a JScrollPane, it is better to not use either setPreferredSize or setSize on the JTextArea and the JScrollPane will scroll when it is needed.

---------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, October 2, 2014

How to make JTextArea display a maximum number of characters?

Following are the steps of setting the maximum numbers of characters that a JTextArea can take.


  1. Create a Document class that extends the PlainDocument class. 
    • In the class create a maxSize field. 
    • Override the insertString method so that only the maxSize or less number of characters can be inserted into the document. 
    • Create a setMaxSize method for setting the value of the maxSize.
  2. Create a Text Area class that extends the JTextArea, which uses the Document created in step 1 as its default document. Add a setMaxSize method to the class that calls the Document's setMaxSize mthod to set the max size for the Document.
Here is the sample code.


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class TextAreaSize {
    
    private class MyDocument extends PlainDocument {
        private int maxSize = 1000000000;
        
        @Override
        public void insertString(int offset, String s, AttributeSet attributeSet)
                throws BadLocationException {
            int length = s.length();
            if (length == 0) {
                return;
            }

            if (offset + length > maxSize) {
                s = s.substring(0, maxSize - offset);
            }
            super.insertString(offset, s, attributeSet);
        }
        
        public void setMaxSize(int size) {
            maxSize = size;
        }
    }
    
    private class MyTextArea extends JTextArea {
        private MyDocument document;
        
        public MyTextArea (MyDocument d){
            super(d);
            document = d;
        }
        
        public void setMaxSize(int s){
            document.setMaxSize(s);
        }
    }
    
    public TextAreaSize() {
        MyTextArea textArea = new MyTextArea(new MyDocument());
        textArea.setMaxSize(30);
        textArea.setRows(2);
        textArea.setColumns(20);
        
        JPanel panel = new JPanel();
        panel.add(textArea);
        
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setSize(500, 300);
        frame.setVisible(true); 
    }
    
    public static void main(String[] args){
        new TextAreaSize();
    }
}

----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


How to make JTextArea display a fixed number of characters each line

There are two ways to achieve this result. One way is to use the setRows and setColumns method to set the size of the JTextArea. The other way is making your text area the subclass of the JTextArea and override the paint() method to get the width and height of the font used. Then, set the size of your text area.

Since for many types of font, the characters do not always have the same widths, some characters are wider than the others, it is better that you use the monospaced font for achieving a constant result.

Following is an example.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class CharInLine {
    private int charWidth = 0;
    private int charHeight = 0;
    private int charPerLine = 30;
 
    public CharInLine() {
        MyTextArea textArea = new MyTextArea();
        textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
     
        //Method 1
        //setting the rows and columns is important for an
        //empty JTextArea to show its size.
        textArea.setRows(5);
        textArea.setColumns(30);
        textArea.setBorder(BorderFactory.createTitledBorder("Text Area"));
     
        //Method 2
        //designate 30 characters per line and 5 lines in the text area
        textArea.setLineWrap(true);
        textArea.setSize(new Dimension(charWidth*charPerLine, charHeight*5));
        //textArea.setPreferredSize(new Dimension(charWidth*charPerLine, charHeight*5));    

        JPanel panel = new JPanel();
        panel.add(textArea);
     
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel,BorderLayout.CENTER);
        frame.setSize(500, 300);
     
        frame.setVisible(true);
    }
 
    private class MyTextArea extends JTextArea {
        @Override
        public void paint(Graphics g){
            super.paint(g);
            FontMetrics fm = g.getFontMetrics();
            charWidth = fm.charWidth('M');
            charHeight = fm.getHeight();
        }
    }
 
    public int getCharWidth() {
        return charWidth;
    }
 
    public static void main(String[] args){
        new CharInLine();
    }
}

Reference:

1. setSize vs setPreferredSize in JTextArea, JTextField, JButton, JLabel, JPanel and JFrame

-----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.