Component to JComponent

is there a way to convert heavy weight component to light weight component?
example Component to JComponent

lol... what do u mean.... what i meant was eg..
Label xx = new Label;
but i want to "change" xx of type Label to JLabel

Similar Messages

  • UI delegate for a custom component

    Hello folks,
    I am trying to write (as said in the subject) a UI delegate for a custom component. I found the following in a Java FAQ (http://www.mindspring.com/~scdrye/java/faq.html#plaf_delegate):
    8.3. How do I create a UI delegate for my custom component?
    Have your component extend from JComponent (or a descendant of JComponent). Create a subclass of ComponentUI for your custom component, overriding at least the createUI() and paint() methods. To enable the new UI, override four methods of your JComponent subclass:
    public class MyComponent extends JComponent {
    public void updateUI() {
    setUI((MyComponentUI)UIManager.getUI(this));
    public void setUI(MyComponent newUI) {
    super.setUI(newUI);
    public MyComponentUI getUI() {
    return (MyComponentUI)ui;
    public String getUIClassID() {
    return "MyComponentUI";
    Well, it turns out that this is not enough. I also had to add during application start (just before initComponents()) the following:
    UIManager.put(uiClassID, uiClassName);
    to avoid exceptions during start of the program.
    Well, now my component is painted (paintComponent()) is called, but the paint() method in my new UI delegate class is not called when the application starts.
    It just gets called when I explicitily (in this case, using a menu item) change the L&F of the application.
    If this informatio is not enough, I can add some excerpts of my code for the ease of understanding!!
    Thanks a lot!

    If I code a new custom component (extending JComponent, or extending the UI delegate of a standard component) and pretend it to be laf aware then I must create the corresponding UI delegate for each laf, like it happens to be with standard swing components. But I'm not sure it is feasible to create the UI delegates for all unknown existing custom lafs.You are right, this is never going to work. I suggest if you want to make your custom component look & feel aware, you design the way it displays around the l & f of other components that are part of j2se and have l&f implementations.
    http://download.oracle.com/javase/7/docs/api/javax/swing/plaf/ComponentUI.html
    There are instructions here:
    http://download.oracle.com/javase/7/docs/api/javax/swing/LookAndFeel.html
    >
    On the other side, if I create a custom laf then I will also create a custom UI delegate for each standard component, but I can not create UI delegate for all unknown existing custom components.
    The point here is that standard components and standard lafs are universally known, while custom components (or custom ui delegates) and custom lafs are not.
    So the question is: How does a swing developer deal with the case of a new custom component that will be used in an unknown custom laf?
    For instance:
    1. Custom text UI delegate for dealing with styled documents in JTextField. See {thread:id=2284487}.
    2. JTabbedPane with custom UI delegate that paints no tab if the component only contains one tab.
    In both cases I need a UI delegate for each known laf, but what happens if the application is using a laf that certainly will not be aware of this custom functionally?
    Thank you!

  • Customize "Tab" key for JTextArea to focus next component.

    Hi,
    I am trying to change the "TAB" key behaviour for JTextArea, by using CustomAction configured via InputMap() and ActionMap(). When the user presses the Tab key, the focus should go the next component instead of tabbing in the same JTextArea component. Here is the code for the CustomAction().
        public static class CustomTabAction extends AbstractAction {
            private JComponent comp;
            public CustomTabAction (JComponent comp) {
                this.comp = comp;
                this.comp.getInputMap().put(KeyStroke.getKeyStroke("TAB"), "TABPressed");
                this.comp.getActionMap().put("TABPressed", this);
            public void actionPerformed(ActionEvent evt) {
                Object source = evt.getSource();
                if (source instanceof Component) {
                    FocusManager.getCurrentKeyboardFocusManager().
                            focusNextComponent((Component) source);
        }This works for most of the cases in my applicaiton. The problem is that it doesn't work with JTable which has a custom cell editor (JTextArea). In JTextArea field of JTable, if the Tab is pressed, nothing happens and the cursor remains in the custom JTextArea exactly at the same place, without even tabbing spaces. Here is the CustomCellEditor code.
        public class DescColCellEditor extends AbstractCellEditor implements TableCellEditor {
    //prepare the component.
            JComponent comp = new JTextArea();
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int rowIndex, int vColIndex) {
                // Configure Tab key to focus to next component
                CustomActions.setCustomAction("CustomTabAction", comp);
                // Configure the component with the specified value
                ((JTextArea)comp).setText((String)value);
                // Return the configured component
                return comp;
            // This method is called when editing is completed.
            // It must return the new value to be stored in the cell.
            public Object getCellEditorValue() {
                return ((JTextArea)comp).getText();
        }regards,
    nirvan

    >
    textArea.getInputMap().remove(....);but that won't work because the binding is actually defined in the parent InputMap. So I think you need to use code like:
    textArea.getInputMap().getParent().remove(...);But I'm not sure about this as I've never tried it.I tried removing the VK_TAB key from both the input map and parent input map as shown below. But I still have to press "TAB" twice in order to get out of the JTextArea column in JTable.
                comp.getInputMap().getParent().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));
                comp.getInputMap().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));after coding this, I am using the setFocusTraversalKeys for adding only "TAB" key as ForwardTraversalKey as given below.
            Set newForwardKeys = new HashSet();
            newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newForwardKeys);
            Set newBackwardKeys = new HashSet();
            newBackwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newBackwardKeys);The only problem that remains now is that I have to press the "TAB" twice in order to get out of the JTextArea column
    regards,
    nirvan.

  • Custom component doesnt draw itself

    Hey
    Im relatively new to java, and especially to swing, heres the problem.
    Im trying to make a custom component (extends JComponent).Ive overwridden the paintComponent() method. But when i make a new component and add it to JPanel, it isnt drawn, although i can see that the paintComponent() method of the component is indeed invoked: heres the short code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.MouseInputAdapter;
    import javax.swing.*;
    public class Test extends JFrame {
         static Test window;
         MouseOps mListener;
         JPanel drawingArea;
        public Test() {
              addWindowListener(new WindowAdapter() {
                  public void windowClosing(WindowEvent e) {
                   System.exit(0);
              drawingArea = new JPanel();
              drawingArea.setBackground(Color.white);
              getContentPane().add(drawingArea, BorderLayout.CENTER);
              mListener = new MouseOps();
              drawingArea.addMouseListener(mListener);
              drawingArea.addMouseMotionListener(mListener);
         class MouseOps extends MouseInputAdapter{
              public void mouseClicked(MouseEvent e) {
                   int x = e.getX();
                   int y = e.getY();
                   TestComp comp = new TestComp(x, y);
                   drawingArea.add(comp);
                   drawingArea.validate();
                   repaint();               
         public static void main(String[] args) {
              window = new Test();
              window.setTitle("Test");
              window.setSize(450, 260);
              window.setVisible(true);
    class TestComp extends JComponent {
         int x, y;
         TestComp(int x, int y){
              this.x = x;
              this.y = y;     
         public void paintComponent (Graphics g) {
              super.paintComponent(g);
              g.setColor(Color.blue);
              g.drawRect(x, y, 30, 30);
              System.out.println("Should be drawn at: " + x + " " + y);
    }

    Your component has zero size. The passed in graphics instance has its clip set
    to the components size, so you will never be able to draw anything.
    So you have two choices:
    * set the bounds of your component manually. To do this you will have to use
    a null LayoutManager: http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html
    * or else do not use a separate component for each graphics object at all.
    Use a single container that overrides paintComponent() and iterates itself
    over the graphics objects and calls paint on them. Because the graphics
    objects are much more lightweight this approach scales better and is usually
    taken in graphics frameworks.
    Stephen

  • Having picked up a mouse event, pass it to parent component.

    This is further to my table cell hover, which is otherwise working.
    I track the mouse accross the table using an invisible child component, and when the mouse leaves it, move the child onto the new cell position.
    The problem is that, while the mouse is over the invisible component, that component is grabbing all the mouse events. My table also wants to detect mouse events (though it's interested in clicks).
    The obvious thing is, after they've been dealt with and the child component level, to transfer the events to the table (having mapped the mouse coordinates). However all the processEvents methods in components like JTable are protected.
    I suppose I could extend JTable and add a method to get arround protected, but that's nasty, especially since a lot of my JTables are already subclassed.

    I had to do just this. I have JLabel's in a JPanel. The JPanel is in a LayeredPane. When I mouse over the JLabels, they grab the mouse events... which I don't want. I want the LayeredPane to get it.
    So in the JLabel, I do:
          * Don't send to parent what you don't have to. Things like tooltips will
          * be broken if this is not handled carefully...
         public void mouseClicked(MouseEvent e) { }
         public void mouseMoved(MouseEvent e) { }
         public void mouseEntered(MouseEvent e) { }
         public void mouseExited(MouseEvent e) { }
         public void mouseReleased(MouseEvent e) { machine.dispatchToParent(e);}
         public void mouseDragged(MouseEvent e) { machine.dispatchToParent(e);}
         public void mousePressed(MouseEvent e) { machine.dispatchToParent(e);}(the "machine" above is a JPanel). Now in the JPanel, aka "machine", I do:
    Point point; int comp_x, comp_y; // for component with respect to this machine
    public void dispatchToParent(MouseEvent e) {
         point=((JComponent)e.getSource()).getLocation();
         //System.out.println("Dispatching: " + e.getX() + " " + e.getY());
         //System.out.println("Component position: " + ((JComponent)(e.getSource())).getLocation());
         if (e.getButton() > 0) MsgIFrame.println("ME at: " + comp_x + "," + comp_y + " button: " + e.getButton() );
         if (e.getButton() > 1) {
              popup(e);
              return;
         comp_x=(int)point.getX(); comp_y=(int)point.getY();
         comp_x+=this.getX(); comp_y+=this.getY();
         e.translatePoint(comp_x, comp_y);
         room.getLayeredPane().dispatchEvent(e);
    }Above, the "room" is a JInternalFrame with a LayeredPane inside it, as you can see. I do a little translating so the LayeredPane gets the event in its coordinate space, not those of its Components.

  • How to preven JButton of generated actions when the user keep pressing down

    How to preven JButton of generated actions when the user keep pressing down the key or the short cut
    The code below to show the issue when the user keep pressing Alt+ O
    We want to prevent the JButton from generating multi actions just one action only
    A sample of code shows the behaviour which has to be prevented. Continue pressing "Alt +O" and you will see the standard ouptput will print time stamps
    Please notice, I am NOT interested in Mouse press which has a solution by adding a threshold ( setMultiClickThreshhold(long threshhold) on the JButton  as an attribute.
    public class TestPanel extends JPanel
       private JButton btn;
       public TestPanel()
          btn = new JButton("Open");
          this.add(btn);
          registerCommand(new MyAction(), InputEvent.ALT_MASK,
                KeyEvent.VK_O, btn, btn.getText(), 0);
       public static void registerCommand(AbstractAction action,
             int mask,
             int shortCommand,
             JComponent component,
             String actionName,
             int mnemonicIndex)
          InputMap inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          KeyStroke knappKombination = KeyStroke.getKeyStroke(shortCommand, mask);
          if ((component instanceof AbstractButton)
                && mnemonicIndex >= 0
                && mnemonicIndex < actionName.length()
                && (shortCommand >= KeyEvent.VK_A && shortCommand <= KeyEvent.VK_Z))
             ((AbstractButton) component).setDisplayedMnemonicIndex(mnemonicIndex);
          if (inputMap != null)
             ActionMap actionMap = component.getActionMap();
             inputMap.put(knappKombination, actionName);
             if (actionMap != null)
                actionMap.put(actionName, action);
       public static class MyAction extends AbstractAction
          private static final long serialVersionUID = 1L;
          @Override
          public void actionPerformed(ActionEvent e)
             System.out.println(System.currentTimeMillis());
       public static void main(String... args)
          SwingUtilities.invokeLater(new Runnable()
             public void run()
                JFrame frame = new JFrame("Testing");
                JPanel panel = new TestPanel();
                frame.getContentPane().add(panel);
                frame.setPreferredSize(new Dimension(500, 500));
                frame.setMinimumSize(new Dimension(500, 500));
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
    }Edited by: user12130673 on 2013-feb-13 03:01

    Use KeyStroke getKeyStroke(int keyCode, int modifiers, boolean onKeyRelease) with onKeyRelease=true instead?

  • Changing the size of a JComboBox

    Greetings,
    I am trying to build a mechanism to perform zooming on a JPanel with an arbitrary collection of components (including nested JPanels). I've tried a number of things with little success. The following is my most promising contraption. It can zoom labels, textfields, checkboxes, and buttons. However, for some reason, the combo box refuses to accept a changes to its size. I'm not sure why this is the case. Its font changes size appropriately.
    Anyway, I'm running in JDK 1.4, and the following program lays out a palette of components. To change the size of the components, hit F1 to zoom in, and F2 to zoom out.
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.KeyEventPostProcessor;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.KeyEvent;
    import java.awt.geom.AffineTransform;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class Demo extends JPanel
        public class Zoomer
            private double m_zoom = 1;
            private JPanel m_panel;
            public Zoomer(JPanel panel)
                m_panel = panel;
            private AffineTransform getTransform()
                return AffineTransform.getScaleInstance(m_zoom, m_zoom);
            private Font transform(Font font)
                return font.deriveFont(getTransform());
            private Dimension transform(Dimension dimension)
                Dimension retval = new Dimension();
                retval.setSize(dimension.getWidth() * m_zoom, dimension.getHeight() * m_zoom);
                return retval;
            private void performZoom(Container container)
                Component[] components = container.getComponents();
                for(int i = 0; i < components.length; i++)
                    Component component = (Component)components;
    component.setFont(transform(component.getFont()));
    component.setSize(transform(component.getSize()));
    for(int i = 0; i < components.length; i++)
    Component component = components[i];
    if(component instanceof Container)
    performZoom((Container)component);
    public double getZoom()
    return m_zoom;
    public void setZoom(double zoom)
    if(zoom > 8.0 || zoom < 0.125) return;
    m_zoom = zoom;
    performZoom(m_panel);
    public void zoom(double factor)
    setZoom(getZoom() * factor);
    public Demo()
    JPanel panel = new JPanel();
    panel.add(buildPanel());
    panel.add(buildPanel());
    final Zoomer zoomer = new Zoomer(panel);
    add(panel);
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(new KeyEventPostProcessor()
    public boolean postProcessKeyEvent(KeyEvent e)
    if(e.getID() != KeyEvent.KEY_PRESSED) return false;
    if(e.getKeyCode() == KeyEvent.VK_F1)
    zoomer.zoom(1.2);
    if(e.getKeyCode() == KeyEvent.VK_F2)
    zoomer.zoom(1/1.2);
    return false;
    private JPanel buildPanel()
    JPanel panel = new JPanel();
    panel.add(new JLabel("label: "));
    panel.add(new JTextField("Hello World"));
    panel.add(new JCheckBox("checkbox"));
    panel.add(new JComboBox(new String[] { "Bread", "Milk", "Butter" }));
    panel.add(new JButton("Hit Me!"));
    return panel;
    * Create the GUI and show it. For thread safety, this method should be
    * invoked from the event-dispatching thread.
    private static void createAndShowGUI()
    // Create and set up the window.
    JFrame frame = new JFrame("Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    Demo newContentPane = new Demo();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args)
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    public void run()
    createAndShowGUI();

    component.setSize(transform(component.getSize()));First of all the above line is not needed. The LayoutManager will determine the bounds (size and location) of each component in the container based on the rules of the LayoutManager. The Flow Layout is the default layout manager for a panel and it simply uses the preferred size of the component as the size of the component.
    So what happens is that when you change the font of the component you are changing the preferred size of the component.
    So why doesn't the combo box work? Well I took a look at the preferred size calculation of the combo box (from the BasicComboBoxUI) and it actually caches the preferred size. The combo box uses a renderer, so the value is cached for performance one would assume. The method does recalculate the size when certain properties change. Note the isDisplaySizeDirty flag used in the code below:
             else if (propertyName.equals("prototypeDisplayValue")) {
                    isMinimumSizeDirty = true;
                    isDisplaySizeDirty = true;
                    comboBox.revalidate();
             else if (propertyName.equals("renderer")) {
                    isMinimumSizeDirty = true;
                    isDisplaySizeDirty = true;
                    comboBox.revalidate();
                }It also handles a Font property change as well:
                else if ( propertyName.equals( "font" ) ) {
                    listBox.setFont( comboBox.getFont() );
                    if ( editor != null ) {
                        editor.setFont( comboBox.getFont() );
                    isMinimumSizeDirty = true;
                    comboBox.validate();
                }but notice that the isDisplaySizeDirty flag is missing. This would seem to be a bug (but I don't know why two flags are required).
    Anyway, the following change to your code seems to work:
    // component.setSize(transform(component.getSize()));
    if (component instanceof JComponent)
         ((JComponent)component).updateUI();
    }

  • How can I make a default border for a JWindow?

    I have a JWindow object that is created when a button is pressed in a JFrame. I want the JWindow to have the same type of border as the JFrame from which it's created. However, the JWindow is not created automatically with a border as the JFrame is, so I don't know how to set the border abstractly so that whatever border is used for the JFrame, per he default L&F, will also be used for the JWindow.
    I tried grabbing the border object from the JFame instance itself, but there is no such field in JFrame or any of its ancestor classes. I looked at UIDefaults, but I have no idea how this class can be used to get what I want. For example, if I use UIDefaults.getBorder(Object obj), what do I specify for the argument?
    I'd be happy with an abstract or a concrete solution. That is, either using the default Border for top level containers in the current L&F, or by grabbing an actual Border instance from a JFrame object.
    -Mark

    Also, I'm curious why you said that JFrame is not a swing component.A Swing component extends JComponent. Basically this means that all the painting of the component is done in Java. You can add Borders to any Swing component. It is called a light weight component. A light weight component cannot exist by itself on the window desktop.
    JFrame, JDialog and JWindow are top level components. They can exist on their own on the windows desktop because essentially they are Windows native components. They have been fancied up to make it easy for you to access and add other Swing components to it which is why they are found in the swing package.
    A Windows border is not the same thing as a Swing Border and there is no way to access the native windows border and use it in a Swing application (that I know of anyway). Swing Borders are not used in a normal JFrame, the Windows border is used. You can however, turn off the use of Windows decorations and use Swing painted decorations. Read the tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html#setDefaultLookAndFeelDecorated]Specifying Windows Decorations. However, this doesn't really help you with your Border problem. If you look at the source code for the FrameBorder, you will find that the "blue" color of the Border is only painted for "active" windows and a JWindow can never be the active window, only the parent JFrame or JDialog is considered active.
    Here is a simple program for you to play around with:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class FrameDecorated
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
              frame.setSize(300, 300);
              frame.setVisible(true);
              Border border = frame.getRootPane().getBorder();
    //          Border border = UIManager.getBorder( "RootPane.frameBorder" );
              System.out.println( border );
              JWindow window = new JWindow(frame);
              JPanel contentPane = (JPanel)window.getContentPane();
              contentPane.add(new JTextField(), BorderLayout.NORTH);
              contentPane.setBorder( border );
              window.setSize(300, 300);
              window.setLocationRelativeTo( null );
              window.setVisible( true );
              System.out.println("Window:" + window);
              Window ancestor = SwingUtilities.getWindowAncestor(contentPane);
              System.out.println("Ancestor:" + ancestor);
              System.out.println(ancestor.isActive());
              System.out.println(frame.isActive());
    }

  • Key Bindings using the arrow keys

    Following is some code that allows you to move a component around the screen using the arrow keys. I've noticed a problem and I'm just wondering if its Java or my keyboard.
    Lets start with an example that works:
    Press the down and right keys. Then press either the up or left key. The image moves proving that it supports 3 keys.
    Now for the problem:
    Press the up and left keys. Then press either the down or right key. Three things to notice:
    a) the direction doesn't change when the third key is pressed
    b) no output is displayed, so the ActionListener is not being invoked
    c) after a short time, the program starts beeping
    Now try rerunning the code after removing the comments that assign the key bindings to the "a, s, d, f" keys. Redo the above test and it works even if all four keys are pressed.
    I don't remember this problem when I wrote the code a while ago, but I did recently get a cheap new keyboard so I'm just wondering if the problem is my keyboard or whether its a quirk with Java.
    You can download Duke from here:
    http://java.sun.com/docs/books/tutorial/uiswing/examples/components/LayeredPaneDemoProject/src/components/images/dukeWaveRed.gif
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class KeyboardNavigationProblem implements ActionListener
         private JComponent component;
         private int deltaX;
         private int deltaY;
         private Timer timer;
         private int keysPressed;
         private InputMap inputMap;
         public KeyboardNavigationProblem(JComponent component, int delay)
              this.component = component;
              this.deltaX = deltaX;
              this.deltaY = deltaY;
              timer = new Timer(delay, this);
              timer.setInitialDelay( 0 );
              inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
         public void addAction(int keyCode, String description, int deltaX, int deltaY)
              new NavigationAction(keyCode, description, deltaX, deltaY);
         public void updateDeltaX(int delta)
              deltaX += delta;
         public void updateDeltaY(int delta)
              deltaY += delta;
         public void actionPerformed(ActionEvent e)
              int componentWidth = component.getSize().width;
              int componentHeight = component.getSize().height;
              Dimension parentSize = component.getParent().getSize();
              int parentWidth  = parentSize.width;
              int parentHeight = parentSize.height;
              //  Determine next X position
              int nextX = Math.max(component.getLocation().x + deltaX, 0);
              if ( nextX + componentWidth > parentWidth)
                   nextX = parentWidth - componentWidth;
              //  Determine next Y position
              int nextY = Math.max(component.getLocation().y + deltaY, 0);
              if ( nextY + componentHeight > parentHeight)
                   nextY = parentHeight - componentHeight;
              //  Move the component
              component.setLocation(nextX, nextY);
         class NavigationAction extends AbstractAction implements ActionListener
              private int deltaX;
              private int deltaY;
              private KeyStroke pressedKeyStroke;
              private boolean listeningForKeyPressed;
              public NavigationAction(int keyCode, String description, int deltaX, int deltaY)
                   super(description);
                   this.deltaX = deltaX;
                   this.deltaY = deltaY;
                   pressedKeyStroke = KeyStroke.getKeyStroke(keyCode, 0, false);
                   KeyStroke releasedKeyStroke = KeyStroke.getKeyStroke(keyCode, 0, true);
                   inputMap.put(pressedKeyStroke, getValue(Action.NAME));
                   inputMap.put(releasedKeyStroke, getValue(Action.NAME));
                   component.getActionMap().put(getValue(Action.NAME), this);
                   listeningForKeyPressed = true;
              public void actionPerformed(ActionEvent e)
                   if (listeningForKeyPressed)
                        updateDeltaX( deltaX );
                        updateDeltaY( deltaY );
                        inputMap.remove(pressedKeyStroke);
                        listeningForKeyPressed = false;
                           if (keysPressed == 0)
                                timer.start();
                     keysPressed++;
                   else // listening for key released
                        updateDeltaX( -deltaX );
                        updateDeltaY( -deltaY );
                        inputMap.put(pressedKeyStroke, getValue(Action.NAME));
                        listeningForKeyPressed = true;
                        keysPressed--;
                           if (keysPressed == 0)
                                timer.stop();
                   System.out.println(KeyboardNavigationProblem.this.deltaX + " : "
                   + KeyboardNavigationProblem.this.deltaY);
         public static void main(String[] args)
              JPanel contentPane = new JPanel();
              contentPane.setLayout( null );
              JLabel duke = new JLabel( new ImageIcon("dukewavered.gif") );
              duke.setSize( duke.getPreferredSize() );
              duke.setLocation(100, 100);
              contentPane.add( duke );
              KeyboardNavigationProblem navigation = new KeyboardNavigationProblem(duke, 100);
              navigation.addAction(KeyEvent.VK_LEFT, "zLeft", -5, 0);
              navigation.addAction(KeyEvent.VK_RIGHT, "zRight", 5, 0);
              navigation.addAction(KeyEvent.VK_UP, "zUp", 0, -5);
              navigation.addAction(KeyEvent.VK_DOWN, "zDown", 0, 5);
    //          navigation.addAction(KeyEvent.VK_A, "zLeft", -5, 0);
    //          navigation.addAction(KeyEvent.VK_S, "zRight", 5, 0);
    //          navigation.addAction(KeyEvent.VK_D, "zUp", 0, -5);
    //          navigation.addAction(KeyEvent.VK_F, "zDown", 0, 5);
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.setContentPane( contentPane);
              frame.setSize(800, 600);
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

    if you hold down left and right (so it doesn't move), down works, but not up.
    hold up/down, right works but not left.Yes, the problem only seems to be when the up and left in combination with the right or down key is pressed.
    num lock off - use the number pad arrow keys and all works OK Thats interesting, I didn't notice that. Although it just confuses the issue as to what the problem is.
    So it appears to me that:
    a) left + up + down, and
    b) left + up + right
    are special key combinations that are intercepted by either the OS or the JVM. Do these key combinations ring a bell to anybody?
    I'm use JDK1.4.2 on XP. I wonder if other OS will have the same problem?
    Again, this isn't a real, problem, just more of a curiosity. Thanks,

  • 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

  • Help with scrolling

    Hey all,
    I have a custom component (extending JComponent) that I have inside a JScrollPane. I am implimenting Scrollable. The problem is that all I am drawing in my component is ImageIcons (I have to ... long story). Because drawIcon() doesn't draw a "component", but just pretty colors on the screen, the JScrollPane doesn't realize that the contentn goes outside of the viewport, and so the scrollbars don't work. Any help/advice/whatever would be most apreciated!!
    Thanx!
    Me.

    that didn't seem to do the trick. I tried setSize and setPreferredSize for JScrollPane.getViewport and JScrollPane.getViewport.getView. Any other thoughts?

  • Abstract Method in a Class with implemented method

    I have a class which already has methods Implemented.I mean thse metgods are not abstract.I want only one method to be abstarct which will be overrideen by its subclass or derived Class
    I have never tried this
    Does anyone knows how to do this
    If yes could you give me syntax of the method
    Thanks in advance
    CSJakharia

    javax.swing.JComponent is an example of an abstract
    class with no abstract methods. That is why the
    following works:
    JComponent component = new JComponent(){};
    Not to forget you cannot instantiate abstarct classes
    public abstract class Test
    public String getName()
    return "Mike";
    public static void main(String[] args)
    Test tt = new Test();
    System.out.println(tt.getName());
    }and you would get the error
    The type Test cannot be instantiated.
    You remove the abstract keyword and it would compile
    good.No I am not misinterpreting I know what he is saying but I am closing the door of misinterpretation which I felt was possible. ;)
    cheers

  • Set border for JComboBox

    i'm trying to change the border for a JComboBox...actually the default border for a JComboBox is null but it is the border for the JScrollPane used by the JComboBox that i want to change....i'm lost as to how to access the JScrollPane that the JComboBox uses so i can change it's border...any ideas?...thanx in advance...

    This might help you see the component you're looking for, but at YATArchivist said, it is a look and feel not a JCombobox componentimport  javax.swing.*;
    import  java.awt.*;
    import  java.util.Random;
    import  java.awt.event.*;
    public class ComboScroll {
      static Random rnd = new Random(); 
      public static void main (String[] args) {
        try {
          if (args.length > 0) {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception ex) {
          ex.printStackTrace();
        final JComboBox combobox = new JComboBox(
          ("foo|bar|baz|" + UIManager.getCrossPlatformLookAndFeelClassName()).split("\\|"));
        combobox.setEditable(true);
        final JFrame frame = new JFrame("ComboScroll");
        frame.getContentPane().add(combobox);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Timer timer = new Timer(800, new ActionListener () {
          public void actionPerformed (ActionEvent e) {
            dumpTree(frame, 0);
            Window[] windows = frame.getOwnedWindows();
            for (int index = 0; index < windows.length; index++) {
              dumpTree(windows[index], 0);
            System.out.println();
        timer.setRepeats(true);
        timer.start();
      static void dumpTree (Component component, int depth) {
        String className = component.getClass().getName();
        System.out.println(indent(depth) + component.getName() + ":" + className);
        if (component instanceof Container) {
          Container container = (Container)component;
          for (int index = 0; index < container.getComponentCount(); index++) {
            dumpTree(container.getComponent(index), depth + 1);
          if (component instanceof JComponent) {
            try {
              ((JComponent)component).setBorder(
                BorderFactory.createTitledBorder(
                  BorderFactory.createMatteBorder(4, 4, 4, 4, new Color(
                    rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))),
                  className.substring(className.lastIndexOf('.') + 1)));
            } catch (Exception ex) {
        if (depth == 0) {
          System.out.println();
      static String indent (int depth) {
        return "                                         ".substring(0, depth * 2);
    }Pete

  • Displaying dynamically changing image: a problem with JLabel.

    Hello! I use NetBeans 5.5 and I develop my GUI with Matisse. I'm rather a beginner in developing GUIs with this editor...
    I'd like to display a dynamically changing image. The idea is: GUI shows the image, that is modified as some computations run in a different thread. App will be run on a single machine.
    I'm trying to display the image as a label's icon. The problem is that my app's frame can be resized - and when it is, the label also resizes. When the label is resized, the image should also be resized - the image should always be of the same size as the label. The problem? I noticed, that it works only when I make my app's bigger. When I try to lower its dimensions, the label's dimensions remain the same. Why the label don't make its size smaller?
    My code works as follows: when app's main frame is resize, the panel (the one, that the label is placed in) is also resized. And, since the label is in the panel, it (should) also be resized. So I wrote all the resize-events handlers (therefore I know that the resize event is sent when my app's frame is resized, and when the panel is resized - but the label is resized only when it grows bigger). In this methods I modify the image displayed in the label (I resize the image).
    Or, perhaps, there is some other way to show a (dynamically changing) image with Swing... I chose JLabel, because I didn't want to write my own JComponent. JLabel can display image and that is all I need. The problem is: when the label grows bigger, I create a new, bigger image (icon). Why my label don't get smaller (the resize event isn't even sent)?

    There is no component that dynamically resizes an image. You need to create your own. Something like this:
    JComponent component = new JComponent()
         protected void paintComponent(Graphics g)
              //  Scale image to size of component
              g.drawImage(yourImage, 0, 0, getWidth(), getHeight(), null);
    };

  • Vertical Labels

    I'm having a problem with getting text to read downwards using 'JLabels' (but I don't mind using normal 'Label's).
    If anybody knows how to either :-
    1) Get a Label or JLabel to write downwards or,
    2) Rotate a Component or JComponent 90 degrees
    I would be very thankful. I've looked as much as I can into the Online Javadoc Overview without finding a solution.
    Thanks

    The obvious way to do 2) is to override the size accessor methods (getPreferredSize etc) to invert the width and height and then implement paint / paintComponent as: protected void paintComponent(Graphics g)
        if (g instanceof Graphics2D)
            // Let affine transforms handle it.
            Graphics2D g2d = (Graphics2D)g;
            g2d.rotate(-Math.PI / 2);
            // It may also be necessary to translate it. Left as an exercise to the reader.
            super.paintComponent(g2d);
            // Now undo our affine transforms, starting with the translation if used.
            g2d.rotate(Math.PI / 2);
            // g is now in the original affine space.
        else
            // Have to paint onto a BufferedImage or somesuch, rotate that and paint.
            // Note: this will be very slow. Optimise by reusing BufferedImage when size doesn't change.
            Dimension actualSize = getSize();
            BufferedImage img = new BufferedImage(actualSize.height, actualSize.width, BufferedImage.TYPE_INT_ARGB);
            super.paintComponent(img.getGraphics());
            // Construct a suitable affine transform - again, translation may be necessary.
            AffineTransform trans = new AffineTransform();
            trans.rotate(-Math.PI / 2);
            // Transform the image.
            AffineTransformOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOUR);
            BufferedImage imgRot = new BufferedImage(actualSize.width, actualSize.height, BufferedImage.TYPE_INT_ARGB);
            op.filter(img, imgRot);
            // Should really use an ImageObserver?
            g.drawImage(imgRot, 0, 0, null);
    }Note: this is not production-quality code. It is entirely untested. Use at own risk.

Maybe you are looking for