gpt4 book ai didi

java - 监听 JTabbedPane 中图标/标题的变化

转载 作者:行者123 更新时间:2023-12-02 05:11:23 25 4
gpt4 key购买 nike

Swing 中有没有一种方法可以让我们监听 JTabbedPane 中图标/标题更改等事件?

编辑1:

根据MadProgrammer的建议尝试添加 propertyChangeListener 但未通知图标更改。

我尝试的代码如下:

final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String property = evt.getPropertyName();
System.out.println("property -> " + property);
}
});

tabbedPane.insertTab("title", someIcon, null, null, 0);

final JButton changeIconBtn = new JButton("Change Icon");
changeIconBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
tabbedPane.setIconAt(0, newIcon);
}
});

如果我尝试按更改图标按钮,则不会调用监听器。

我做错了什么吗?

最佳答案

正如MadProgrammer所说,您可以使用AccessibleContextaddPropertyChangeListener(PropertyChangeListener)方法:

import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;

public class TabbedPaneAccessibleTest {
public JComponent makeUI() {
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.getAccessibleContext().addPropertyChangeListener(
new PropertyChangeListener() {
@Override public void propertyChange(PropertyChangeEvent evt) {
String property = evt.getPropertyName();
System.out.println("property -> " + property);
if (evt.getOldValue() instanceof Icon
&& evt.getNewValue() instanceof Icon) {
System.out.println("New Icon: " + evt.getNewValue());
}
}
});
Icon someIcon = UIManager.getIcon("OptionPane.errorIcon");
Component c = Box.createRigidArea(new Dimension(320, 240));
tabbedPane.insertTab("title", someIcon, c, null, 0);

JButton changeIconBtn = new JButton(new AbstractAction("Change Icon") {
@Override public void actionPerformed(final ActionEvent e) {
Icon newIcon = UIManager.getIcon("OptionPane.warningIcon");
tabbedPane.setIconAt(0, newIcon);
}
});

JPanel p = new JPanel(new BorderLayout());
p.add(new JScrollPane(tabbedPane));
p.add(changeIconBtn, BorderLayout.SOUTH);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TabbedPaneAccessibleTest().makeUI());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

关于java - 监听 JTabbedPane 中图标/标题的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27309502/

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