我正在尝试以图形方式显示数组,但我遇到了问题。
在我填充数组之前它会穿上“null”,这很好,但是在我填充数组之后,它会覆盖“null”,这使得它难以阅读。
我怎样才能使画布在我填满数组后清理并重绘。
到目前为止,这是我的代码:
public class wordManager extends JFrame
{
String[] array = new String[15];
private BufferedImage buffered;
public wordManager()
{
super("Word Managery");
setSize(300,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics window)
{
if(buffered==null)
buffered = (BufferedImage)(createImage(getWidth(),getHeight()));
Graphics windowTemp = buffered.createGraphics();
int y = 50;
for(int i = 0; i<array.length; i++)
{
windowTemp.drawString(array[i] + "", 10,y);
y+=10;
}
window.drawImage(buffered, 0, 0, null);
}
public void read(String filename) throws IOException
{
String word;
int i = 0;
Scanner file = new Scanner(new File(filename+".txt"));
while(file.hasNext())
{
word = file.next();
array[i] = word;
i++;
}
repaint();
}
public void scramble()
{
for(int i=0;i<array.length;i++)
{
int a = (int) (Math.random()*array.length);
String b = array[i];
array[i] = array[a];
array[a] = b;
}
repaint();
}
public void sort()
{
for (int i = 1; i < array.length; i++)
{
int s = i-1;
for (int j = i; j < array.length; j++)
{
if (array[j].compareTo(array[s]) < 0)
{
s = j;
}
}
String temp = array[i-1];
array[i-1] = array[s];
array[s] = temp;
}
repaint();
}
public void write() throws IOException
{
PrintWriter fileOut = new PrintWriter(new FileWriter("out.txt"));
for(int i = 0; i<array.length; i++)
{
fileOut.println(array[i]);
}
fileOut.close();
}
public void printArray()
{
for(String term : array)
{
System.out.println(term);
}
}
}
public class runner
{
public static void main(String args[]) throws IOException
{
wordManager run = new wordManager();
Scanner keyboard = new Scanner(System.in);
System.out.println("In put file name");
String filename = keyboard.next();
run.read(filename);
System.out.println("");
run.printArray();
System.out.println("");
System.out.println("Enter 1 if you want to sort\n");
System.out.println("Enter 2 if you want to scramble");
int selection = keyboard.nextInt();
if(selection == 1)
{
run.sort();
}
if(selection == 2)
{
run.scramble();
}
run.printArray();
System.out.println("");
run.write();
}
}