Method to say what jpanel is shown at the moment in a jtabbedpane

238 views Asked by At

I don't find the method that say what jpanel is showed at the moment, what I see on the screen at the moment. I try isShowing() , hasFocus() , isEnabled() but never that works. Thanks at all.

1

There are 1 answers

1
Madhawa Priyashantha On BEST ANSWER

you can use getSelectedComponent() or getSelectedIndex() to get currently active panel on jtabbed pane. consider following example this will set color of currently active panel to yello when click the button

public class JTabbedPaneDemo extends JFrame {

    public JTabbedPaneDemo() {
        JButton button = new JButton("color");
        JPanel mainpanel = new JPanel();
        JTabbedPane jtbExample = new JTabbedPane();
        JPanel jplInnerPanel1 = new JPanel();
        jtbExample.addTab("t1", jplInnerPanel1);
        jtbExample.setSelectedIndex(0);
        JPanel jplInnerPanel2 = new JPanel();
        jtbExample.addTab("t2", jplInnerPanel2);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jtbExample.getSelectedComponent().setBackground(Color.yellow);
            }
        });
        setLayout(new GridLayout(1, 1));
        mainpanel.setLayout(new BorderLayout());
        mainpanel.add(jtbExample, BorderLayout.CENTER);
        mainpanel.add(button,BorderLayout.NORTH);
        this.setContentPane(mainpanel);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new JTabbedPaneDemo();
    }
}

and for your comment

myPane.getSelectedComponent() will return active component .and getSelectedComponent() return component object .so there is no method getComponents() in component class.if you are going to get all components in jpnel then you have to cast returned component to a jpanel before call getComponents() example

Component[] c=((JPanel)jtbExample.getSelectedComponent()).getComponents();

for your comment 2

if you want to verify that active one is jpanel1 then cast to jpanel and check like follow.make sure you have declared jPanel12 as a field variable.

if((JPanel)jTabbedPane2.getSelectedComponent()==jPanel12){
     System.out.println("jPanel12 is active");
}