Custom focus rectangle in JTextField

I'm trying to change my theme/look & feel to show a focus rectangle for JTextField, somewhat like this: [http://www.macvswindows.com/index.php?title=GUI_Customization|http://www.macvswindows.com/index.php?title=GUI_Customization] (second image down, or direct [http://www.macvswindows.com/images/thumb/f/f2/osx_aqua_colors.png/500px-osx_aqua_colors.png|http://www.macvswindows.com/images/thumb/f/f2/osx_aqua_colors.png/500px-osx_aqua_colors.png] ) I don't want to make it exactly like MacOS, but a similar idea.
For now I'm just trying to do it on the inner part of the field. I can get it to paint with the code below, but then the caret painting messes things up as I tab through the fields or move the caret around inside the fields.
So it seems I'm headed down the wrong path, what should I be doing? Extending DefaultHighlighter or DefaultCaret, or something else?
Thanks,
Jim
package testui;
import javax.swing.*;
import javax.swing.plaf.metal.DefaultMetalTheme;
import javax.swing.plaf.metal.MetalLookAndFeel;
public class ThemeTest extends JFrame {
    public class TestMetalTheme extends DefaultMetalTheme {
        public void addCustomEntriesToTable(UIDefaults table) {
            UIManager.put("TextFieldUI", "customui.CustomTextFieldUI");
        public String getName() {
            return "TestMetalTheme";
    public static void main(String[] args) {
        ThemeTest testFrame = new ThemeTest();
        testFrame.setVisible(true);
    public ThemeTest() {
        try {
            MetalLookAndFeel.setCurrentTheme(new TestMetalTheme());
            UIManager.setLookAndFeel(new MetalLookAndFeel());
        } catch (Exception e) {
            e.printStackTrace();
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        JPanel panel = new JPanel();
        add(panel);
        panel.add(new JTextField("test"));
        panel.add(new JTextField("test"));
        panel.add(new JTextField("test"));
        panel.add(new JButton("button"));
package testui;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.metal.MetalTextFieldUI;
import java.awt.*;
public class CustomTextFieldUI extends MetalTextFieldUI {
    private Color focusColor = Color.cyan;
    private JComponent component;
    public CustomTextFieldUI(JComponent c) {
        if (c == null) {
            throw new IllegalArgumentException("component must be specified");
        this.component = c;
    public static ComponentUI createUI(JComponent c) {
        return new CustomTextFieldUI(c);
    protected void paintSafely(Graphics g) {
        super.paintSafely(g);
        if (component.hasFocus()) {
            Dimension size = component.getSize();
            Graphics2D g2d = (Graphics2D) g;
            System.out.println(g2d.getClip());
            System.out.println(g2d.getClipBounds());
            g2d.setColor(focusColor);
            g2d.setStroke(new BasicStroke(2f));
            g2d.drawRect(1, 1, size.width - 3, size.height - 3);
}

Why not just combine the two approaches?
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.metal.MetalTextFieldUI;
public class CustomTextFieldUI extends MetalTextFieldUI {
     private Color focusColor = Color.cyan;
     private JComponent component;
     private Border normalBorder;
     private Border focusedBorder;
     private FocusListener focusListener;
     public CustomTextFieldUI( JComponent c ) {
          if ( c == null ) {
               throw new IllegalArgumentException( "component must be specified" );
          this.component = c;
          focusListener =  new FocusListener() {
               public void focusGained( FocusEvent fe ) {
                    if ( normalBorder == null ) {
                         normalBorder = component.getBorder();
                         focusedBorder = new BevelBorder( BevelBorder.LOWERED ) {
                              @Override
                              public Color getHighlightInnerColor() { return focusColor; }
                              @Override
                              public Color getHighlightOuterColor() { return focusColor; }
                              @Override
                              public Color getShadowInnerColor() { return focusColor; }
                              @Override
                              public Color getShadowOuterColor() { return focusColor; }
                    component.setBorder( focusedBorder );
               public void focusLost( FocusEvent fe ) {
                    component.setBorder( normalBorder );
     public static ComponentUI createUI( JComponent c ) {
          return new CustomTextFieldUI ( c );
     @Override
     protected void installListeners() {
          super.installListeners();
          component.addFocusListener( focusListener );
     @Override
     protected void uninstallListeners() {
          super.uninstallListeners();
          component.removeFocusListener( focusListener );
}

Similar Messages

  • JButton & Win XP Look and Feel focus rectangle bug??

    I searched the bug database but was unable to find any matches...
    I have received a bug report from our users relating to mistakenly thinking a button has focus. In the XP LAF, when a button is a 'default' button, it has a blue rectancle drawn around it (which is correct). When you tab to that button however, there is no additional 'focus' rectangle to indicate that the button has focus. I tested this in native XP components and an additional rectancle IS drawn when the button gets focus (in addition to the blue rectangle). Shouldn't there be some sort of focus indicator in addition to the blue rectangle? I'm using JRE version 1.4.2_02.
    Thanks,
    Andy

    Hello Andy!
    If the behavior of Win XP LAF is different from the native this is definitely a bug. It would be greate if you file a bug here
    http://java.sun.com/webapps/bugreport.
    Thank you.
    Anton

  • ComboBox focus rectangle

    I m using Combobox and when I activated accesability by Tab,
    The focus rectangles apears in a grean color, how do I change the
    color of that rectangle.. (I want it to Yellow, like it comes for
    Buttons etc..)
    Regards
    Sidharth

    nobody replied

  • Focus rectangle

    Can someone tell me how to make a focus rectangle visible
    without tabbing. i.e. via code something like that below:
    I know its possible because I've done it before and can't
    remember how I did it.
    Thanks in advance.

    I read through my post and thought it wasn't very clear what
    I was asking. Basically I've created code before that would show a
    focus rectangle if a user clicked in that field with the mouse. Now
    I'm trying to do that again and can't remember how I did it.

  • Focus rectangle around jCheckBox

    Hi all,
    I have a JCheckBox with no label text with it. Usually when the JCheckBox has focus, theres a dotted focus rectangle around the label text, so in this case there never is.
    Since theres a few checkboxes in the same panel, it gets very confusing as you can't see what component is in focus. Is there any way about this? I was trying to create my own checkbox with a dotted border when the component gets focus, but theres no dotted border in swing.
    So my question is this:
    1) Is there any way to change the focus rectangle to go about the whole component and not just the text label?
    or
    2) Is there any dotted border in swing that I've missed?
    thanks,
    Justin

    what about having blank spaces as the text (the # of spaces determines the rectangle width)
    something like this
    import java.awt.*;
    import javax.swing.*;
    class Testing extends JFrame
      JCheckBox cbx1 = new JCheckBox("      ");
      JCheckBox cbx2 = new JCheckBox("      ");
      public Testing()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel p = new JPanel();
        p.add(cbx1);
        p.add(cbx2);
        getContentPane().add(p);
        pack();
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Problem while adding both Key And Focus Listeners to JTextField

    Hi!
    I have something peculiar while adding Key and Focus Listener to JTextField. Suppose i add just Key Listener then everything's fine and i could keep track of keys being pressed. But as soon as i add a Focus Listener to it with the code to select full text in focusGained() method, it starts reponding wrongly to arrow keys pressed and does not perform desired actions. For let arrow key it moves caret by one for the first time after that it does not resond to that unless caret is changed by using mouse. If right arrow key is pressed the it moves the caret to last position from wherever it is. For UP and DOWN it selects the full text(This should be done when it gets focus)
    public void focusGained(FocusEvent fe)
    setCaretPosition(0);
    moveCaretPosition(getDocument().getLength());
    Can someone help me out on this?
    thanks and regards,
    Amit.

    None of those things will cause your JFrame to resize itself. And this is probably a good thing, because your JFrame shouldn't change size once you have created it. Why not create your JPanel so that it has enough space for you to add the component later? Or why not just add the component to start with and then enable it or make it editable when you decide that's necessary?

  • HToggleButton increase width of focus rectangle

    Hi, can anyone tell me how to increase the width of focus rectangle when any component like HToggleButton is focused

    Hi, can anyone tell me how to increase the width of focus rectangle when any component like HToggleButton is focused

  • JTable Focus Rectangle

    When navigating around my table the focus recatangle is not shown - but the correct cell is selected.
    A single click selects a cell, but I need to double click to see the focus triangle.
    I would like the focus rectangle to appear when the cell is selected.
    Any ideas?

    Actually I was't thinking clearly when you asked about a "focus rectangle (which is why I always recommend a simple demo program that shows your problem). I thought you where asking about the "dotted line focus rectangle" that appears on components like JButton.
    Anyway here is a simple table and not that the "focus rectangle" appears on all cells except the column with boolean values.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class TableBasic extends JFrame
         public TableBasic()
              String[] columnNames = {"Date", "String", "Integer", "Boolean"};
              Object[][] data =
                   {new Date(), "A", new Integer(1), Boolean.TRUE },
                   {new Date(), "B", new Integer(2), Boolean.FALSE},
                   {new Date(), "C", new Integer(9), Boolean.TRUE },
                   {new Date(), "D", new Integer(4), Boolean.FALSE}
              JTable table = new JTable(data, columnNames)
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableBasic frame = new TableBasic();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }The default renderer for boolean values uses a JCheckBox to render the value. the check box uses setBorderPainted(false), which is why "focus rectangle" is not painted. Personally, I think this is a bug.
    Anyway, if you want the "focus rectangle" then you would need to create your own Boolean renderer, setBorderPainted(true) and provide a default EmptyBorder for the check box:
    Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);

  • Cropped focus rectangle on Spark VideoPlayer's Play/Pause button

    Can anyone help with an issue I am having with a cropped focus rectangle?
    The video player is cropping the focus rectangle on the bottom and left of the component.  One of my components is audio-only, and that is being cropped at the top too.  Images attached.
    Maybe I could rectify this by setting the focus rectangle direction inwards, instead of outwards?  How would I do that just for this particular component (I definitely wouldn't wan't to change the focus rectangle globally)
    Or is there some other fix perhaps?
    Should I register this as a bug?  If so, where should I do that?

    This looks like a bug. You can file bug reports here: http://bugs.adobe.com/flex/
    -Darrell

  • Open and Close OnScreen Keyboard while focus gain on JTextField

    Hi
    I have a Jtextfield when ever I click on textfield I want to open OSK(On Screen Keyboard) of Windows 8 OS and windows 7.
    I tried in below mentioned way to open and close in focus listener focusGained() and focusLost() but it is not working. could some body do needful.
    Opening OSK:
    builder = new ProcessBuilder("cmd /c " + sysroot + " /System32/osk.exe");
    Closing Osk:
    Runtime.getRuntime().exec("taskkill /f /im osk.exe");

    You need to start() the ProcessBuilder and you need to split the command like this:
    builder  = new ProcessBuilder("cmd", "/c", sysroot + " /System32/osk.exe");
    builder.start();
    And naturally you should wrap the call in a new Thread or use an ExecutorService to avoid EDT problems.

  • How to capture the event on changing focus from a JTextField?

    Hi All,
    I have got a problem...
    I want to do something (say some sort of validations/calculations) when I change the focus by pressing tab from a JTextField. But I am not able to do that.
    I tried with DocumentListener (jtf01.getDocument().addDocumentListener(this);). But in that case, it's calling the event everytime I ke-in something in the text field. But that's not what I want. I want to call that event only once, after the value is changed (user can paste a value, or even can key-in).
    Is there any way for this? Is there any method (like onChange() in javascript) that can do this.
    Please Help me...
    Regards,
    Ujjal

    Hi Michael,
    I am attaching my code. Actual code is very large containing 'n' number of components and ActionListeners. I am attaching only the relevant part.
    //more codes
    public class PaintSplitDisplay extends JApplet implements ActionListener
         JFrame jf01;
         JPanel jp01;
         JTextField jtf01, jtf02;
         //more codes
         public void start()
              //more codes
             jtf01 = new JTextField();
              jtf01.setPreferredSize(longField);
              jtf01.setFont(new Font("Courier new",0,12));
              jtf01.setInputVerifier(new InputVerifier(){public boolean verify(JComponent input)
                   //more codes
                   System.out.print("updating");
                   jtf02.setText("updated value");
                   System.out.print("updated");
                   return true;
              //more codes
              jtf02 = new JTextField();
              jtf02.setPreferredSize(mediumField);
              jtf02.setEditable(false);
              jp01.add(jtf02, gbc);
              //more codes
              jf01.add(jp01);
              jf01.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jf01.setVisible(true);
              //more codes
         public static void main(String args[])
              PaintSplitDisplay psp = new PaintSplitDisplay();
              psp.start();
         public void actionPerformed(ActionEvent ae)
              //more codes
    }As you can see I want to update the second JTextField based on some calculations. That should happen when I change the focus from my frist JTextField. I have called jtf02.setText() method inside InputVerifier. But it's giving error...
    Please suggest...
    Ujjal

  • Focus on a JTextField

    I have a JTextField which is in a JPanel in a JFrame. I have tried grabFocus() and requestFocus() but neither seem to work in ensuring that when the frame is launched that the cursor is blinking on the textbox. Unfortunately I am working on a project where the client is not very keen on using the mouse! Has anyone any ideas on how to ensure that the TextField has the cursor blinking and the focus when it is launched!
    Thanks in advance

    I have a JTextField which is in a JPanel in a JFrame.
    I have tried grabFocus() and requestFocus() but
    neither seem to work in ensuring that when the frame
    is launched that the cursor is blinking on the
    textbox.
    There are some bugs related to Focus management in JDK 1.3.x. They are fixed in JDK 1.4.
    Unfortunately I am working on a project where
    the client is not very keen on using the mouse! Has
    anyone any ideas on how to ensure that the TextField
    has the cursor blinking and the focus when it is
    launched!Fortunately, there is a workaround though :
    JTextField myTextField = new JTextField();
    //.... add this textfield to your panel etc...
      Runnable doHelloWorld = new Runnable() {
         public void run() {    
        myTextField.requestFocus();
    SwingUtilities.invokeLater(doHelloWorld);
    myFrame.setVisible();

  • How to gain focus to a JTextField in a Jwindow

    Hi Friends
    I am trying to create a Login screen which covers the entire desktop using a Jwindow.
    I have one JTextfield and JPassword field in the Jwindow but i am not able to gain focus to those text fields and not able to type anything in those fields...
    I am using java 1.4.2
    This is my program...
    public class Login implements ActionListener
            JWindow fs;
            JTextField tx1;
            JPasswordField tx2;
             public Login ()
                 fs= new JWindow(new JFrame());
                 tx1= new JTextField(12);
                 tx2= new JPasswordField(12);
                 JButton jb = new JButton();
                 fs.getContentPane().setLayout(new FlowLayout());
                 fs.getContentPane().add(tx1);
                 fs.getContentPane().add(tx2);
                 fs.getContentPane().add(jb);
                 fs.setSize(300,300);
                 fs.setVisible(true);
                 fs.show();
                 fs.toFront();
    public void actionPerformed (ActionEvent e)
         System.out.println("User id "+tx1.getText()+" and Password is : "+tx2.getText()):
    public static void main(String[] args)
        new Login();
         Can some one help me in solving this issue with JWINDOW... Plz dont suggest JFrame , since i am not willing to use that header....
    Thanks in advance
    Ur Friend.

    Swing releated questions should be posted in the Swing forum.
    Check out this posting, found in the Swing forum:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=675445
    Plz dont suggest JFrame , since i am not willing to use that header....
    JFrame.setDefaultLookAndFeelDecorated(false);

  • Custom Document + Array of JTextFields

    Hi,
    I read through the tutorial and managed to get a Custom Document going for my JTextFields (of which i am using quite a few =))
    To cut my code down and aid getting data back from the textfields, I changed them from a page of declarations to a couple of grouped arrays.
    However, now that I have done that, whenever i change the text in one of the textfields, the text in all the textfields in the array change...
    I'm assuming it's something to do with the super.insertString(offs, str, a); that is being called from the Custom Document, but I'm not sure how to fix it up...
    Any help would be most appreciated.
    Cheers
    Andy

    whenever i change the text in one of the textfields, the text in all the textfields in the array change...This means that each text field is using the same document. It's hard to help since you don't post any code. Your code should look something like:
    textField1 = new JTextField()
    textField1.setDocument( new CustomDocument() );
    textField2 = new JTextField()
    textField2.setDocument( new CustomDocument() );

  • Custom text painting using JTextField

    Greetings all!
    I would like to implement a custom JTextField that displays text in gradient colors instead of the usual solid colors.
    I guess I would need to override the default painting mechanism in JTextField, but I'm not sure how to go about it.
    Would appreciate if anyone can give me any suggestions/tips!
    Thanks so much!
    Dora
    public class GradientTextField extends JTextField {
    }

    it will work only if the size of the textfield is large enough (no scrolling).Good point. Here's a newer version that seems to work ok, assuming the text is left justified.
    import java.awt.*;
    import javax.swing.*;
    public class GradientTextField extends JTextField
        private Color from;
        private Color to;
        private Insets insets;
        private Point view = new Point();
        public GradientTextField(Color from, Color to)
            this.from = from;
            this.to = to;
            insets = getInsets();
        public void paintComponent(Graphics g)
            setForeground( getBackground() );
            super.paintComponent(g);
            //  Get the text to paint, assuming left justification
            getInsets( insets );
            view.x = insets.left;
            view.y = insets.top;
            int offset = viewToModel( view );
            String text = getText().substring(offset);
            //  Create the GradientPaint object
            FontMetrics fm = g.getFontMetrics();
            int width = fm.stringWidth( text );
            int x = insets.left;
            int y = fm.getAscent() + insets.top;
            GradientPaint paint = new GradientPaint(x, 0, from, x + width, 0, to);
            //  Use the GradientPaint object to overwrite the existing text
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(paint);
            g2d.drawString(text, x, y);
        public static void main(String[] args)
            JTextField textField = new GradientTextField(Color.blue, Color.green);
            textField.setText("ABCDEFGHIJKLMNOPQRSTUVWZYZ");
            JFrame frame = new JFrame("Gradient Text Field");
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.getContentPane().add(textField, BorderLayout.SOUTH);
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }It's probably not a complete solution, but it may be helpful is specific situations.

Maybe you are looking for

  • Can I convert an apple store gift card into a itunes gift card

    Can I convert an apple store gift card into a itunes gift card. I bought the wrong one.

  • IPhone not recognised by laptop (or connecting to itunes)

    My iphone has recently been repaired with a new dock (since the other was corroded with water damage and would not allow the iphone to charge at all). I got it back today and after updating my itunes, the softwarde on the iphone (to iO6.1.2) and the

  • Call thirty party java web service but always return null

    hi I call a java web service in my application visual studio 2008 c#, but always return NULL. I used Tool Fiddler to monitor the traffic between my client and the web service server, it showed the return is not Null. Here is my code, please see if an

  • Error trying to Buy using shopping cart

    Hi, I added the iTunes Essentials: Green Day - The Basics, to my shopping cart yesterday. When I go to the cart and click Buy, I get the following message: +"Purchase of this item is not currently available. This item is being modified. Please try ag

  • Can't see tooltips anymore

    Until a short while ago I could see a "tooltip" - a display of a name or shortcut, when my cursor was over any given button. I ensured "show tooltips" or somesuch was checked in General tab in User Preferences, but no dice. Thanks for any help.