JTabbedPane实现关闭选项卡
使用 JTabbedPane 的时候,希望在添加了一个选项卡之后可以将其关闭。
如图,鼠标指针移动到 选项卡1 后显示 X:
点击 X 后可以将 选项卡1 关闭:
思路:
- 可以在 选项卡标题 处添加两个标签:lab1 和 lab2。
- lab1 为选项卡的标题。
- lab2 为 X,添加鼠标监视器,鼠标点击关闭选项卡。
将上述两标签放入一个 JPanel 子类中
tabPanel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tabPanel extends JPanel implements MouseListener {
private JTabbedPane pane; // 所在选项卡窗格
private JLabel lab1, lab2;
public tabPanel(String title, JTabbedPane pane) {
this.pane = pane;
lab1 = new JLabel(title);
lab1.setFont(new Font("黑体", Font.PLAIN, 23));
lab1.setHorizontalAlignment(JLabel.LEFT); //设置文字显示在最左边
lab2 = new JLabel();
lab2.setFont(new Font("黑体", Font.PLAIN, 23));
lab2.setHorizontalAlignment(JLabel.RIGHT); //设置文字显示在最左边
lab2.addMouseListener(this);
this.setLayout(new GridLayout(1, 2, 10, 0));
this.add(lab1);
this.add(lab2);
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int confirm = JOptionPane.showConfirmDialog(this.pane, "确认关闭选项卡", "提示", JOptionPane.YES_NO_OPTION);
if (confirm == 0) { this.pane.remove(this.pane.indexOfTabComponent(this)); }
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
this.lab2.setText("X");
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
this.lab2.setText("");
}
@Override
public void mousePressed(MouseEvent e) { }
@Override
public void mouseReleased(MouseEvent e) { }
}
创建窗口,添加选项卡窗格 pane,将 pane 作为参数传入 tabPanel 对象。
MainView.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainView extends JFrame implements ActionListener {
JTabbedPane pane; // 选项卡窗格
public MainView() {
this.setTitle("选项卡窗格");
this.setSize(1000, 700);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
int width = Toolkit.getDefaultToolkit().getScreenSize().width; // 屏幕宽
int height = Toolkit.getDefaultToolkit().getScreenSize().height; // 屏幕高
this.setLocation((width - 1000) / 2, (height-700) / 3); // 设置窗体位置
//添加选项卡窗格
pane = new JTabbedPane(JTabbedPane.TOP);
this.add(pane, BorderLayout.CENTER);
pane.setFont(new Font("黑体", Font.PLAIN, 23));
pane.addTab("", new JPanel());
pane.setTabComponentAt(0, new tabPanel("选项卡1", pane)); // 实现关闭选项卡
pane.addTab("", new JPanel());
pane.setTabComponentAt(1, new tabPanel("选项卡2", pane));
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
Main.java
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
MainView window = new MainView();
}
}
参考文章:
https://blog.csdn.net/xietansheng/article/details/74366541
https://blog.csdn.net/pzhtpf/article/details/7645023