Pregunta

Since we started on the wrong foot, I ask again, previous question deleted. Please check it out, the border of JTextPane IS NOT the same as the border of JTextArea, not by default:

So I need a JTextPane that looks exactly like a JTextArea.

I set the border of the JTextPane to new JTextArea().getBorder();. It looks like it should, however, focus isn't being drawn properly... How do I fix it?

I'm using Nimbus here, if it's any help...

THE SSCCE:

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;


public class Main
{
public static void main(String[] args)
{
    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
    {
        if ("Nimbus".equals(info.getName()))
        {
            try
            {
                UIManager.setLookAndFeel(info.getClassName());
            }
            catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e)

            {
                System.out.println("No Nimbus!");
            }

            break;
        }
    }

    JFrame a = new JFrame("Test");
    a.setSize(200, 400);
    a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    a.getContentPane().setLayout(new BoxLayout(a.getContentPane(), BoxLayout.Y_AXIS));

    JTextPane[] b = new JTextPane[5];

    for (int i = 0; i < 5; i++)
    {
        b[i] = new JTextPane();
        b[i].setBorder(new JTextArea().getBorder());
        b[i].setText(Integer.toString(i));
        a.getContentPane().add(b[i]);
    }

    a.setVisible(true);
}
}

I've set the border to be the same one as on JTextArea, but the focus is not being painted or moved properly. If you comment out that line, there will be no border whatsoever.

¿Fue útil?

Solución

If you add a Focus Listener that forces a repaint, then the strange behvaiour goes away.

Example:

for (int i = 0; i < 5; i++) {
    final JTextPane b = new JTextPane();
    b.setBorder(new JTextArea().getBorder());
    b.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(FocusEvent arg0) {
            b.repaint();
        }

        @Override
        public void focusLost(FocusEvent arg0) {
            b.repaint();
        }

    });
    b.setText(Integer.toString(i));
    a.getContentPane().add(b);
}

This seems like a hack fix, but I am not sure why this is happening.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top