Add controls to a tab in JTabbedPane in Java
Description
The following code shows how to add controls to a tab in JTabbedPane.
Example
/*from w ww. j a v a 2 s. co m*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Main{
private JFrame frame = new JFrame();
private JTabbedPane tabbedPane = new JTabbedPane();
private JButton addTabButton = new JButton("Add Tab");
private Dimension closeButtonSize;
private int tabCounter = 0;
public Main() {
addTabButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
add();
}
});
frame.add(tabbedPane, BorderLayout.CENTER);
frame.add(addTabButton, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setMinimumSize(new Dimension(300, 300));
frame.setVisible(true);
}
public void add() {
final JPanel content = new JPanel();
JPanel tab = new JPanel(new FlowLayout());
JLabel tabLabel = new JLabel("Tab " + (++tabCounter));
JButton tabCloseButton = new JButton("X");
tabCloseButton.setPreferredSize(closeButtonSize);
tabCloseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int closeTabNumber = tabbedPane.indexOfComponent(content);
tabbedPane.removeTabAt(closeTabNumber);
}
});
tab.add(tabLabel);
tab.add(tabCloseButton);
tabbedPane.addTab(null, content);
tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, tab);
}
public static void main(String[] args) {
new Main();
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »