I keep getting a stack overflow error when I run this short program I made! please help! Right now all it's supposed to do is take the users input and print their position (in X and Y coordinates). I'm not sure what Stack overflow error is or how to fix it.
import java.awt.*;
import javax.swing.*;
public class ExplorerPanel extends JFrame {
ExplorerEvent prog = new ExplorerEvent(this);
JTextArea dataa = new JTextArea(15, 20);
JTextField datain = new JTextField(20);
JButton submit = new JButton("Submit");
JTextField errors = new JTextField(30);
public ExplorerPanel() {
super("Explorer RPG");
setLookAndFeel();
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_…
BorderLayout bord = new BorderLayout();
setLayout(bord);
JPanel toppanel = new JPanel();
toppanel.add(dataa);
add(toppanel, BorderLayout.NORTH);
JPanel middlepanel = new JPanel();
middlepanel.add(datain);
middlepanel.add(submit);
add(middlepanel, BorderLayout.CENTER);
JPanel bottompanel = new JPanel();
bottompanel.add(errors);
add(bottompanel, BorderLayout.SOUTH);
dataa.setEditable(false);
errors.setEditable(false);
submit.addActionListener(prog);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLo…
);
} catch (Exception exc) {
// ignore error
}
}
public static void main(String[] args) {
ExplorerPanel frame = new ExplorerPanel();
}
}
public class ExplorerEvent implements ActionListener, Runnable {
ExplorerPanel gui;
Thread playing;
String command;
String gamedata;
ExplorerGame game = new ExplorerGame();
public ExplorerEvent(ExplorerPanel in) {
gui = in;
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("Submit")) {
startPlaying();
}
}
void startPlaying() {
playing = new Thread(this);
playing.start();
}
void stopPlaying() {
playing = (null);
}
void clearAllFields() {
gui.dataa.setText("");
}
public void run() {
Thread thisThread = Thread.currentThread();
while (playing == thisThread) {
// Game code
game.Game();
}
}
}
public class ExplorerGame {
ExplorerPanel gui = new ExplorerPanel();
String command;
int x = 1;
int y = 1;
public void Game() {
command = gui.submit.getText().toLowerCase();
if (command.equals("east")) {x--;}
else if (command.equals("south")) {y--;}
else if (command.equals("west")) {x++;}
else if (command.equals("north")) {y++;}
System.out.println(x + y);
}
}
In ExplorerGame, you have declared: -
ExplorerPanel gui = new ExplorerPanel();
then, in ExplorerPanel: -
ExplorerEvent prog = new ExplorerEvent(this);
and then again, in ExplorerEvent: -
ExplorerGame game = new ExplorerGame();
This will fill the Stack with recursive creation of objects.
ExplorerGame -> ExplorerPanel -> ExplorerEvent --+
^ |
|____________________________________________|
You want to solve the Issue?
I'll Suggest you: -
Throw away the code, and re-design your application. Having a cyclic dependency in your application is a big loop hole, showing a very poor design.
Related
I am trying to create a slideshow with Java Swing.
I began with implementing a class PicturePanel
public class PicturePanel extends JPanel {
private int counter = 0;
private ImageIcon[] images = new ImageIcon[10];
private JLabel label;
public PicturePanel()
{
for(int i = 0 ; i <images.length;i++)
{
images[counter] = new ImageIcon("check.png");
label = new JLabel();
add(label);
Timer timer = new Timer(100, new TimerListener());
}
}
private class TimerListener implements ActionListener {
public TimerListener() {
}
#Override
public void actionPerformed(ActionEvent ae) {
counter++;
//counter% =images.length;
label.setIcon(images[counter]);
}
}
}
Then I am calling this class in my Jframe through this code :
panProfil= new PicturePanel();
panProfil is a Jpanel in my form
When I run my project, I don't get any errors, but there is nothing in my form. Can someone point me in the right direction?
So you haven't started your Timer that's the problem (as #ItachiUchiha pointed out). But another thing you need to do is know when to stop() the Timer or else it will keep running
You want to start() it in the constructor after you create the Timer. In you ActionListener, to stop it, you'll want to do something like this.
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (counter == images.length) {
((Timer)e.getSource()).stop();
} else {
label.setIcon(images[counter]);
counter++;
}
}
}
If you want to access the Timer from your main GUI class, so you can control it, you want to have a getter for it, and declare it globally
public class PicturePanel extends JPanel {
private Timer timer = null;
public PicturePanel() {
timer = new Timer(1000, new TimerListener());
}
public Timer getTimer() {
return timer;
}
}
Then you can start and stop it from your main GUI class
DrawPanel panel = new DrawPanel();
Timer timer = panel.getTimer();
Also, I don't see the point of create a JLabel every iteration and adding it to the JPanel. You only need one.
public class Project2 {
int c=0;
public static void main(String arg[]) throws InterruptedException {
JFrame login = new JFrame("Login");
// creating a new frame
login.setSize(700, 500);
JPanel addPanel = new JPanel();
JLabel pic = new JLabel();
Project2 p2= new Project2();
String[] list = {"C:\\Users\\divyatapadia\\Desktop\\pic1.jpg", "C:\\Users\\divyatapadia\\Desktop\\benefit.PNG" , "C:\\Users\\divyatapadia\\Desktop\\pic2.jpg"};
pic.setBounds(40, 30, 500, 300);
JButton log = new JButton("SHOW");ImageIcon[] img = new ImageIcon[3];
for(int time = 0;time<3;time++) {
img[time]= new ImageIcon(list[time]);
}
addPanel.add(pic);
addPanel.add(log);
login.add(addPanel);
login.setVisible(true);
try {
log.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Timer t ;
t= new Timer(1000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(p2.c<3) {
pic.setIcon(img[p2.c]);
p2.c++;
}}
});
t.start();
}
}
);
}catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}
I am making a clone of minesweeper with (slightly modified) JButtons. Because there are so many game tiles in minesweeper, I am storing them as an array. When I try and add the buttons to the Frame using a for loop, I get a nullpointerexception on the buttons. The class ButtonObject is extended from the JButton class with just two extra variables and getter/setter methods. What is going wrong?
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Minesweeper extends JFrame implements ActionListener{
JLabel starttitle;
ButtonObject[] minefield;
JFrame frame;
Random r = new Random();
int rand;
JPanel startscreen;
JPanel gamescreen;
int gamesize;
JButton ten;
JButton tfive;
JButton fifty;
GridLayout layout;
public Minesweeper()
{
frame = new JFrame("Minesweeper");
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);;
startscreen = new JPanel();
startScreen();
}
public void startScreen()
{
ten = new JButton("10 x 10");
tfive = new JButton("25 x 25");
fifty = new JButton("50 x 50");
starttitle = new JLabel("Welcome to minesweeper. Click a game size to begin.");
frame.add(startscreen);
startscreen.add(starttitle);
startscreen.add(ten);
startscreen.add(tfive);
startscreen.add(fifty);
ten.addActionListener(this);
tfive.addActionListener(this);
fifty.addActionListener(this);
}
public void initializeGame()
{
minefield = new ButtonObject[gamesize];
for(int i = 0;i<gamesize;i++)
{
minefield[i]=new ButtonObject();
rand = r.nextInt(5);
if(rand==5)
{
minefield[i].setButtonType(true);//this tile is a mine
}
}
}
public void gameScreen()
{
frame.getContentPane().removeAll();
frame.repaint();
initializeGame();
for(int i = 0;i<minefield.length;i++)
{
gamescreen.add(this.minefield[i]);//EXCEPTION HERE
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ten)
{
gamesize = 99;
gameScreen();
}
else if(e.getSource()==tfive)
{
gamesize = 624;
gameScreen();
}
else if(e.getSource()==fifty)
{
gamesize = 2499;
gameScreen();
}
else
{
System.out.println("Fatal error");
}
}
public static void main(String[] args)
{
new Minesweeper();
}
}
Well, you never initialize your gamescreen variable, so that's totally normal you get a NullPointerException at this line.
I'm trying to make something for fun and my components keep disappearing after I press the "ok" button in my gui.
I'm trying to make a "Guess a word" program, where one will get a tip and you can then enter a guess and if it matches it will give you a message and if not, another tip. The problem is, if you enter something that's not the word it will give you a message that it's not the correct word and it will then give you another tip. But the other tip won't show up. They disappear.
I've two classes, "StartUp" and "QuizLogic".
The problem arrives somewhere in the "showTips" method (I think).
If someone would try it themselves a link to the file can be found here: Link to file
Thank you.
public class StartUp {
private JFrame frame;
private JButton showRulesYesButton;
private JButton showRulesNoButton;
private JButton checkButton;
private JPanel mainBackgroundManager;
private JTextField guessEntery;
private QuizLogic quizLogic;
private ArrayList<String> tips;
private JLabel firstTipLabel;
private JLabel secondTipLabel;
private JLabel thirdTipLabel;
// CONSTRUCTOR
public StartUp() {
// Show "Start Up" message
JOptionPane.showMessageDialog(null, "Guess a Word!");
showRules();
}
// METHODS
public void showRules() {
// Basic frame methods
frame = new JFrame("Rules");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(500, 500));
frame.setLocationRelativeTo(null);
// Creates JLabels and adds to JPanel
JLabel firstRule = new JLabel("1. You will get one tip at a time of what the word could be.");
JLabel secoundRule = new JLabel("2. You will get three tips and unlimited guesses.");
JLabel thirdRule = new JLabel("3. Every word is a noun and in its basic form.");
JLabel understand = new JLabel("Are you ready?");
// Creates JPanel and adds JLabels to JPanel
JPanel temporaryRulesPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 100, 60));
temporaryRulesPanel.add(firstRule);
temporaryRulesPanel.add(secoundRule);
temporaryRulesPanel.add(thirdRule);
temporaryRulesPanel.add(understand);
// Initialize buttons
showRulesYesButton = new JButton("Yes");
showRulesNoButton = new JButton("No");
showRulesYesButton.addActionListener(new StartUpEventHandler());
showRulesNoButton.addActionListener(new StartUpEventHandler());
// Creates JPanel and adds button to JPanel
JPanel temporaryButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 100, 35));
temporaryButtonPanel.add(showRulesYesButton);
temporaryButtonPanel.add(showRulesNoButton);
// Initialize and adds JPanel to JPanel
mainBackgroundManager = new JPanel(new BorderLayout());
mainBackgroundManager.add(temporaryRulesPanel, BorderLayout.CENTER);
mainBackgroundManager.add(temporaryButtonPanel, BorderLayout.SOUTH);
//Adds JPanel to JFrame
frame.add(mainBackgroundManager);
frame.setVisible(true);
}
public void clearBackground() {
mainBackgroundManager.removeAll();
quizLogic = new QuizLogic();
showGuessFrame();
showTips();
}
public void showGuessFrame() {
JPanel guessPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 10));
firstTipLabel = new JLabel("a");
secondTipLabel = new JLabel("b");
thirdTipLabel = new JLabel("c");
tips = new ArrayList<String>();
guessEntery = new JTextField("Enter guess here", 20);
checkButton = new JButton("Ok");
checkButton.addActionListener(new StartUpEventHandler());
guessPanel.add(guessEntery);
guessPanel.add(checkButton);
mainBackgroundManager.add(guessPanel, BorderLayout.SOUTH);
frame.add(mainBackgroundManager);
}
public void showTips() {
JPanel temporaryTipsPanel = new JPanel(new GridLayout(3, 1));
temporaryTipsPanel.removeAll();
tips.add(quizLogic.getTip());
System.out.println(tips.size());
if (tips.size() == 1) {
firstTipLabel.setText(tips.get(0));
}
if (tips.size() == 2) {
secondTipLabel.setText(tips.get(1));
}
if (tips.size() == 3) {
thirdTipLabel.setText(tips.get(2));
}
temporaryTipsPanel.add(firstTipLabel);
temporaryTipsPanel.add(secondTipLabel);
temporaryTipsPanel.add(thirdTipLabel);
mainBackgroundManager.add(temporaryTipsPanel, BorderLayout.CENTER);
frame.add(mainBackgroundManager);
frame.revalidate();
frame.repaint();
}
public void getGuess() {
String temp = guessEntery.getText();
boolean correctAnswer = quizLogic.checkGuess(guessEntery.getText());
if (correctAnswer == true) {
JOptionPane.showMessageDialog(null, "Good Job! The word was " + temp);
}
else {
JOptionPane.showMessageDialog(null, temp + " is not the word we are looking for");
showTips();
}
}
private class StartUpEventHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == showRulesYesButton) {
clearBackground();
}
else if (event.getSource() == showRulesNoButton) {
JOptionPane.showMessageDialog(null, "Read the rules again");
}
else if (event.getSource() == checkButton) {
getGuess();
}
}
}
}
public class QuizLogic {
private ArrayList<String> quizWord;
private ArrayList<String> tipsList;
private int tipsNumber;
private String word;
public QuizLogic() {
tipsNumber = 0;
quizWord = new ArrayList<String>();
quizWord.add("Burger");
try {
loadTips(getWord());
} catch (Exception e) {
System.out.println(e);
}
}
public String getWord() {
Random randomGen = new Random();
return quizWord.get(randomGen.nextInt(quizWord.size()));
}
public void loadTips(String word) throws FileNotFoundException {
Scanner lineScanner = new Scanner(new File("C:\\Users\\Oliver Nielsen\\Dropbox\\EclipseWorkspaces\\BuildingJava\\GuessAWord\\src\\domain\\" + word + ".txt"));
this.word = word;
tipsList = new ArrayList<String>();
while (lineScanner.hasNext()) {
tipsList.add(lineScanner.nextLine());
}
}
public String getTip() {
if (tipsNumber >= tipsList.size()) {
throw new NoSuchElementException();
}
String temp = tipsList.get(tipsNumber);
tipsNumber++;
System.out.println(temp);
return temp;
}
public boolean checkGuess(String guess) {
return guess.equalsIgnoreCase(word);
}
}
I figured it out!
I don't know why it can't be done but if I deleted this line: JPanel temporaryTipsPanel = new JPanel(new GridLayout(3, 1));
and placed it in another method it worked. If someone could explain why that would be great but at least I/we know what was the problem.
Thank you. :)
f.e. I have an email client, it receives new message, button with incoming messages starts doing something, until user clicks it to see whats up.
I'm trying to make button attract attention by selecting, waiting and then deselecting it, but this does nothing!
do{
button.setSelected(true);
Thread oThread = new Thread() {
#Override
public void run() {
synchronized (this) {
try {
wait(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
button.setSelected(false);
}
};
oThread.start();
}while(true);
You should use Swing timers for that. Don't interact with GUI objects from foreign threads.
There's some docs in the Java tutorial: How to use Swing timers.
Here's an example way you could do this playing with the button's icon.
// member var
Icon buttonIcon;
Timer timer;
// in constructor for example
buttonIcon = new ImageIcon("resources/icon.png");
button.setIcon(buttonIcon);
timer = new Timer(1000, this);
timer.start();
// in the actionPerformed handler
if (button.getIcon() == null)
button.setIcon(icon);
else
button.setIcon(null);
Your class will need to implement ActionListener for this to work like that. Add some logic to stop the flashing when you need it.
hafl_workaround to your questions
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ShakingButtonDemo implements Runnable {
private JButton button;
private JRadioButton radioWholeButton;
private JRadioButton radioTextOnly;
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new ShakingButtonDemo());
}
#Override
public void run() {
radioWholeButton = new JRadioButton("The whole button");
radioTextOnly = new JRadioButton("Button text only");
radioWholeButton.setSelected(true);
ButtonGroup bg = new ButtonGroup();
bg.add(radioWholeButton);
bg.add(radioTextOnly);
button = new JButton(" Shake with this Button ");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
shakeButton(radioWholeButton.isSelected());
}
});
JPanel p1 = new JPanel();
p1.setBorder(BorderFactory.createTitledBorder("Shake Options"));
p1.setLayout(new GridLayout(0, 1));
p1.add(radioWholeButton);
p1.add(radioTextOnly);
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(0, 1));
p2.add(button);
JFrame frame = new JFrame();
frame.setTitle("Shaking Button Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(p1, BorderLayout.NORTH);
frame.add(p2, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void shakeButton(final boolean shakeWholeButton) {
final Point point = button.getLocation();
final Insets margin = button.getMargin();
final int delay = 75;
Runnable r = new Runnable() {
#Override
public void run() {
for (int i = 0; i < 30; i++) {
try {
if (shakeWholeButton) {
moveButton(new Point(point.x + 5, point.y));
Thread.sleep(delay);
moveButton(point);
Thread.sleep(delay);
moveButton(new Point(point.x - 5, point.y));
Thread.sleep(delay);
moveButton(point);
Thread.sleep(delay);
} else {// text only
setButtonMargin(new Insets(margin.top, margin.left + 3, margin.bottom, margin.right - 2));
Thread.sleep(delay);
setButtonMargin(margin);
Thread.sleep(delay);
setButtonMargin(new Insets(margin.top, margin.left - 2, margin.bottom, margin.right + 3));
Thread.sleep(delay);
setButtonMargin(margin);
Thread.sleep(delay);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
}
private void moveButton(final Point p) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
button.setLocation(p);
}
});
}
private void setButtonMargin(final Insets margin) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
button.setMargin(margin);
}
});
}
}
I have a simple Java program that reads in a text file, splits it by " " (spaces), displays the first word, waits 2 seconds, displays the next... etc... I would like to do this in Spring or some other GUI.
Any suggestions on how I can easily update the words with spring? Iterate through my list and somehow use setText();
I am not having any luck. I am using this method to print my words out in the consol and added the JFrame to it... Works great in the consol, but puts out endless jframe. I found most of it online.
private void printWords() {
for (int i = 0; i < words.size(); i++) {
//How many words?
//System.out.print(words.size());
//print each word on a new line...
Word w = words.get(i);
System.out.println(w.name);
//pause between each word.
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
JFrame frame = new JFrame("Run Text File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel(w.name,SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
I have a window that get's created with JFrame and JLable, however, I would like to have the static text be dynamic instead of loading a new spring window. I would like it to flash a word, disappear, flash a word disappear.
Any suggestions on how to update the JLabel? Something with repaint()? I am drawing a blank.
Thanks!
UPDATE:
With the help from the kind folks below, I have gotten it to print correctly to the console. Here is my Print Method:
private void printWords() {
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListener() {
private Iterator<Word> w = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (w.hasNext()) {
_textField.setText(w.next().getName());
//Prints to Console just Fine...
//System.out.println(w.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
}
However, it isn't updating the lable? My contructor looks like:
public TimeThis() {
_textField = new JTextField(5);
_textField.setEditable(false);
_textField.setFont(new Font("sansserif", Font.PLAIN, 30));
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(_textField);
this.setContentPane(content);
this.setTitle("Swing Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
//_textField.setText("loading...");
}
Getting there... I'll post the fix once I, or whomever assists me, get's it working. Thanks again!
First, build and display your GUI. Once the GUI is displayed, use a javax.swing.Timer to update the GUI every 500 millis:
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListsner() {
private Iterator<Word> it = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (it.hasNext()) {
label.setText(it.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
Never use Thread.sleep(int) inside Swing Code, because it blocks the EDT; more here,
The result of using Thread.sleep(int) is this:
When Thread.sleep(int) ends
Example code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.*;
//http://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java
public class ButtonsIcon extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private Queue<Icon> iconQueue = new LinkedList<Icon>();
private JLabel label = new JLabel();
private Random random = new Random();
private JPanel buttonPanel = new JPanel();
private JPanel labelPanel = new JPanel();
private Timer backTtimer;
private Timer labelTimer;
private JLabel one = new JLabel("one");
private JLabel two = new JLabel("two");
private JLabel three = new JLabel("three");
private final String[] petStrings = {"Bird", "Cat", "Dog",
"Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
private boolean runProcess = true;
private int index = 1;
private int index1 = 1;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ButtonsIcon t = new ButtonsIcon();
}
});
}
public ButtonsIcon() {
iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));
one.setFont(new Font("Dialog", Font.BOLD, 24));
one.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
two.setFont(new Font("Dialog", Font.BOLD, 24));
two.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
three.setFont(new Font("Dialog", Font.BOLD, 10));
three.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelPanel.setLayout(new GridLayout(0, 3, 4, 4));
labelPanel.add(one);
labelPanel.add(two);
labelPanel.add(three);
//labelPanel.setBorder(new LineBorder(Color.black, 1));
labelPanel.setOpaque(false);
JButton button0 = createButton();
JButton button1 = createButton();
JButton button2 = createButton();
JButton button3 = createButton();
buttonPanel.setLayout(new GridLayout(0, 4, 4, 4));
buttonPanel.add(button0);
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
//buttonPanel.setBorder(new LineBorder(Color.black, 1));
buttonPanel.setOpaque(false);
label.setLayout(new BorderLayout());
label.add(labelPanel, BorderLayout.NORTH);
label.add(buttonPanel, BorderLayout.SOUTH);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));
add(label, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
startBackground();
startLabel2();
new Thread(this).start();
printWords(); // generating freeze Swing GUI durring EDT
}
private JButton createButton() {
JButton button = new JButton();
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setIcon(nextIcon());
button.setRolloverIcon(nextIcon());
button.setPressedIcon(nextIcon());
button.setDisabledIcon(nextIcon());
nextIcon();
return button;
}
private Icon nextIcon() {
Icon icon = iconQueue.peek();
iconQueue.add(iconQueue.remove());
return icon;
}
// Update background at 4/3 Hz
private void startBackground() {
backTtimer = new javax.swing.Timer(750, updateBackground());
backTtimer.start();
backTtimer.setRepeats(true);
}
private Action updateBackground() {
return new AbstractAction("Background action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(getImage()));
}
};
}
// Update Label two at 2 Hz
private void startLabel2() {
labelTimer = new javax.swing.Timer(500, updateLabel2());
labelTimer.start();
labelTimer.setRepeats(true);
}
private Action updateLabel2() {
return new AbstractAction("Label action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
two.setText(petStrings[index]);
index = (index + 1) % petStrings.length;
}
};
}
// Update lable one at 3 Hz
#Override
public void run() {
while (runProcess) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
one.setText(petStrings[index1]);
index1 = (index1 + 1) % petStrings.length;
}
});
try {
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Note: blocks EDT
private void printWords() {
for (int i = 0; i < petStrings.length; i++) {
String word = petStrings[i].toString();
System.out.println(word);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
three.setText(word);
}
three.setText("<html> Concurency Issues in Swing<br>"
+ " never to use Thread.sleep(int) <br>"
+ " durring EDT, simple to freeze GUI </html>");
}
public BufferedImage getImage() {
int w = label.getWidth();
int h = label.getHeight();
GradientPaint gp = new GradientPaint(0f, 0f, new Color(
127 + random.nextInt(128),
127 + random.nextInt(128),
127 + random.nextInt(128)),
w, w,
new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setColor(Color.BLACK);
return bi;
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
class TimeThis extends JFrame {
private static final long serialVersionUID = 1L;
private ArrayList<Word> words;
private JTextField _textField; // set by timer listener
public TimeThis() throws IOException {
_textField = new JTextField(5);
_textField.setEditable(false);
_textField.setFont(new Font("sansserif", Font.PLAIN, 30));
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(_textField);
this.setContentPane(content);
this.setTitle("Swing Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
_textField.setText("loading...");
readFile(); // read file
printWords(); // print results
}
public void readFile(){
try {
BufferedReader in = new BufferedReader(new FileReader("adameve.txt"));
words = new ArrayList<Word>();
int lineNum = 1; // we read first line in start
// delimeters of line in this example only "space"
char [] parse = {' '};
String delims = new String(parse);
String line = in.readLine();
String [] lineWords = line.split(delims);
// split the words and create word object
//System.out.println(lineWords.length);
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
line = in.readLine();
in.close();
} catch (IOException e) {
}
}
private void printWords() {
final Timer timer = new Timer(100, null);
ActionListener listener = new ActionListener() {
private Iterator<Word> w = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (w.hasNext()) {
_textField.setText(w.next().getName());
//Prints to Console just Fine...
//System.out.println(w.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
}
class Word{
private String name;
public Word(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static void main(String[] args) throws IOException {
JFrame ani = new TimeThis();
ani.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ani.setVisible(true);
}
}
I got it working with this code... Hope it can help someone else expand on their Java knowledge. Also, if anyone has any recommendations on cleaning this up. Please do so!
You're on the right track, but you're creating the frame's inside the loop, not outside. Here's what it should be like:
private void printWords() {
JFrame frame = new JFrame("Run Text File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel("", SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
for (int i = 0; i < words.size(); i++) {
//How many words?
//System.out.print(words.size());
//print each word on a new line...
Word w = words.get(i);
System.out.println(w.name);
//pause between each word.
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
textLabel.setTest(w.name);
}
}