I'm trying now for a couple of hours to optimize my user interface but I'm not getting any further right now. I got a JTabbedPane to show datasets. There is one textfield in there with should also represent the tabs title. Right now there is a button labeled "save" which does nothing else but read this text field from the current tab and updates the tabs title. I'd love to replace this by updating the tab's title when the field is changed. I got the event listener up and running, so no problems here, but how to I get to call the JTabbedPane object? I tried to put a JTabbedPane variable into my JPanel class and store a reference here, but this keeps crashing the moment I call the setter for this variable... Well, not actually crashing, but it throws an exception:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
[...]
The setter is quite simple:
public void setTabContainer(JTabbedPane cont){
container = cont;
}
Any ideas?
In Swing, JTabbedPane is simply a specialized container. Each tab has a name. To add a tab to the JTabbedPane , simply call addTab() . You'll need to specify the name of the tab as well as a component that supplies the tab's contents.
To disable a tab in a JTabbedPane container, use the setEnabledAt() method and set it to false with the index of the tab you want to disable.
To Create Tabbed Panes. To create a tabbed pane, instantiate JTabbedPane , create the components you wish it to display, and then add the components to the tabbed pane using the addTab method.
I got the event listener up and running, so no problems here, but how to I get to call the JTabbedPane object?
You can use SwingUtilities
class as follows to get the tabbed pane that is the ancestor of your text field:
JTabbedPane tabbedPane = (JTabbedPane)SwingUtilities.getAncestorOfClass(JTabbedPane.class, textField);
Then you can iterate over the tabbed pane's components in order to find the index where your text field is placed and finally update the tab's title:
for(int i = 0; i < tabbedPane.getTabCount(); i++) {
if(SwingUtilities.isDescendingFrom(textField, tabbedPane.getComponentAt(i))) {
tabbedPane.setTitleAt(i, textField.getText());
break;
}
}
See the API for:
Try:
JTabbedPane tabbedPane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, this);
tabbedPane.setTitleAt(tabbedPane.indexOfTabComponent(this), title);
Assumes that this
is the tab component, and title
is the new title. Note that you must have set this
as the content for the tab.
Uses:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With