JComboBox中如何加JLabel
问题如题,我在JComboBox中加的JLabel是重画过的。
不考虑重画,就在JComboBox中如何加JLabel。如有达人,不胜感激!
------解决方案--------------------具体要实现什么效果
------解决方案--------------------啥意思?加到什么位置?怎么显示
------解决方案--------------------package test;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxTest extends JFrame {
private JComboBox comboBox;
public ComboBoxTest() {
String colors[] = { "一年级", "二年级","三年级" };
comboBox = new JComboBox(colors);
ComboBoxRenderer renderer = new ComboBoxRenderer();
comboBox.setRenderer(renderer);
renderer.setPreferredSize(new Dimension(40, 15));
comboBox.setEditable(true);
comboBox.setEditor(new ComboBoxEditorExample());
Container con = getContentPane();
JPanel panel = new JPanel();
panel.add(comboBox);
con.add(panel);
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]) {
new ComboBoxTest();
}
}
class ComboBoxRenderer extends JLabel implements ListCellRenderer {
public ComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof String)
setText((String)value);
return this;
}
}
class ComboBoxEditorExample extends JLabel implements ComboBoxEditor {
public ComboBoxEditorExample() {
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
}
public void setItem(Object anObject) {
if (anObject != null && anObject instanceof String)
setText((String) anObject);
/
}
public Component getEditorComponent() {
return this;
}
public Object getItem() {
return getText();
//return getBackground();
}
public void selectAll() {
}
public void addActionListener(ActionListener e) {
}
public void removeActionListener(ActionListener e) {
}
}