0

I have a JPanel which contains a number of JTextField(s) that have a length limit of a few characters (implemented by a custom PlainDocument).

I want to display a text in red font at the top left of the panel saying, "**Fields allow a max of 20 characters!".

Two options that I am considering so far is adding a TitledBorder or a JLabel. What is the best way to do this?

Thank you.

Vinayak
  • 11
  • 3
  • 4
    *implemented by a custom PlainDocument).* - don't use a PlainDocument. That is an old approach. With Swing you should use a `DocumentFilter`. Read the section from the Swing tutorial on [Implementing a DocumentFilter](https://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter) for a working example that does exactly what you want. I don't know why you need either. I don't see this on forms that I fill out when using the web. The DocumentFilter will "beep" when you reach the maximum. But of the two choices I would use a JLabel. – camickr Aug 16 '20 at 21:55
  • Thank you. I offered to popup a warning dialog with a clear message saying there is a limit of number of chars. Beep was deemed confusing. So, do you suggest that I use DocumentFilter instead of PlainDocument to implement the fixed length validation rule on the textfields? – Vinayak Aug 16 '20 at 22:04
  • Th best way to do this is any way which meets you needs and does the job you want. There are any number of ways you "might" achieve this, [for example](https://stackoverflow.com/questions/25274566/how-can-i-change-the-highlight-color-of-a-focused-jcombobox/25276658#25276658) for a different approach. – MadProgrammer Aug 16 '20 at 22:32

1 Answers1

0

You can add one more JLabel to the TextField, wich you can setVisible, when needed.

JTextField t = new JTextField();
    t.setBounds(0, 0, 200, 75);
    frame.add(t);

    JLabel l = new JLabel();
    l.setText("only 20 Character");
    l.setForeground(Color.red);
    l.setBounds(0, 0, 100, 25);
    t.add(l);

Thats how I would do it.

carlos.gmz
  • 100
  • 8
  • Why are you using 'setBounds'. Your suggestion is pretty reasonable but the usage of setBounds is quite suspect. – matt Aug 18 '20 at 16:16
  • yeah, I probably also could use setSize, because the Position is (0,0). But if you want to set x and y too, you can do it with that. setBounds is just set x, y ,with and height in one. If that was your question. – carlos.gmz Aug 18 '20 at 16:29
  • Why would you set either? – matt Aug 18 '20 at 17:02
  • because if I dont set the size of the Component, it is by default 0px * 0px and you cant see or use the components. You just cant see them, if you dont give them a size. Is that your question – carlos.gmz Aug 18 '20 at 17:05
  • That's not the case for most components, and usually you let your layout manager handle the size. – matt Aug 18 '20 at 17:52
  • oh, I only used swing like 2 times, so i am not that used to layoutManagers, but if it works, you can do it – carlos.gmz Aug 18 '20 at 18:22