Get Random String with Button push
ok, first of all: sorry if my english isn't perfect, but i'm living in a non-english country :D
and here's my problem:
i want to code something like a generator. when you press a button, a random string should appear in a text field. there a re predefinied strings the program can choose from.
i think i also have to say you, that i'm a absolute newbie in java.
here's what i got so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.*;
publicclass FlameGenerator2extends Frame
{
protected TextField Textfeld;
protected Button Druckknopf;
private AktionsAbhoerer einAktionsAbhoerer;
private FensterAbhoerer einFensterAbhoerer;
private FlameGenerator einFlameGenerator;
FlameGenerator()
{
setTitle("[p0rn] FlameGenerator v.0.1");
setSize(400,150);
setContentPane(new ContentPanel("images/ct.jpg"));
setVisible(true);
setLayout(null);
Textfeld =new TextField();
Textfeld.setBounds(25,10,350,25);
add(Textfeld);
Druckknopf =new Button();
Druckknopf.setLabel("FLAME !");
aDruckknopf.setBounds(135,70,130,26);
add(Druckknopf);
einAktionsAbhoerer =new AktionsAbhoerer();
einFensterAbhoerer =new FensterAbhoerer();
Druckknopf.addActionListener(einAktionsAbhoerer);
addWindowListener(einFensterAbhoerer);
}
class Zufall
{
privatevoid test(){
String[] greetings =new String[]{
"test1",
"test2",
"test3",
"test4"
};
int index = intRand(0, greetings.length - 1);
System.out.println(greetings[index]);
}
privateint intRand(int low,int hi){
returnnew Zufall().nextInt(hi - low + 1) + low;
}
class AktionsAbhoerer
implements ActionListener
{
publicvoid actionPerformed(ActionEvent event)
{
Object quelle = event.getSource();
if (quelle == Druckknopf)
test();//Reaktion auf Anzeigen
}
}
class ContentPanelextends JPanel
{
Image bgimage =null;
ContentPanel(String imagename)
{
if(imagename !=null)
{
MediaTracker mt =new MediaTracker(this);
bgimage = Toolkit.getDefaultToolkit().getImage(imagename);
mt.addImage(bgimage, 0);
try
{
mt.waitForAll();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
protectedvoid paintComponent(Graphics g)
{
super.paintComponent(g);
if(bgimage !=null)
{
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
if((imwidth > 0) && (imheight > 0))
{
for(int y = 0; y<getHeight(); y+=imheight)
{
for(int x = 0; x><getWidth(); x+=imwidth)
{
g.drawImage(bgimage, x, y,null);
}
}
}
}
}
}
}
}
i hope that someone can help me with it, coz it doesn't work as it should>
[6294 byte] By [
SheepStara] at [2007-11-26 15:13:09]

Have you tried to use Math.random() for generating a random number between 0.0 and 1.0, multiply it by the largest index of your predefined String array and round to the closest int. Use this result as array index... Something like that.
BTW German looks so odd as a programming language!
public class Test
{
public static void main(String[] args)
{
String[] options = new String[]{"a", "b", "c", "d", "e", "f"}; // list of options
// generate a random number no higher than the list length
int randomSelection = (int)(Math.random()*options.length);
if (randomSelection >= options.length)
{
randomSelection--;
}
System.out.println(options[randomSelection]); // display it
}
}
There you go. Math.random to creates random number <= 1, multiply it by the length of the list. Need to check that the random number is not equal to list length otherwise you'll potentially get an ArrayOutOfBoundsException.
Ted.
Instead of having a separate class handle the action on the button, you can use an anonymous inner class as your action listener. This makes the code easier to read, and removes the need for checking the event source, since no other component will ever use this action listener. I'm afraid I don't speak German, so I am not sure what all your code is supposed to be doing. If I were you, however, I would get rid of the awt code, and use swing only. And instead of using Math.random, I would also use Random() and its nextInt(int max) function.
Druckknopf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
flame.setText(test());
};});
// I moved this method to the FlameGenerator2 class, and changed the signature to static,
// and it now reteurns a String, easier to understand, at least for me
//rnd is declared static at the class level as Random rnd = new Random();
private static String test() {
String[] greetings = new String[] { "test1", "test2", "test3",
"test4" };
int index = rnd.nextInt(greetings.length);
System.out.println(greetings[index]);
return greetings[index];
}
~Tim
ok, thanx for all the replies first.
i still get an error: invalid method declaration; return type required
on line 18 (it's the line where FlameGenerator stands).
here's my new code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.*;
public class FlameGenerator2 extends Frame
{
protected TextField Textfeld;
protected Button Druckknopf;
private AktionsAbhoerer einAktionsAbhoerer;
private FensterAbhoerer einFensterAbhoerer;
private FlameGenerator einFlameGenerator;
FlameGenerator()
{
setTitle("[p0rn] FlameGenerator v.0.1");
setSize(400,150);
setContentPane(new ContentPanel("images/ct.jpg"));
setVisible(true);
setLayout(null);
Textfeld = new TextField();
Textfeld.setBounds(25,10,350,25);
add(Textfeld);
Druckknopf = new Button();
Druckknopf.setLabel("FLAME !");
aDruckknopf.setBounds(135,70,130,26);
add(Druckknopf);
einAktionsAbhoerer = new AktionsAbhoerer();
einFensterAbhoerer = new FensterAbhoerer();
Druckknopf.addActionListener(einAktionsAbhoerer);
addWindowListener(einFensterAbhoerer);
Druckknopf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
flame.setText(test());
};});
}
private static String test() {
String[] greetings = new String[] { "test1", "test2", "test3",
"test4" };
int index = rnd.nextInt(greetings.length);
System.out.println(greetings[index]);
return greetings[index];
}
class AktionsAbhoerer
implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Object quelle = event.getSource();
if (quelle == Druckknopf)
test();//Reaktion auf Anzeigen
}
}
class ContentPanel extends JPanel
{
Image bgimage = null;
ContentPanel(String imagename)
{
if(imagename != null)
{
MediaTracker mt = new MediaTracker(this);
bgimage = Toolkit.getDefaultToolkit().getImage(imagename);
mt.addImage(bgimage, 0);
try
{
mt.waitForAll();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(bgimage != null)
{
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
if((imwidth > 0) && (imheight > 0))
{
for(int y = 0; y<getHeight(); y+=imheight)
{
for(int x = 0; x><getWidth(); x+=imwidth)
{
g.drawImage(bgimage, x, y, null);
}
}
}
}
}
}
}
Message was edited by:
SheepStar>
You really needed to read the code I posted, and understand what it was doing, then adapt it to your specific situation. I changed the names of some of the variables, I changed to implementation to use swing instead of awt, etc.
YOURSMINE
TextField TextFeld -->>JTextField flame
You also did not declare rnd
Here is all my code,
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.util.*;
public class FlameGenerator2 extends JFrame {
protected JTextField flame;
static Random rnd = new Random(System.currentTimeMillis());
protected JButton Druckknopf;
private static FlameGenerator2 einFlameGenerator;
public FlameGenerator2() {
setTitle("[p0rn] FlameGenerator v.0.1");
setBounds(200,200,400, 150);
JPanel pnl = new JPanel();
//setLayout(null);
flame = new JTextField();
flame.setBounds(25, 10, 350, 25);
flame.setPreferredSize(new Dimension(350,25));
Druckknopf = new JButton();
Druckknopf.setText("FLAME !");
Druckknopf.setBounds(135, 70, 130, 26);
pnl.add(Druckknopf, BorderLayout.NORTH);
pnl.add(flame,BorderLayout.SOUTH);
getContentPane().add(pnl);
Druckknopf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
flame.setText(test());
};});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private static String test() {
String[] greetings = new String[] { "test1", "test2", "test3",
"test4" };
int index = rnd.nextInt(greetings.length);
System.out.println(greetings[index]);
return greetings[index];
}
public static void main(String[] args) {
einFlameGenerator = new FlameGenerator2();
}
}
~Tim
Its gotta be declared
public void FlameGenerator(){
}
or if it is an construktor:
public FlameGenerator2(){
}
Message was edited by:
Dingo_no_1
p0rnDruckknopfDruckknopfAktionsAbhoererThis is in no way related to your problem but i just went through your program and these are some of the fields i obtained.I am just a bit inquisitive to know as to where you are from?
yay, it works...thanx a lot guys !!!^^