I have 2 classes, mainFrame and panel. By clicking the button on mainFrame I call panel from another class and set it in tabbed pane which is in JFrame (mainFrame class). Now, I have another button (btnRemove) on my panel in panel class. So when I click that button I want to remove my panel from tabbed pane in mainFrame class. How do I write my listener properly?
mainFrame class:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MainFrame extends JFrame {
JTabbedPane tPane = new JTabbedPane();
JButton btn = new JButton("Add panel");
public MainFrame(){
setSize(400,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
add(tPane, BorderLayout.CENTER);
add(btn,BorderLayout.NORTH);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
panel p = new panel();
tPane.add("Panel",p);
}
});
}
public static void main(String[] args){
new MainFrame();
}
}
panel class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Panel extends JPanel{
JButton btnRemove = new JButton("Remove panel");
public Panel(){
setLayout(new FlowLayout());
add(btnRemove);
btnRemove.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
}
}
If you want the code to keep working even if you nest the button inside a sub-panel, you should use the follwoing:
Side note: please respect Java naming conventions: classes start with upper-case letters.