Hy,
ich habe folgenden Code,
Im Konstruktor setze ich die Hashmap:
jedoch ist danach die Variable im CellRenderer leer:
gibt null - 0 zurück.
Der Konstruktor wird doch als erstes aufgerufen und die Variablen-Werte werden auch erfolgreich gesetzt. Warum sind diese später nicht mehr verfügbar?
ich habe folgenden Code,
Java:
public class meinProg {
private JFrame frame;
private Map<String, Color> myColors = new HashMap<String, Color>();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
meinProg window = new meinProg();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public meinProg() {
myColors.put("Eintrag 1", Color.RED);
myColors.put("Eintrag 2", Color.red);
myColors.put("Eintrag 3", Color.black);
// myColors enthält nun Einträge
System.out.println(myColors.size());
initialize();
}
private String[] getKeysOfHashmap(Map<String, Color> algoColors2) {
String[] ret = new String[algoColors2.size()];
int index = 0;
Iterator it = algoColors2.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
ret[index] = (String) pairs.getKey();
index++;
it.remove();
}
return ret;
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 656, 501);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JList list = new JList();
list.setModel(new AbstractListModel() {
String[] values = getKeysOfHashmap(myColors);
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
list.setCellRenderer(new ListAlgoCellRenderer() {
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
setText(value.toString());
if (isSelected) {
setBackground(Color.blue);
} else {
setBackground(Color.white);
}
// Hier ist myColors leer, warum?
System.out.println(myColors.get(value.toString()) + " - "
+ myColors.size());
return this;
}
});
list.setBounds(42, 48, 154, 93);
frame.getContentPane().add(list);
}
}
Im Konstruktor setze ich die Hashmap:
Java:
myColors.put("Eintrag 1", Color.RED);
myColors.put("Eintrag 2", Color.red);
myColors.put("Eintrag 3", Color.black);
jedoch ist danach die Variable im CellRenderer leer:
Java:
System.out.println(myColors.get(value.toString()) + " - "
+ myColors.size());
Der Konstruktor wird doch als erstes aufgerufen und die Variablen-Werte werden auch erfolgreich gesetzt. Warum sind diese später nicht mehr verfügbar?