Reputation: 14381
I want to trigger an event whenever the "+" tab is clicked (and no other tabs present). Basically, I want the "+" tab to act like a button. I'm not quite sure which type of listener to use. How can I do this?
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JTPTest extends JTabbedPane {
public JTPTest() {
this.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
System.out.println(changeEvent);
}
});
JPanel blankJPanel = new JPanel();
this.addTab("+", blankJPanel);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new JTPTest());
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Upvotes: 0
Views: 1353
Reputation: 562
Try:
JPanel blankJPanel1 = new JPanel(); this.addTab("+", blankJPanel1);
setModel(new DefaultSingleSelectionModel() {
@Override
public void setSelectedIndex(int index) {
System.out.println("woah!");
}
});
Update
Just an alternative version, without the need of modifying the model behavior.
JPanel blankJPanel = new JPanel(); this.addTab("dummy text", blankJPanel);
JLabel label = new JLabel("x");
label.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("woah!!");
}
});
setTabComponentAt(indexOfComponent(blankJPanel), label);
Update 2 Seems I end up doing something similar to this answer, please refer to it as the "best" solution to this problem.
Upvotes: 1
Reputation: 324128
Read the section from the Swing tutorial on How to Use Tabbed Panes.
One of the examples shows how to add a "Close" button to a tab. You should be able to easily modify the code to add a "+" button.
Upvotes: 2