Reputation: 4283
I can set the title for a titled border for a JTextField
c
easily enough.
c.setBorder(BorderFactory.createTitledBorder(title));
The documentation says to use getTitle()
to find the contents of the title, but I can't find any example or working combination of what seems natural. None of the below will even compile:
c.getBorder().getTitle();
c.getTitle();
Border b = null;
...
b = BorderFactory.createTitledBorder(new LineBorder(BLACK, 2),title);
c.setBorder(b);
b = c.getBorder();
b.getTitle();
How do I get the String contents of the title of a JTextField
whose border type is createTitledBorder
?
Upvotes: 0
Views: 385
Reputation: 2309
The border type is not createTitledBorder
. That is just the name of the static factory method you are using. It returns a TitledBorder
. Calling getBorder()
on the JTextField only returns a border of type Border
, which does not have the getTitle()
method, since not all borders have titles.
You need to have a reference to the border that is of type TitledBorder
so that Java knows that the border has a title:
TitledBorder b = null;
...
b = BorderFactory.createTitledBorder(new LineBorder(BLACK, 2),title);
c.setBorder(b);
b = (TitledBorder)c.getBorder();
b.getTitle();
or, if you don't want to keep a reference of type TitledBorder
, you could do this:
Border b = null;
...
b = BorderFactory.createTitledBorder(new LineBorder(BLACK, 2),title);
c.setBorder(b);
b = c.getBorder();
( (TitledBorder)b ).getTitle();
EDIT
Here is a less verbose way of doing what you have done in your posted answer:
Border b;
String title;
b = c.getBorder();
if(b instanceof TitledBorder)
{
title = ( (TitledBorder)b ).getTitle();
}
Upvotes: 1
Reputation: 4283
This worked:
Border b;
TitledBorder tb;
String title;
b = c.getBorder();
if(b instanceof TitledBorder)
{
c.getBorder();
tb = (TitledBorder)c.getBorder();
title = tb.getTitle();
}
No matter what type of border c
has, IF it's TitledBorder
, I get the title as advertised. If not, proceed as usual.
Thanks, gla3dr, for the tip.
Does anyone see a less verbose way of accomplishing the task?
Upvotes: 0
Reputation: 253
Try something like
TitledBorder border = BorderFactory.createTitledBorder("Title");
c.setBorder(border);
You could then call the getTitle method using something like
System.out.println(border.getTitle());
Upvotes: 1