JTextArea with padding?

Hello,
is it possible to get a padding between my text and the border of a textArea?
Thanks,
Alex

Have you tried textarea.setBorder(new Insets(10, 10, 10, 10)) for example ?
If it works, you'll have a little more of work because JTextArea has its own border, but you can build a compound one...
Hope this helped,
Regards.

Similar Messages

  • Error using JTextArea with JScrollPane

    hi,
    I am using JTextArea with JScrollpane. I am getting a problem in selecting the text in text area. I am searching for some text in the text area and selecting it if search successful. The problem is that the the scrollbar position didnt set to the correct location. So sometime the text selected is not visible in the scrolpane. Any help regarding this will be highly appreciated.
    Regards
    Danish

    What about sth like this:Rectangle r = textarea.modelToView(textarea.getSelectionStart());
    scrollpane.scrollRectToVisible(r);Just a guess, no idea whether it works.

  • Border with padding for object styles

         Hi,
    I am trying to apply a universal object style in my Indesign CC 14 document. I'd like each image (object, non text) to have a a border with padding. Currently, I know how to apply the border (object styles > stroke > outer fill) and I can get rounded corners and all real nice. But I need that padding between the image and the border.
    As i understand it, I apply the margin through the text style, but how to apply the padding for the border?
    thanks
    matt

    For text frames you use Inset Spacing in Text Frame Options. For images you can make a custom stroke style like this and apply it to the image frame. Here the stroke is from 0 to 25% and the gap is from 25 to 100%. I've applied a 20pt stroke outside aligned, so the stroke is 5 pts and the gap or padding is 15pts. You can then color the gap or leave it transparent:

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

  • Background image fill div, text with padding

    I have a div set up with a width of 182px, and the padding is T:15 R:10 B:15 L:20. The text in the div works with these parameters, but when I add my background image (a bar of color) also 182px, it does not fill the div, only about 75% of it. I'm learning as I go, so any advice would be appreciated.

    gregjb wrote:
    I have a div set up with a width of 182px, and the padding is T:15 R:10 B:15 L:20. The text in the div works with these parameters, but when I add my background image (a bar of color) also 182px, it does not fill the div, only about 75% of it. I'm learning as I go, so any advice would be appreciated.
    Padding is added to the dimensions of the <div>. So your <div> is really 182px wide plus padding left and right 30px = 212px
    So your background image needs to also be 212px wide.
    HOWEVER if you do want your <div> to only be 182px wide set its width to 152px wide to take into account the padding.

  • Problem update JTextArea with message from thread

    I have a JTextArea to present the actually status of an running thread. The thread sends strings like: System.out.println("Reading in new message...");to the standardoutput.
    The problem is, that my application freezes when it should update the JTextArea. Any idea and what type of actionListener is recommend to use for the JTextArea?
    try
       BufferedReader breader = new BufferedReader(new InputStreamReader(System.in));
       statusmsg = breader.readLine();
       statusTextArea.append(statusmsg);
    catch (Exception e){};Cheers

    In general, you can't update the Swing stuff from "side" threads. Side threads talk with the Swing event thread by creating Runnable objects which contains the necessary data (in your case, for instance, the JTextArea or its parent panel/window, and the text to append), and then invoking SwingUtilities.invokeLater() to have this object run() method called by the Sing event thread. See:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html

  • JTextArea with freeze pane functionality

    Greetings. I am trying to implement a plain text viewer that has some sort of "freeze pane" functionality (like that found in MS Excel)
    I took the approach of using 4 JTextArea and put them into a JScrollPane, its row header, column header and upper-left corner. All these text areas share the same document.
    Everything works as expected. When I scroll the lower-right pane, the row and column headers scroll correspondingly. The problem I have is that the document in the lower-right pane now shows duplicate portion of the document that is already showing in the row and column headers.
    Knowing that this should merely be a matter of shifting the Viewport on the document, I went through the documentation and java source, and just couldn't find a way to translate the view. SetViewPosition() works to a certain extent, but the scrollbars allow users to scroll back to the origin and reveal the duplicate data, which is undesirable.
    Your help with find out a way to relocate the view to the desired location is much appreciated.
    khsu

    some sample code attached (with a quick hack in attempt to making it work, at least presentation-wise)
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.text.*;
    public class SplitViewFrame extends JFrame {
        int splitX = 100;
        int splitY = 100;
        public static void main(String[] args) {
            // Create application frame.
            SplitViewFrame frame = new SplitViewFrame();
            // Show frame
            frame.setVisible(true);
         * The constructor.
         public SplitViewFrame() {
            JMenuBar menuBar = new JMenuBar();
            JMenu menuFile = new JMenu();
            JMenuItem menuFileExit = new JMenuItem();
            menuFile.setLabel("File");
            menuFileExit.setLabel("Exit");
            // Add action listener.for the menu button
            menuFileExit.addActionListener
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        SplitViewFrame.this.windowClosed();
            menuFile.add(menuFileExit);
            menuBar.add(menuFile);
            setTitle("SplitView");
            setJMenuBar(menuBar);
            setSize(new Dimension(640, 480));
            // Add window listener.
            this.addWindowListener
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        SplitViewFrame.this.windowClosed();
            makeFreezePane();
        void makeFreezePane() {
            Container cp = getContentPane();
            Font font = new Font("monospaced", Font.PLAIN, 14);
            OffsetTextArea ta = new OffsetTextArea();
            ta.setSplit(splitX, splitY);
            ta.setOpaque(false);
            ta.setFont(font);
            // read doc
            readDocIntoTextArea(ta, "..\\afscheck.txt");
            JScrollPane jsp = new JScrollPane(ta);
            jsp.getViewport().setBackground(Color.white);
            Document doc = ta.getDocument();
            // dump doc
            //dumpDocument(doc);
            JViewport ulVP = makeViewport(doc, font, 0, 0, splitX, splitY);
            JViewport urVP = makeViewport(doc, font, splitX, 0, 20, splitY);
            JViewport llVP = makeViewport(doc, font, 0, splitY, splitX, 20);
            jsp.setRowHeader(llVP);
            jsp.setColumnHeader(urVP);
            jsp.setCorner(JScrollPane.UPPER_LEFT_CORNER, ulVP);
            jsp.setCorner(JScrollPane.UPPER_RIGHT_CORNER, new Corner());
            jsp.setCorner(JScrollPane.LOWER_LEFT_CORNER, new Corner());
            jsp.setCorner(JScrollPane.LOWER_RIGHT_CORNER, new Corner());
            cp.setLayout(new BorderLayout());
            cp.add(jsp, BorderLayout.CENTER);
        void readDocIntoTextArea(JTextArea ta, String filename) {
            try {
                File f = new File(filename);
                FileInputStream fis = new FileInputStream(f);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int br = 0;
                byte[] buf = new byte[1024000];
                while ((br = fis.read(buf, 0, buf.length)) != -1) {
                    baos.write(buf, 0, br);
                fis.close();
                ta.setText(baos.toString());
            } catch (Exception e) {
                e.printStackTrace();
                ta.setText("Failed to load text.");
        protected void windowClosed() {
            System.exit(0);
        JViewport makeViewport(Document doc, Font f, int splitX, int splitY, int width, int height) {
            JViewport vp = new JViewport();
            OffsetTextArea ta = new OffsetTextArea();
            ta.setSplit(splitX, splitY);
            ta.setDocument(doc);
            ta.setFont(f);
            ta.setBackground(Color.gray);
            vp.setView(ta);
            vp.setBackground(Color.gray);
            vp.setPreferredSize(new Dimension(width, height));
            return vp;
        static void dumpDocument(Document doc) {
            Element[] elms = doc.getRootElements();
            for (int i = 0; i < elms.length; i++) {
                dumpElement(elms, 0);
    static void dumpElement(Element elm, int level) {
    for (int i = 0; i < level; i++) System.out.print(" ");
    System.out.print(elm.getName());
    if ( elm.isLeaf() && elm.getName().equals("content")) {
    try {
    int s = elm.getStartOffset();
    int e = elm.getEndOffset();
    System.out.println(elm.getDocument().getText(
    s, e-s));
    } catch (Exception e) {
    System.out.println(e.getLocalizedMessage());
    return;
    System.out.println();
    for (int i = 0; i < elm.getElementCount(); i++) {
    dumpElement(elm.getElement(i), level+1);
    class OffsetTextArea extends JTextArea {
    int splitX = 0;
    int splitY = 0;
    public void setSplit(int x, int y) {
    splitX = x;
    splitY = y;
    public void paint(Graphics g) {
    g.translate(-splitX, -splitY);
    super.paint(g);
    g.translate( splitX, splitY);
    /* Corner.java is used by ScrollDemo.java. */
    class Corner extends JComponent {
    protected void paintComponent(Graphics g) {
    // Fill me with dirty brown/orange.
    g.setColor(new Color(230, 163, 4));
    g.fillRect(0, 0, getWidth(), getHeight());

  • Trouble with padding in CSS

    Hi all
    I'm just a beginner so if the below question seems easy, apologies but i'm struggling with it!
    I have a #footer which is 908px wide x 100px high, im trying to put 20px of white space above the footer in between the main image.
    So i have the following BUT it is showing the padding as the background colour instead of white! How can i fix this.
    #footer {
    width: 968px;
    background-color: #BC1745;
    height: 100px;
    padding-top: 20px;
    Any help much appreciated.
    Many thanks
    Rich

    Apologies Ken, i'm new to this.  See below if this helps.
    HTML:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    <link href="styles/smith_styles.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <div id="container">
      <div id="header"><img src="images/smith_header.jpg" width="968" height="100" alt="Smith Planning" />
        <ul>
          <li><a href="#">Welcome</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Services</a></li>
          <li><a href="#">Clients</a></li>
          <li><a href="#">Giving Back</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </div>
      <div id="main_image"></div>
      <div id="main_text"></div>
      <div id="footer"></div>
    </div>
    </body>
    </html>
    CSS
    @charset "UTF-8";
    /* CSS Document */
    #container {
        width: 968px;
        background: #FFF;
        margin: 0 auto;
        padding-left: 10px;
        padding-right: 10px;
        overflow: hidden;
    #main_image {
              background-image: url(file:///Macintosh%20HD/Users/rpfogg/Documents/Deb%20New%20Site/images/main_image.jpg) ;
              background-repeat: no-repeat;
              height: 376px;
              width: 908px;
              margin-left: auto;
              margin-right:auto;
    #footer {
              width: 968px;
              background-color: #BC1745;
              height: 100px;
              padding-top: 20px;
    #h1 {
              font-family:Arial, Helvetica, sans-serif;
    #header {
              width: 968px;
              margin-left: auto;
              margin-right: auto;
              padding-bottom:20px;
    #header a {
              font-size: 20px;
              font-weight: bold;
              font-variant: small-caps;
              color: #fff;
              text-decoration: none;
              text-align: center;
              display: block;
              width: 100px;
    #header ul {
              margin: 0px;
              padding: 0px;
              list-style-type: none;

  • Printer - printing preferences with pad locks on them

      I am seeking help with my HP ENVY 7640 e-All-in-One-Printer. I was having trouble printing single sided copies and I went to printing preferences and I see that there are pad locks on all the settings. So if I select a preference to change it, it doesn't change, I'm assuming because of the pad locks. I'm not sure how they got there or how to remove them PLEASE HELP!!!  Thanks in advance!  

     You might try the following: Create your own Shortcut / Template from the "locked" shortcuts that are already available. See:Printing Preferences See Section titled: Custom Print Preferences Template  When you see a Post that helps you,Inspires you, provides fresh insight,Or teaches you something new,Click the "Thumbs Up" on that Post. Click my Answer Accept as Solution to help others find Answers.
      

  • How can i get the content of JTextArea with out loosing Indentation.

    I am developing one mail sending application. I am getting mailid , from address, mail body from one Swing. In one JTextArea i am typing i have typed some matter. When i call the content of JTextArea using
    jtx.getText() method, i am getting all the content as one paragraph. That means there is no indentation which was there in TextArea.
    Please provide me some solution how can i get the content of JTextArea wiht out loosing indentation.

    And it was you who asked the question!

  • Can I store iphoto pictures in time capsule and use with pad

    Can I store iphoto pictures in time capsule and use with pad

    We can tell you that it is possible to store separate images on the Time Capsule drive. If however, you are asking if you can access separate images from your Time Machine backups on the Time Capsule, this is not possible.
    How you get the images that your want from iPhoto on your Mac to the Time Capsule drive is a question for the iPhoto experts. It will likely involve "exporting" the files that you want and then moving them using the Finder to the Time Capsule drive.
    How you access those images on the Time Capsule from an iPad is a question for the Using iPad experts.

  • JTextArea with setText

    hi it is sadaf here.....................
    Actually i m picking contents of JTextField using getText and storing into a string getName. next using setText function i wanted to display the Contegnt of getName String into JTextArea....... But after compiling Executing it is not showing any thing there......... Please assist me.......
    inside a button btn_save Listener i m doing this
    public class UserInterface extends JFrame{
         private static final long serialVersionUID = 1L;
         abstract class ActionAdapter implements ActionListener{
         public void actionPerformed(ActionEvent ae){}
    protected Container container;
    protected JTextField t_studentName,t_schoolName;
    protected JTextField t_monthlyFees;
    protected JPanel panel;
    protected JLabel l_studentName,l_schoolName,l_monthlyFees;
    protected JButton btn_save,btn_update,btn_click,btn_delete;
    protected JTextArea nameArea;
    String getName;
    UserInterface(){
         container = new Container();
         container.setLayout(null);
         setSize(500,300);
         panel = new JPanel(null,true);
         setContentPane(panel);
         btn_save = new JButton("save");
         btn_save.setBounds(200,10,70,25);
         panel.add(btn_save);
    ///////////////////////// action Listener for save button/////////////////
    btn_save.addActionListener(new ActionAdapter(){
         public void actionPerformed(ActionEvent ae)     
    ////////////////code for displaying content of getName in textArea///////////
         nameArea.setText(getName);
    ///////////////////////////// Creating JTextArea ///////////////////////////////////
    nameArea = new JTextArea();
         nameArea.setBounds(20,120,150,130);
         panel.add(nameArea);
         l_studentName = new JLabel("student");
         l_studentName.setBounds(10,10,50,25);
         panel.add(l_studentName);
    t_studentName = new JTextField();
         t_studentName.setBounds(70,10,110,25);
         panel.add(t_studentName);
         getName= t_studentName.getText();
    }

    if this is in the constructor
    getName= t_studentName.getText();
    getname wil be whatever is in t_studentName at that time - probably ""
    it is not like Excel's automatic recalculation.
    try changing
    nameArea.setText(getName);
    to
    nameArea.setText(t_studentName.getText());

  • What does getting IPAD with Cellular give me that I can't get with PAD and just WIFI?

    Do any models of IPAD with wifo also have 3G?

    You get GPS and the ability to connect where wifi is not available.
    3G is a type of cellular network, so do you think a wifi only device would have a cellular radio in it?

  • HT2452 i need to check the cloud and match with pad and phone please advise

    trying to set up icloud on all devices using imatch but having trouble any suggestions

    Hi again,
    I'm not full-time at this location, but when I'm here I'm pretty busy, so I haven't had time to blah blah blah.
    Alright, I've figured out the IP addresses, I think.
    My printer's is 192.168.1.105. I know this because it's on the printer's control panel.
    Now, when I look at my network connection in system preferences, it says 122.127.104.156.
    Do I understand correctly that the third set of digits, 1 and 104 respectively, are the subnet and the subnet for the two devices need to be the same?
    The IPv4 is configured using PPP. Am I meant to configure it manually and set up an IP address for this location using the subnet 104? In which case, I need to assign a unique number to my Mac for the final series. And it must  be different from any other device running through this here router.
    That seems like it should be pretty easy. If it's just my mac, the Windows system, and the printer on this network, don't I have the choice of any number except three between 1 and 244?

  • Problem with JTextArea

    Hi all,
    I am having a class which extends JTextArea. I press backspace and I check for some condition in KeyReleased event. If the condition is true I am setting the JTextArea with the old text(retainText). What happens here is that first the backspace entered by me is reflecting on the screen and then only the new text (retainText) is set. This causes a flickering on the text area. My requirement is that this should not happen.
    Is there any way to avoid this .
    or else Is there any way to cancel this event ( say i enter backspace and if the condition becomes true in the KeyReleased event, I should stop this event. Can any body please help me ASAP. Thanks!!!
    I ve attached the code also
    package com.bankofny.iic.client.component;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    import com.bankofny.iic.client.instruction.viewer.TradeDetailForm;
    import com.bankofny.iic.common.util.StringFormatter;
    public class IicTextAreaSwift extends JTextArea implements FocusListener, KeyListener
        // IicTextAreaSwift Method
         private int DescCharWidth = 0;
        private int DescCharHeight =0;
         private String retainText; //retain always the latest text
         private int KeyCode;
         private String KeyText="";
        public IicTextAreaSwift(int _rows, int _columns, boolean scrollPane)
            super(_rows, _columns + 1);
            setDisabledTextColor(Color.gray);
                rows            = _rows;
            columns         = _columns;
            setRows(_rows);
            maxTextAllowed  = _rows * _columns;
            setBorder(new BevelBorder(BevelBorder.LOWERED));
            setLineWrap(true);
            setWrapStyleWord(true);
            Font fixedFont = new Font("Courier", Font.PLAIN, 12);
            setFont(fixedFont);
            FontMetrics fm = getFontMetrics(fixedFont);
            DescCharWidth = fm.charWidth('W') * (_columns + 1);
          //  DescCharHeight = fm.getHeight() * 4 ;
               DescCharHeight =  DEFAULT_LABEL_HEIGHT * 3;
            setPreferredSize(new Dimension(DescCharWidth, DescCharHeight));
            // setSize(new Dimension(DescCharWidth, DescCharHeight));
            addKeyListener(this);
            addFocusListener(this);
            fixTAB();
        public IicTextAreaSwift(int _rows, int _columns)
              super(_rows, _columns);
              // HA this constructor is for this field not in a scroll pane
              setDisabledTextColor(Color.gray);
              rows            = _rows;
              columns         = _columns;
              setRows(_rows);
              maxTextAllowed  = _rows * _columns;
              setBorder(new BevelBorder(BevelBorder.LOWERED));
              setLineWrap(true);
              setWrapStyleWord(true);
              Font fixedFont = new Font("Courier", Font.PLAIN, 12);
              setFont(fixedFont);
              FontMetrics fm = getFontMetrics(fixedFont);
              DescCharWidth = fm.charWidth('W') * (_columns + 1);
             //  DescCharHeight = fm.getHeight() * 4 ;
              DescCharHeight =  DEFAULT_LABEL_HEIGHT * 3;
              setPreferredSize(new Dimension(DescCharWidth, DescCharHeight));
              // setSize(new Dimension(DescCharWidth, DescCharHeight));
              addKeyListener(this);
              addFocusListener(this);
              fixTAB();
        public Dimension getDimen()
              return new Dimension(     DescCharWidth, DescCharHeight);
         public void showKeys(JComponent component)
              // List keystrokes in the WHEN_FOCUSED input map of the component
              InputMap map = component.getInputMap(JComponent.WHEN_FOCUSED);
              printInputMap(map,"WHEN_FOCUSED");
              // List keystrokes in the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT input map of the component
              map = component.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              printInputMap(map,"WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
              //list(map, map.keys());
              // List keystrokes in all related input maps
              //list(map, map.allKeys());
              // List keystrokes in the WHEN_IN_FOCUSED_WINDOW input map of the component
              map = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
              printInputMap(map,"WHEN_IN_FOCUSED_WINDOW");
              printActionMap( getActionMap() , "JTextArea");
              //list(map, map.keys());
              // List keystrokes in all related input maps
            // list(map, map.allKeys());
         public void fixTAB()
              Set newForwardKeys = new HashSet ();
              newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, false));
              this.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys);
              Set newBackwardKeys = new HashSet ();
              newBackwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK, false));
              this.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, newBackwardKeys);
              Set forwardKeys = this.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
    //          System.out.println ("Desktop forward focus traversal keys: " + forwardKeys);
              Set backwardKeys = this.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
    //          System.out.println ("Desktop backward focus traversal keys: " + backwardKeys);
             this.setFocusTraversalKeysEnabled(true);
         public static void printActionMap(ActionMap actionMap, String who)
         {     //     System.out.println("Action map for " + who + ":");
              Object[] keys = actionMap.allKeys();
              if (keys != null)
                   for (int i = 0; i < keys.length; i++)
                        Object key = keys;
                        Action targetAction = actionMap.get(key);
                   //     System.out.println("\tName: <" + key + ">, action: " + targetAction.getClass().getName());
         public static void printInputMap(InputMap inputMap, String heading)
              //System.out.println("\n" + heading + ":");
              KeyStroke[] keys = inputMap.allKeys();
              if (keys != null)
                   for (int i = 0; i < keys.length; i++)
                        KeyStroke key = keys[i];
                        Object actionName = inputMap.get(key);
                   //     System.out.println("\tKey: <" + key + ">, action name: " + actionName);
    public void paste()
    public void focusGained(java.awt.event.FocusEvent event)
              //System.out.println("Hman " + event.paramString());
         if(event.getOppositeComponent() != null)
              if(event.getOppositeComponent().getParent() != null)
                   if (findRoot(event.getOppositeComponent()) != null && findRoot(this) != null)
                        if ( isEnabled() && findRoot(event.getOppositeComponent()) == findRoot(this))
                        selectAll();
         public Component findRoot(Component _cc)
              while (_cc.getParent() != null)
                   cc = cc.getParent();
                   //System.out.println("Parent:" + _cc);
                   if (_cc instanceof TradeDetailForm)
                   return _cc;
              return null;
    public void focusLost(java.awt.event.FocusEvent event)
         Begin Nirmal 1: Requirements 3.1 issues.
         To fix: getValue() method never returns more than the rows.
         New method added to ensure user entered text never goes beyond Rows
    * Method to ensure the getValue() never returns more than the rows.
    * will return -1 if the rows are out of range
    * @param KeyEvent
    * @return int
    public int ensureNotBeyondRows(KeyEvent e)
              String[] s = getValue();
              if (s==null)
                   return 0;
              if (s.length>rows)
                   setText(retainText);
                   return -1;
              String str=getText();
              insert(e.getKeyChar()+"", getCaretPosition());
              s = getValue();
              setText(str);
              if (s.length>rows)
                   setText(retainText);
                   return -1;
              return 0;
         End Nirmal 1:
    // main Method
    // processComponentKeyEvent Method
    public void keyTyped(KeyEvent e)
         /* Naga */
              System.out.println("inside keyTyped");
              System.out.println("e.getKeyChar() " + KeyEvent.getKeyText(e.getKeyCode()));
         /*try
                   java.lang.Thread.sleep(2000);
              catch(InterruptedException ie)
         try {
    int curPos2 = getCaretPosition();
    int curLine2 = getLineOfOffset(curPos2);
    //System.out.println( "curline:" + curLine2 + " of " + rows);
    char[] tmp = {e.getKeyChar()};
    int curPos1 = getCaretPosition();
    int line1 = getLineOfOffset(curPos1) ;
    int startOfLine = getLineStartOffset(line1) ;
    if( curPos1 == startOfLine && line1 > 0)
    if ((tmp[0] == ':') || (tmp[0] == '-' )){
    // System.out.println("hman3");
    e.consume();
    return;
                   Begin Nirmal 2: Requirements 3.1 issues.
                   To fix: getValue() method never returns more than the rows.
                   New method added to ensure user entered text never goes beyond Rows
                   if (!isArrowKey(e) &&
                        (e.paramString().indexOf("Enter") == -1 ) &&
                        !isBackspaceKey(e)) {
                             int maxLimitFlg=ensureNotBeyondRows(e);
                             setCaretPosition(curPos2);
                             if (maxLimitFlg == -1)
                                  e.consume();
                                  return;
                   End Nirmal 2:
    // System.out.println("e.paramString()" + e.paramString());
    // System.out.println("place 2 " + e.paramString());
    if (!(StringFormatter.isValidSwift(tmp[0])) && !(functionKey(e)) && notMoveForward(e))
    // System.out.println("hman2 isaction" + e.isActionKey());
    // System.out.println("KeyTyped" + e.getKeyChar()+ e.getKeyText(e.getKeyCode()) + "/keycode" + e.getKeyCode() + "/modifiers" + e.getModifiers() );
    e.consume();
    return;
    int curPosInLine = -1;
    int firstPos = -1;
    if (getText().length() < maxTextAllowed ||
    (KeyCode == KeyEvent.VK_UP || KeyCode == KeyEvent.VK_BACK_SPACE))
    int curPos = getCaretPosition();
    if (!(functionKey(e)))
    e.setKeyChar( (new String( tmp ).toUpperCase()).toCharArray()[0]);
    curPos2 = getCaretPosition();
    curLine2 = getLineOfOffset(curPos2);
    //System.out.println( "curline:" + curLine2 + " of " + rows);
    if (curLine2 + 1 >= rows &&
    (KeyCode == KeyEvent.VK_ENTER ||
    KeyCode == KeyEvent.VK_DOWN) )
    // System.out.println("hman1");
    e.consume();
    return;
    else {
    String oldText = getText();
    // super.processKeyEvent(e);
    if (getNumberOfLines(getLineCount()) == -1 && !(functionKey(e)))
    setText(oldText);
    invalidate();
    setCaretPosition(curPos);
    } } catch (javax.swing.text.BadLocationException evt) {
    System.out.println("Bad Location Exception in processKeyEvent");
    public void keyPressed(KeyEvent e){
              //System.out.println("keyPressed" + e.getKeyCode()+ e.getKeyText(e.getKeyCode()));
                   retainText = getText();//retain always the latest text
                   /* Naga */
                   //System.out.println("retainText " + retainText);
                   System.out.println("inside keyPressed");
                   System.out.println("e.getKeyChar() " + KeyEvent.getKeyText(e.getKeyCode()));
                   /*try
                        java.lang.Thread.sleep(2000);
                   catch(InterruptedException ie)
    public void keyReleased(KeyEvent e){
              //System.out.println( "keyReleased" + e.getKeyCode()+ e.getKeyText(e.getKeyCode()));
         String []s = getValue();
         /* Naga */
         System.out.println(" inside keyReleased");
         System.out.println("e.getKeyChar() " + KeyEvent.getKeyText(e.getKeyCode()));
         /*try
              java.lang.Thread.sleep(2000);
         catch(InterruptedException ie)
              /*try
                   System.out.println("s " + s[0]);
                   System.out.println("s " + s[1]);
                   System.out.println("s " + s[2]);
                   System.out.println("s " + s[3]);
              catch(Exception e1)
              //System.out.println("s.length " + s.length);
              //System.out.println("rows " + rows);
              if (s!=null && s.length>rows)
                   System.out.println("setting text");
                   //setText(retainText);
                   invalidate();
         public boolean isTab(KeyEvent e)
              if (e.paramString().indexOf("keyChar=Tab") == -1)
              return false;
              } else
                   return true;
         public boolean keepProcessing(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("keyChar=Backspace") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Left") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Down") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Up") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Delete") != -1 ) { return true; }
              if (e.paramString().indexOf("keyChar=Right") != -1 ) { return true; }
              return false;
         public boolean isArrowKey(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("Left") != -1 ||
                   e.paramString().indexOf("Down") != -1 ||
                   e.paramString().indexOf("Up") != -1 ||
                   e.paramString().indexOf("Right") != -1 )
                   return true;
              return false;
         public boolean isBackspaceKey(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("Backspace") != -1)
                   return true;
              return false;
         public boolean isDeleteKey(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("Delete") != -1)
                   return true;
              return false;
    public boolean notMoveForward(java.awt.event.KeyEvent e)
              if (e.paramString().indexOf("Backspace") == -1 &&
              e.paramString().indexOf("Left") == -1 &&
              // e.paramString().indexOf("keyText=Down") == -1 &&
              e.paramString().indexOf("Up") == -1 &&
              e.paramString().indexOf("Delete") == -1 ) { return true; }
              return false;
    // processKeyEvent Method
    public void processKeyEvent(java.awt.event.KeyEvent e)
    //     System.out.println( "processKeyEvent");
         /* Naga */
         System.out.println(" inside processKeyEvent");
         System.out.println("e.getKeyChar() " + KeyEvent.getKeyText(e.getKeyCode()));
                   if (e.paramString().indexOf("KEY_PRESSED") != -1) {
                        KeyText=e.paramString();
                   } else {
                        KeyText="";
                   KeyCode=e.getKeyCode();
    int filledRows = (getText().length()-1)/columns + 1;
    if (KeyCode == KeyEvent.VK_ENTER && filledRows >= rows)
    return;
    try {
                   if (isArrowKey(e) || isBackspaceKey(e) || isDeleteKey(e)) {
                        super.processKeyEvent(e);
                        return;
    int curPos2 = getCaretPosition();
    int curLine2 = getLineOfOffset(curPos2);
    // System.out.println( "curline:" + curLine2 + " of " + rows);
    if (curLine2 + 1 >= rows &&
    (KeyCode == KeyEvent.VK_ENTER ||
    KeyCode == KeyEvent.VK_DOWN) )
                             //System.out.println("hman5");
    e.consume();
    return;
    int curPosInLine = -1;
    int firstPos = -1;
    if (getText().length() < maxTextAllowed)
    int curPos = getCaretPosition();
    curPos2 = getCaretPosition();
    curLine2 = getLineOfOffset(curPos2);
    int curlinepos = getLineStartOffset(curLine2) ;
                   if ( (curLine2 + 1 == rows) && (curPos2 - curlinepos >= getColumns() - 1) && notMoveForward(e))
                        e.consume();
    return;
    if ((curLine2 + 1 >= rows &&
    (KeyCode == KeyEvent.VK_ENTER ||
    KeyCode == KeyEvent.VK_DOWN) ))
    // System.out.println("hman6");
    e.consume();
    return;
    } else {
    String oldText = getText();
    // System.out.println("hman7");
    super.processKeyEvent(e);
    if (getNumberOfLines(getLineCount()) == -1 && !(functionKey(e)))
    // System.out.println("hman8");
    setText(oldText);
    invalidate();
    setCaretPosition(curPos);
    } } catch (javax.swing.text.BadLocationException evt) {
    System.out.println("Bad Location Exception in processKeyEvent");
    // processFunctionalKeys Method
    public boolean processFunctionalKeys(java.awt.event.KeyEvent e)
    // System.out.println( "processFunctionalKeys");
    if (KeyCode == KeyEvent.VK_BACK_SPACE ||
    KeyCode == KeyEvent.VK_ESCAPE ||
    KeyCode == KeyEvent.VK_PAGE_UP ||
    KeyCode == KeyEvent.VK_PAGE_DOWN ||
    KeyCode == KeyEvent.VK_END ||
    KeyCode == KeyEvent.VK_HOME ||
    KeyCode == KeyEvent.VK_LEFT ||
    KeyCode == KeyEvent.VK_UP ||
    KeyCode == KeyEvent.VK_RIGHT ||
    KeyCode == KeyEvent.VK_DOWN ||
    KeyCode == KeyEvent.VK_DELETE
    //System.out.println("Process the KEY getkey:" + e.getKeyChar() + "/getcode:" + e.getKeyCode());
    super.processKeyEvent(e);
    return true;
    else
    return false;
    public boolean functionKey(java.awt.event.KeyEvent e)
    // System.out.println( "functionKey");
    if (KeyCode == KeyEvent.VK_BACK_SPACE ||
    KeyCode == KeyEvent.VK_ESCAPE ||
    KeyCode == KeyEvent.VK_PAGE_UP ||
    KeyCode == KeyEvent.VK_PAGE_DOWN ||
    KeyCode == KeyEvent.VK_END ||
    KeyCode == KeyEvent.VK_HOME ||
    KeyCode == KeyEvent.VK_LEFT ||
    KeyCode == KeyEvent.VK_UP ||
    KeyCode == KeyEvent.VK_RIGHT ||
    KeyCode == KeyEvent.VK_DOWN ||
    KeyCode == KeyEvent.VK_DELETE
    //System.out.println("Process the KEY getkey:" + e.getKeyChar() + "/getcode:" + e.getKeyCode());
    //super.processKeyEvent(e);
    return true;
    else
    return false;
    // getLineCount Method - Returns -1 if number of lines is not between 1 to 4.
    /* This method return -1 if number of lines is not between 1 to 4.
    Pass in getLineCount() to get number of lines for all elements.
    JTextArea separates elements by new line character.
    BnyTextArea treats each row as a line.
    public int getNumberOfLines(int elementCount)
    int lineCount = 0;
    int startPos = 0;
    int endPos = 0;
    for (int i = 0; i <= elementCount - 1; i++) {
    lineCount = lineCount + getLineCountOfElement(i);
    if (lineCount == -1 || lineCount > rows) {
    lineCount = -1;
    break;
    return lineCount;
    // getSpacePos Method - this method finds the first position of space found.
    public int getSpacePos(int pos)
              Begin Nirmal 3: Requirements 3.1 issues.
              Modified the end limit from 0 to pos-columns,
              so that to avoid the return index value from previous lines
              int endLimit=pos-columns;
              if (endLimit<0) {
                   endLimit=pos;
    for (int i = pos; i > endLimit; i--) {
    if (getText().charAt(i) == ' ' || getText().charAt(i) == '\n') { // 11/14/03 Eaten treat \n as space
                        return i;
    return -1;
              End Nirmal 3:
    // getLineCountOfElement Method - returns -1 if number of lines is not between 1 to 4.
    public int getLineCountOfElement(int line)
    int lineCount = 1;
    try {
    int startPos = getLineStartOffset(line) ;
    int endPos = getLineEndOffset(line) ;
    if (moreThanNumOfColumns(startPos, endPos)) {
    lineCount = 2;
    startPos = getSpacePos(startPos+columns);
    if (startPos != -1 && moreThanNumOfColumns(startPos+1,endPos)) {
    lineCount = 3;
    startPos = getSpacePos(startPos+columns);
    if (startPos != -1 && moreThanNumOfColumns(startPos+1,endPos)) {
    lineCount = 4;
    startPos = getSpacePos(startPos+columns);
    if (startPos != -1 && moreThanNumOfColumns(startPos+1,endPos)) {
    return -1;
    } catch (javax.swing.text.BadLocationException e) {
    System.out.println("Bad Location Exception in getLineCountOfElement");
    return lineCount;
    // moreThanNumOfColumns Method
    public boolean moreThanNumOfColumns(int startPos, int endPos)
    if ((endPos - startPos) > (columns + 1))
    return true;
    else
    return false;
    // getNewLineCount Method
    public int getNewLineCount()
    int count = 0;
    boolean rc = true;
    int pos = getText().indexOf(KeyEvent.VK_ENTER, 0);
    if (pos == -1)
    rc = false;
    else
    count++;
    while (rc) {
    pos = getText().indexOf(KeyEvent.VK_ENTER, pos+1);
    if (pos == -1)
    rc = false;
    else
    count++;
    return count;
    // getValue Method
    public String[] getValue()
    // System.out.println(getText());
    int lines = getLineCount();
    int spacePos = 0;
    String str = new String();
    Vector strings = new Vector();
    boolean newLine=true;
    /*Nirmal : this boolean is to add the empty only in new line.
    To avoid those lines which end with \n
    if (getDocument().getLength() > 0) {
    for (int i = 0; i < lines; i++) {
                        newLine=true;
    try {
    int startPos = getLineStartOffset(i) ;
    int endPos = getLineEndOffset(i) + 1;
    /* Naga */
    //System.out.println("startPos " + startPos);
    //System.out.println("endPos " + endPos);
    //System.out.println(i + "HHMAN startPos = " + getLineStartOffset(i));
    //System.out.println(i + "HHMAN endPos = " + getLineEndOffset(i));
    while (moreThanNumOfColumns(startPos,endPos)) {
                                  newLine=false;
    int tempEndPos = 0;
    tempEndPos = startPos + columns;
    System.out.println("tempEndPos " + tempEndPos + " columns " + columns);
    spacePos = getSpacePos(tempEndPos);
    if (spacePos == -1) {
    if (startPos >= getDocument().getLength())
    break;
    else {
    if (tempEndPos >= getDocument().getLength())
    spacePos = getDocument().getLength();
    else {
    spacePos = startPos + columns;
    str = getText().substring(startPos,spacePos);
    if (!(str.trim().equals(""))) {
                                       strings.addElement(str.trim());
    startPos = spacePos;
                             if (startPos < endPos) {
         str = getText().substring(startPos,endPos - 1).trim();
         if(str!=null) {
              if(str.trim().length()>0) {
                                            strings.addElement(str);
                                            continue;
                                       } else {
                                            if(newLine) {
                                                 strings.addElement(str);
    /*Nirmal commented the below lines to fix existing issue
    of adding even empty lines entered in textbox */
    //if ((str==null) || (str.length()==0)) continue;
    //if (!(str.trim().equals(""))) strings.addElement(str);
    } catch (javax.swing.text.BadLocationException e) {
    System.out.println("Bad Location Exception in getValue");
    String[] strs = new String[strings.size()];
    strings.copyInto(strs);
    return strs;
    } else
    return null;
         public void clear() {
    setText("");
    // invalidate();
    // repaint();
    // fixTAB();
    public int getColumnsX()
    if (columnLimits != null)
    int curPos = getCaretPosition();
    //System.out.println("getCaretPosition()" + curPos);
    if (curPos > 0)
    for (int i = 0;i < columnLimits.length;i++)
    curPos = curPos - columnLimits[i];
    if (curPos < 1)
    //System.out.println("getNumberOfLines(curElem)" + i);
    return columnLimits[i];
    } else
    return columns;
    return 0;
         public void setRowLimitX(int rows,int columns)
    maxTextAllowed = rows * columns;
    setRows(_rows);
    rows = _rows;
    columns = _columns;
    setFont(fixedFont);
    setBorder(new BevelBorder(BevelBorder.LOWERED));
    setLineWrap(true);
    setWrapStyleWord(true);
    Font fixedFont = new Font("Courier", Font.PLAIN, 12);
    FontMetrics fm = getFontMetrics(fixedFont);
    int width = fm.charWidth('W') * (35 + 1);
    int height = DEFAULT_LABEL_HEIGHT * 3 ;
    setPreferredSize(new Dimension(width, height));
    public void setEditable(boolean editable)
    super.setEditable(editable);
    super.setEnabled(editable);
    setFocusable(editable);
    if (editable)
    setForeground(Color.black);
    else
    setForeground(Color.gray);
    fixTAB();
    // add your data members here
    // add your data members here
    private int rows = 0;
    private int columns = 0;
    private int[] columnLimits = null;
    private int maxTextAllowed = 0;
    private Font fixedFont = new Font("Courier", Font.PLAIN, 12);
    public final static int LEFT_LABEL_WIDTH = 100;
         public final static int DEFAULT_LABEL_HEIGHT = 20;

    You posted way too much code. 90% of the code is not related to the "backspace" problem. We want compileable and executable code, but only that code that is relevant to the problem.
    Anyway, instead of handling KeyEvents you should read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings for the recommended approach.
    Also you may want to check out this posting which has some information on the backspace KeyStroke:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=566748

Maybe you are looking for

  • IN Portal BSP Blank page is comming

    Hi All, I am facing problem in Production portal . its calling BSP application and its showing Blank page. i have checked in backedn its working..... and portal the iview also working fine.. can any body suggest what would be the case. point will be

  • Issues   :-   after creating sales order   mail goes to customer

    Hello everybody  , my requriment is that after creating the sales order  , the sales order number goes to the customer  so how can i solve this requriment i  tryed to find out user-exit  but i didn't get proper EXIT  point  . please help me out ASAP

  • Error while trying to visualize the results from algorithms (connect with Rserver)

    Hello all, I'm trying to execute Apriori to create a relation purchase between products. I execute the algorithm and it work perfectly, but when I change the view to change the results, it appears the following error: Does anyone knows what might be

  • Container  ALV not working in background

    Hi all, I created an ALV grid, which runs fine foreground. In the background however the spool is created but cancelled. REATE OBJECT g_custom_container         EXPORTING           container_name              = 'G_CUSTOM_CONTAINER'         EXCEPTIONS

  • Af:tree table populate data with viewobject

    Hi all, I am trying to populate data into af:tree which binds with viewobject. so i create recursive view object using view link. then i populate data into view object programmatically. but i found that those data show as normal table rather than tre