"what I am trying to do is have an array or similar of strings to chose from and have it display a random string from the array"
I'm not sure how you want you want to randomly choose the word, but in the code below, what I do is use a Timer
whose registered listener's callback, gets a random index of a List
of Strings. There is already a word
variable, so I just make word = list.get(randomIndex);
then call repaint()
. You can easily do something similar with the press of a button or something.
private List<String> list = new ArrayList<>();
private Random random = new Random(System.currentTimeMillis());
private String word;
public StringPanel() {
for (int i = 1; i <= 100; i++) {
list.add("Word " + i);
}
word = list.get(0);
Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int rand = random.nextInt(list.size());
word = list.get(rand);
repaint();
}
});
timer.start();
}
....
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
...
g.drawString(word, x, y);
}

Here's the complete code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class TestRandomString {
public TestRandomString() {
JFrame frame = new JFrame("Test Card");
frame.setContentPane(new StringPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public class StringPanel extends JPanel {
private static final int D_H = 500;
private static final int D_W = 500;
private int x = 50;
private int y = 50;
private List<String> list = new ArrayList<>();
private Random random = new Random(System.currentTimeMillis());
private String word;
Font font = new Font("impact", Font.PLAIN, 28);
int wordWidth;
int wordHeight;
public StringPanel() {
for (int i = 1; i <= 100; i++) {
list.add("Word " + i);
}
word = list.get(0);
Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int rand = random.nextInt(list.size());
word = list.get(rand);
x = random.nextInt(D_W - wordWidth);
y = random.nextInt(D_H) + wordHeight;
repaint();
}
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
FontMetrics fm = g.getFontMetrics(font);
wordWidth = fm.stringWidth(word);
wordHeight = fm.getAscent();
g.setFont(new Font("impact", Font.PLAIN, 28));
g.setColor(Color.BLUE);
g.drawString(word, x, y);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(D_H, D_W);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestRandomString();
}
});
}
}