让我们承担,你真的应该使用Swing的API,而不是AWT API片刻(并视为你只是刚开始学习,我认为这是一个体面的假设)。
您可以执行以下操作...
基本上。我有JComboBox
定制ListCellRenderer
和ActionListener
。
ListCellRenderer
以我想要的方式呈现项目以及ActionListener
听众更改组合框。
当选择新项目时,将根据所选项目更改组合框的背景。
这里展示的概念是理解挥杆的关键(和Java一般)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestComboBox08 {
public static void main(String[] args) {
new TestComboBox08();
}
public TestComboBox08() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
final JComboBox cb = new JComboBox();
cb.addItem(new SelectableColor("Red", Color.RED));
cb.addItem(new SelectableColor("Green", Color.GREEN));
cb.addItem(new SelectableColor("Blue", Color.BLUE));
cb.setRenderer(new ColorCellRenderer());
add(cb);
cb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object value = cb.getSelectedItem();
if (value instanceof SelectableColor) {
cb.setBackground(((SelectableColor)value).getColor());
} else {
cb.setBackground(null);
}
}
});
cb.setSelectedItem(null);
}
}
public class SelectableColor {
private String name;
private Color color;
public SelectableColor(String name, Color color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public Color getColor() {
return color;
}
}
public class ColorCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof SelectableColor) {
SelectableColor sc = (SelectableColor) value;
if (!isSelected) {
setBackground(sc.getColor());
setOpaque(true);
}
setText(sc.getName());
}
return this;
}
}
}
你真的应该熟悉Creating A UI with Swing。如果这是你的头,从Trails开始涵盖的基本知识
正如我在你上一篇文章中所建议的,你需要添加一个'Color'对象到组合框,你需要创建一个自定义的渲染器。你不能只添加一个字符串,并期望它神奇地代表一种颜色。 – camickr
为什么使用AWT Choice类而不是Swing JComboBox? –
不要混合轻重量组件,这只会与z排序混淆,并且永远不会结束 – MadProgrammer