gpt4 book ai didi

java - 如何阻止 JPopupMenu show() 在视觉上取消选择单击的列表项

转载 作者:行者123 更新时间:2023-12-02 08:34:56 26 4
gpt4 key购买 nike

现在,当用户右键单击程序中选定的 JList 项时,生成的 JPopupMenu 会清除选择(至少在视觉上),直到弹出菜单关闭。这与我所知道的任何平台的原生外观和感觉都不一致。该项目应保持视觉选定状态或周围有选定颜色的边框。但我在 API 中找不到任何有关弹出菜单更改选择外观的内容。有什么办法可以控制这种行为吗?

最佳答案

您如何实现显示弹出窗口的鼠标监听器?我创建了一个测试应用程序来演示我通常期望的列表选择和弹出菜单的行为。在使用 Java 1.5/6 的 Windows 上,此行为正确。

也许这会帮助您解决您的特定问题。

package jlist;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Test extends JPanel implements ListSelectionListener {
private static final String ACTION_FEED = "Feed";
private JList list;
private JPopupMenu menu;
// Initialise a JList and add to JPanel.
public Test() {
super(new BorderLayout());
list = new JList(new Object[]{"Badger", "Ferret", "Stoat", "Weasel"});
initActions();
list.addListSelectionListener(this);
// Add mouse listener
list.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) showPopup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) showPopup(e);
}
private void showPopup(MouseEvent e) {
menu.show(e.getComponent(), e.getX(), e.getY());
}
});
add(new JScrollPane(list), BorderLayout.CENTER);
valueChanged(null);
}

// Triggered when List Selection changes. Used to control Actions enabled state.
public void valueChanged(ListSelectionEvent e) {
boolean selected = list.getSelectedValue() != null;
getActionMap().get(ACTION_FEED).setEnabled(selected);
}

// Initialise Actions and Popup Menu
private void initActions() {
menu = new JPopupMenu();
Action feed = new AbstractAction(ACTION_FEED) {
public void actionPerformed(ActionEvent e) {
String value = (String) list.getSelectedValue();
JOptionPane.showMessageDialog(Test.this, "Fed " + value);
}
};
getActionMap().put(ACTION_FEED, feed);
menu.add(feed);
}

public static void main(String [] args) {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new Test());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}

关于java - 如何阻止 JPopupMenu show() 在视觉上取消选择单击的列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2157345/

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