import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JClosableTabbedPane extends JTabbedPane implements MouseListener {
public JClosableTabbedPane() {
super();
addMouseListener(this);
}
public void addTab(String title, Component component) {
this.addTab(title, component, null);
}
public void addTab(String title, Component component, Icon extraIcon) {
super.addTab(title, new CloseTabIcon(extraIcon), component);
}
public void mouseClicked(MouseEvent e) {
int tabNumber = this.getSelectedIndex();
if (tabNumber < 0)
return;
Rectangle rect = ( (CloseTabIcon) getIconAt(tabNumber)).getBounds();
if (rect.contains(e.getX(), e.getY())) {
this.remove(tabNumber);
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
class CloseTabIcon implements Icon {
private int x_pos;
private int y_pos;
private int width;
private int height;
private Icon fileIcon;
public CloseTabIcon(Icon fileIcon) {
this.fileIcon = fileIcon;
width = 16;
height = 16;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
this.x_pos = x;
this.y_pos = y;
Color col = g.getColor();
g.setColor(Color.black);
int y_p = y + 2;
g.drawLine(x + 1, y_p, x + 12, y_p);
g.drawLine(x + 1, y_p + 13, x + 12, y_p + 13);
g.drawLine(x, y_p + 1, x, y_p + 12);
g.drawLine(x + 13, y_p + 1, x + 13, y_p + 12);
g.drawLine(x + 3, y_p + 3, x + 10, y_p + 10);
g.drawLine(x + 3, y_p + 4, x + 9, y_p + 10);
g.drawLine(x + 4, y_p + 3, x + 10, y_p + 9);
g.drawLine(x + 10, y_p + 3, x + 3, y_p + 10);
g.drawLine(x + 10, y_p + 4, x + 4, y_p + 10);
g.drawLine(x + 9, y_p + 3, x + 3, y_p + 9);
g.setColor(col);
if (fileIcon != null) {
fileIcon.paintIcon(c, g, x + width, y_p);
}
}
public int getIconWidth() {
return width + (fileIcon != null ? fileIcon.getIconWidth() : 0);
}
public int getIconHeight() {
return height;
}
public Rectangle getBounds() {
return new Rectangle(x_pos, y_pos, width, height);
}
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch (Exception e) {
e.printStackTrace();
}
JClosableTabbedPane pane = new JClosableTabbedPane();
ImageIcon icon = new ImageIcon("");
pane.addTab("tab1",new JButton("按钮1"),icon);
pane.addTab("tab2",new JButton("按钮2"),icon);
pane.addTab("tab3",new JButton("按钮3"),icon);
pane.addTab("tab4",new JButton("按钮4"),icon);
JFrame frame = new JFrame("Demo");
frame.getContentPane().add(pane,BorderLayout.CENTER);
frame.setSize(500,300);
frame.setLocation(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
上面的程序在关闭一个tab时发生了异常(你可以试试看先关闭tab4,再关闭tab3),看不出有什么问题,麻烦大家帮帮忙,谢谢.
PS:异常我就不贴出来了,你可以拷到机子上运行试试看,3q