I have create a simple code :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class tab extends JFrame
{
JTabbedPane tab=new JTabbedPane();
JTextField input=new JTextField();
JButton button=new JButton("process");
tab()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,600);
setLocation(100,100);
setLayout(new BorderLayout());
add(tab,"Center");
tab.add("code",new JPanel());
tab.add("assembly",new JPanel());
tab.add("compiler",new JPanel());
tab.add("Execution",new JPanel());
tab.add("Structure",new JPanel());
JPanel panel=new JPanel();
add(panel,"South");
panel.setLayout(new BorderLayout());
panel.add(input,"Center");
panel.add(button,"East");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
tab.setSelectedIndex(Integer.parseInt(input.getText()));
}
});
show();
}
public static void main(String[]args)
{
new tab();
}
}
this code, it can selected tab by index.
in my question how to selected tab by finding title. so if I input "compiler" it can select tab that title "compiler".
You can simply iterate over the tabs and find the index of the one with the given name:
public int findTabByName(String title, JTabbedPane tab)
{
int tabCount = tab.getTabCount();
for (int i=0; i < tabCount; i++)
{
String tabTitle = tab.getTitleAt(i);
if (tabTitle.equals(title)) return i;
}
return -1;
}
Then in your code just call findTabByName() passing the user input (and the compoenent) and if the returned index is not -1
you can call tab.setSelectedIndex()
Simple: do your own housekeeping: you create a Map<String, Component> componentsByName
; and whenever you add a component to your TabbedPane, you add that component to that map as well.
Of course, you would want to make that as convenient as possible; so you should do something like:
public class Tab extends JFrame {
private final JTabbedPane tab=new JTabbedPane();
private final Map<String, Component> componentsByName = new HashMap<>();
...
private void addComponentToPaneAndMap(String title, Component component) {
tab.add(title, component);
componentsByName.put(title, component);
}
( well, not only for convenience, but also to make sure that all components that go into your pane also go into the map! )
And then, you simply replace
tab.add("code",new JPanel());
with
addComponentToPaneAndMap("code", new JPanel());
And later on, when you need to access one of the components in your tab; you can do a simple lookup like:
Component someComponent = componentsByName.get("compiler");
Please note:
If you think you will need this more often, it would be even reasonable to create your own subclass of JTabbedPane that uses the above mechanisms and provides corresponding getter methods already.
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