JTabbedPane如切换卡一般,大大的优化了布局,方便用户操作。Java默认的JTabbedPane添加tab时只会显示一个标题,咱们这里来给它实现关闭按钮,当鼠标移上这个tab时,便显示关闭按钮,移除时,便隐藏。也没什么好说的,实现代码如下:
import java.awt.GridLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JLabel; import javax.swing.JPanel; public class addTab implements MouseListener{ JPanel jp; JLabel lab ; JLabel lab3=new JLabel(); public addTab(){ lab= new JLabel("选项卡1"); JLabel lab1 = new JLabel("选项卡"); jp=new JPanel(); GridLayout gl= new GridLayout(1,1,10,0); jp.setLayout(gl); lab1.setHorizontalAlignment(JLabel.LEFT);//设置文字显示在最左边 lab3.setHorizontalAlignment(JLabel.RIGHT);// 设置文字显示在最右边 jp.add(lab1); jp.add(lab3); tab.pane.addTab("i",lab); tab.pane.setTabComponentAt(tab.pane.indexOfComponent(lab),jp);//实现这个功能的就这一条最重要的语句 lab3.addMouseListener(this); } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub tab.pane.remove(tab.pane.indexOfTabComponent(jp)); } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub lab3.setText("x "); } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub lab3.setText(""); } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }
主方法类调用这个类:
import java.awt.event.*; import javax.swing.*; public class tab extends JFrame implements ActionListener{ JMenuItem mi; staticJTabbedPane pane; public tab() { super("选项卡窗格"); setVisible(true); setSize(800,600); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mi=new JMenuItem("增加"); JMenu menu=new JMenu("增加"); menu.add(mi); JMenuBar bar=new JMenuBar(); bar.add(menu); setJMenuBar(bar); pane = new JTabbedPane(); add(pane); new addTab(); mi.addActionListener(this); } public static void main(String[] args) throws Exception { new tab(); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==mi){ new addTab(); } } }
实现效果图:
当鼠标移动到第二个选项卡上,便显示出“X”(没有截取到鼠标箭头):
关闭第二个选项卡: