我正在尝试编辑JComboBox,以便在每个单元格中都有一个“删除”按钮(图像/图标)来删除特定条目。 我已经尝试创建一个自定义的CellRenderer,我能够添加图像,但不能对MouseClicks作出反应(至少我不知道单击了哪个图像/单元格),我只能获得X和Y位置。但我不知道图像的位置。
我很感激,如果有人对如何做到这一点有一个想法,我已经尝试了谷歌,但我没有找到任何体面的。
答案 0 :(得分:3)
这可能(?)给你一些想法。
它使用JLayer类来装饰JList并绘制关闭图标(在示例中是一个简单的“X”字符)。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
import javax.swing.plaf.basic.*;
class LayerList extends JPanel
{
LayerList()
{
LayerUI<JComponent> layerUI = new LayerUI<JComponent>()
{
public void paint(Graphics g, JComponent c)
{
super.paint(g, c);
JLayer layer = (JLayer)c;
JList list = (JList)layer.getView();
int selected = list.getSelectedIndex();
if (selected == -1 ) return;
Rectangle area = list.getCellBounds(selected, selected);
g.drawString("X", area.width - 15, area.y + area.height - 3);
}
public void installUI(JComponent c)
{
super.installUI(c);
JLayer jlayer = (JLayer)c;
jlayer.setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
public void uninstallUI(JComponent c)
{
super.uninstallUI(c);
// reset the layer event mask
((JLayer) c).setLayerEventMask(0);
}
@Override
protected void processMouseEvent(MouseEvent e, JLayer l)
{
// e.consume();
if (e.getID() == MouseEvent.MOUSE_RELEASED)
{
JList list = (JList)e.getComponent();
int selected = list.getSelectedIndex();
Rectangle area = list.getCellBounds(selected, selected);
if (e.getX() >= area.width - 15)
{
e.consume();
DefaultComboBoxModel model = (DefaultComboBoxModel)list.getModel();
model.removeElementAt( selected );
list.setSelectedIndex(selected);
}
}
}
};
String[] data = { "a", "b", "c", "d", "e", "f" };
JComboBox<String> comboBox = new JComboBox<String>(data);
Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = (JList)popup.getList();
Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
JScrollPane scrollPane = (JScrollPane)c;
scrollPane.setViewportView( new JLayer<JComponent>(list, layerUI) );
setLayout( new BorderLayout() );
add( comboBox );
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Layer List");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new LayerList() );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
阅读How to Decorate Components with the JLayer Class上Swing教程中的部分,了解有关使用JLayer类的更多信息和示例。
答案 1 :(得分:0)
使用面板构建UI。构建包含标签和按钮的面板(您可以添加图像作为背景)。将此面板作为项目添加到组合框中。
http://www.codejava.net/java-se/swing/create-custom-gui-for-jcombobox