Loop to Create Buttons
I need to create two classes within a larger class. One that take info from a text file in the format: String:double
String:double
...
and outputs the two variables. And a second class that takes this information a开发者_运维百科nd loops, creating buttons with each text entry as the label. My code so far is:
public class MainClass {
Scanner readFile = new Scanner(new File("text.txt"));
while (fileScanner.hasNext()) {
String name = readFile.next();
double value = readFile.nextDouble();
}
class Button {
Button(String text. double number) {
this.text=text;
this.number=number;
}
}
}
How do I go from here?
Not an answer but here's the OP's code modified so it compiles
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JButton;
public class MainClass {
class ScanFile {
void Foo() throws FileNotFoundException{
Scanner readFile = new Scanner(new File("text.txt")); // don't forget to catch FileNotFoundException!
readFile.useDelimiter(":|\\n");
while (readFile.hasNext()) {
String name = readFile.next();
double value = readFile.nextDouble();
System.out.println(name + " " + value);
}
}
}
class Button extends JButton {
String text;
double number;
Button(String text, double number) {
super(text);
this.text=text;
this.number=number;
}
}
}
@James, making buttons, while not difficult, does require a working knowledge of Java (because you also have to know how to create Frames, Panels, ActionListeners, and handle Events when your buttons are clicked--enough material to fill a textbook alone!).
If you're only interested in making some buttons in a window, the following tutorials should give you an idea of how to make a rudimentary frame with buttons:
http://download.oracle.com/javase/tutorial/uiswing/components/frame.html
http://download.oracle.com/javase/tutorial/uiswing/components/button.html
But to make it display exactly as you want it to (and using a loop!) is going to require a lot of thinking on your part.
精彩评论