我正在尝试制作一个简单的颜色处理程序,允许您更改窗口中框的颜色。我通过将一些预设颜色从文件中读取到我专门设置为包含这些值的类中来使用它们。我正在使用数组来包含所有预设值,当我尝试访问该数组的各个元素时,我不断收到空指针异常。这是我第一次尝试使用 java,所以我认为我犯了一个愚蠢的错误。这是我的代码:
package color.sampler;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
public class ColorSampler extends JFrame
{
protected ColorFrame sampler;
public JList colorList;
protected colors [] listOfColors;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
new ColorSampler("ColorSampler");
}
public ColorSampler(String title) throws IOException
{
super(title);
setBounds(100,100,300,300);
addWindowListener(new WindowDestroyer());
sampler = new ColorFrame();
getContentPane().setLayout(null);
getContentPane().add(sampler);
sampler.setBounds(10,10,270,200);
FileInputStream stream = new FileInputStream("C:\\java input\\input.txt");
InputStreamReader reader;
reader = new InputStreamReader(stream);
StreamTokenizer tokens = new StreamTokenizer(reader);
int numColors, counter;
numColors = 11;
counter = 0;
listOfColors = new colors[numColors];
while(tokens.nextToken() != tokens.TT_EOF)
{
listOfColors[counter].name = (String)tokens.sval;
tokens.nextToken();
listOfColors[counter].r = (int)tokens.nval;
System.out.println(listOfColors[counter].r);
tokens.nextToken();
listOfColors[counter].g = (int)tokens.nval;
tokens.nextToken();
listOfColors[counter].b = (int)tokens.nval;
counter++;
}
stream.close();
colorList = new JList();
colorList.addListSelectionListener(new ListHandler());
String colorString[];
colorString = new String[numColors];
for(counter = 0; counter < numColors; counter++)
{
colorString[counter] = listOfColors[counter].name;
}
colorList.setListData(colorString);
getContentPane().add(colorList);
setVisible(true);
// TODO code application logic here
}
private class ListHandler implements ListSelectionListener
{
@Override
public void valueChanged(ListSelectionEvent e)
{
if(e.getSource() == colorList)
{
if(!e.getValueIsAdjusting())
{
int i = colorList.getSelectedIndex();
String s = (String) colorList.getSelectedValue();
System.out.println("Position " + i + " selected: " + s);
}
}
}
}
}
以及我用来存储值的类:
public class colors
{
public int r, g, b;
public String name;
public colors()
{
r = 0;
g = 0;
b = 0;
name = "bob";
}
}
那么,当我尝试访问数组中第一个元素的名称时,我该如何解决这个问题呢?