newbie newbie - 2 months ago 12
Java Question

Select tab by title

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".

Answer

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()