gpt4 book ai didi

java - 在 JTabbedPane 中禁用的选项卡上单击事件

转载 作者:行者123 更新时间:2023-11-30 07:23:56 25 4
gpt4 key购买 nike

我有一个 JTabbedPane,里面有 5 个选项卡。位置 2,3 和 5 处的选项卡被禁用。我想在单击此禁用选项卡时显示一个 JDialog。我尝试添加鼠标监听器并更改监听器,但对我没有任何帮助。使用鼠标单击方法,我可以获得该选项卡被单击但无法识别特定的选项卡被单击。如何在 JTabbedPane 中禁用的选项卡上获取点击事件?

这是我尝试过的:

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Test {
public static void main(String[] args) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Test tab pane click");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel1 = new JPanel();
panel1.add(new JLabel("HI1"));
tabbedPane.addTab("Tab 1", panel1);
JPanel panel2 = new JPanel();
panel2.add(new JLabel("HI2"));
tabbedPane.addTab("Tab 2", panel2);
JPanel panel3 = new JPanel();
panel3.add(new JLabel("HI3"));
tabbedPane.addTab("Tab 3", panel3);
JPanel panel4 = new JPanel();
panel4.add(new JLabel("HI4"));
tabbedPane.addTab("Tab 4", panel4);
JPanel panel5 = new JPanel();
panel3.add(new JLabel("HI5"));
tabbedPane.addTab("Tab 5", panel5);
frame.setLayout(new BorderLayout());
frame.add(tabbedPane, BorderLayout.CENTER);
frame.setSize(500, 200);
frame.setVisible(true);

// disable 2nd, 3rd and 5th tab.
tabbedPane.setEnabledAt(1, false);
tabbedPane.setEnabledAt(2, false);
tabbedPane.setEnabledAt(4, false);

tabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
System.out.println("I'm not called for disabled tabs.");
}
});
tabbedPane.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("I'm called for disabled tabs, but not able to know which tab is clicked.");
}
});
}
});
}
}

最佳答案

使用鼠标点击方法我可以得到点击了选项卡但无法识别具体点击了哪个选项卡。

您可以使用 JTabbedPaneindexAtLocation(int, int) 方法(MouseEventgetX()getY()),它告诉您包含给定位置的选项卡的索引。

关于java - 在 JTabbedPane 中禁用的选项卡上单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11721579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com