讓我們承擔,你真的應該使用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