How to change the JTextField values inside a loop - java

I need some help with my program. I'm trying to make a brute force program as a project and I don't know how to make the loop values appear in the JTextField in the print () method. I don't just need the final value of the loop. I know this question has been asked a lot and I've tried everything but it's just not working. Please can anyone help me? I'll appreciate it !
public class BF implements ActionListener {
private JPanel contentPane;
private JTextField password;
private JTextField length;
public JTextField generateField;
JRadioButton numbers;
JButton generate;
JLabel passwordfound;
JLabel timelabel;
int min;
int max;
int stringLength;
private int[] chars;
String n="";
char[] passCom;
JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BF frame = new BF();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public BF() {
frame = new JFrame ("Brute Force Attack Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 754, 665);
frame.setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.setLocationRelativeTo(null);
frame.setContentPane(contentPane);
contentPane.setLayout(null);
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
backgroundPanel panel = new backgroundPanel();
panel.setBounds(0, 0, 749, 633);
contentPane.add(panel);
panel.setLayout(null);
generate = new JButton("Find Password");
generate.setFont(new Font("Tahoma", Font.BOLD, 15));
generate.setBounds(292, 401, 145, 35);
generate.addActionListener(this);
panel.add(generate);
generateField = new JTextField();
generateField.setForeground(Color.WHITE);
generateField.setFont(new Font("Tahoma", Font.BOLD, 24));
generateField.setEditable(false);
generateField.setBounds(315, 449, 186, 54);
generateField.setBackground(new Color(0,0,0,0));
generateField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
panel.add(generateField);
generateField.setColumns(10);
frame.setVisible(true);
}
public void run(char min, char max, int len)
{
this.min = min;
this.max = max;
this.stringLength = len;
chars = new int[stringLength + 1];
Arrays.fill(chars, 1, chars.length, min);
while (chars[0] == 0&&!n.equals(password.getText()))
{
print();
increment();
n=String.valueOf(passCom);
}
}
public void increment()
{
for (int i = chars.length - 1; i >= 0; i--)
{
if (chars[i] < max)
{
chars[i]++; return;
}
chars[i] = min;
}
}
public void print()
{
int x=0;
for (int i = 1; i < chars.length; i++)
{
passCom[x]=(char)chars[i];
x++;
String txt = new String (passCom);
generateField.setText(txt);
}
}
#Override
public void actionPerformed(ActionEvent e) {
if (!password.getText().equals("") && e.getSource() == generate && !length.getText().equals("")&&numbers.isSelected()){
int count = Integer.parseInt(length.getText());
passCom = new char [count];
run('0','9',count);
}
}
}

For example, the string 123 has length 3 so the permutations can be 000,001,002 etc
Then why only display one at t time?
Instead I would use a JTextArea and append each value to the text field so all values are visible at the same time. Nobody is going to remember all the values if you display one at a time.
Otherwise, you would use a Swing Timer to display one at a time.

Related

Java repaint() not working when called from a different class

My repaint works when called in the same class but not from another class. I haven't been able to find this issue elsewhere. I have put my code below. Thank you! The code is for making a calculator in a JFrame with 2 JPanels, one showing the user's input and one with all the buttons. I want to call repaint so the drawString() method changes as the user enters their input.
public class Calculator
{
public static void main(String[] args)
{
Calculator c = new Calculator();
}
public Calculator()
{
JFrame frame = new JFrame("Calculator");
frame.setSize(800, 800);
frame.setResizable(false);
Buttons b = new Buttons();
Display d = new Display();
frame.setLayout(new GridLayout(2, 1));
frame.add(d);
frame.add(b);
frame.setVisible(true);
}
public class Buttons extends JPanel implements ActionListener
{
private int z;
public JButton[] buttons;
public Display d;`enter code here`
public String[] values;
public String clickedButton;
public Buttons()
{
setBackground(Color.BLACK);
setLayout(new GridLayout(5, 4));
values = new String[100];
for(int i = 0; i < values.length; i++)
{
values[i] = new String("");
}
addButtons();
}
public void addButtons()
{
Font courier = new Font("Courier", Font.BOLD, 20);
buttons = new JButton[20];
for(int i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(Integer.toString(i));
buttons[i].setBackground(Color.BLUE);
buttons[i].setForeground(Color.WHITE);
buttons[i].setFont(courier);
buttons[i].setFocusable(false);
buttons[i].addActionListener(this);
buttons[i].setBorder(BorderFactory.createLineBorder(new Color(0, 100, 175, 255)));
add(buttons[i]);
}
buttons[10].setVisible(false);
buttons[10].setEnabled(false);
buttons[11].setVisible(false);
buttons[11].setEnabled(false);
buttons[12].setText("C");
buttons[13].setText("+");
buttons[14].setText("-");
buttons[15].setText("*");
buttons[16].setText("/");
buttons[17].setText("+/-");
buttons[18].setText("^");
buttons[19].setText("=");
}
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
d = new Display();
for(int i = 0; i < 10; i++)
{
if(action.equals(Integer.toString(i)))
{
values[d.i]+=Integer.toString(i);
System.out.println("should be repainting");
d.repaint();
}
}
}
}
public class Display extends JPanel
{
public Buttons b;
public Font courier;
public int i;
public Display()
{
i = 0;
b = new Buttons();
setBackground(Color.BLACK);
courier = new Font("Courier", Font.BOLD, 50);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
g.setFont(courier);
g.drawString(b.values[i], 50, 50);
repaint();
}
}
}
You seem to be creating a new Display every time and telling that to repaint instead of the real one. Move your Display d variable into the Calculator class as a field, and don't declare new ones.
You create the original Display object as a local variable so it can't be accessed from elsewhere, so make this part use the class field instead:
Display d = new Display();
Also, this line in actionPerformed is creating a new instance and should be removed:
d = new Display();
Don't call repaint from within a paint method. This will cause the API to schedule anther paint request, which will eventually consume all your CPU cycles
You actually have two instances of Display, one which is on the screen, one which is not
While there are a few ways to fix this, one of the simpler would be to simply pass the instance of Display created to in Calculators constructor to Buttons, for example...
public class Calculator {
public static void main(String[] args) {
Calculator c = new Calculator();
}
public Calculator() {
JFrame frame = new JFrame("Calculator");
frame.setSize(800, 800);
frame.setResizable(false);
Display d = new Display();
Buttons b = new Buttons(d);
frame.setLayout(new GridLayout(2, 1));
frame.add(d);
frame.add(b);
frame.setVisible(true);
}
public class Buttons extends JPanel implements ActionListener {
private int z;
private JButton[] buttons;
private String[] values;
private String clickedButton;
private Display d;
public Buttons(Display d) {
this.d = d;
setBackground(Color.BLACK);
setLayout(new GridLayout(5, 4));
values = new String[100];
for (int i = 0; i < values.length; i++) {
values[i] = new String("");
}
addButtons();
}
Then buttons can use that instance to display what ever it needs to display
private int index = 0;
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
for (int i = 0; i < 10; i++) {
if (action.equals(Integer.toString(i))) {
values[index] += Integer.toString(i);
d.setValue(values[index]);
index++;
}
}
}
}
public class Display extends JPanel {
public Font courier;
private String value;
public Display() {
setBackground(Color.BLACK);
courier = new Font("Courier", Font.BOLD, 50);
}
public void setValue(String value) {
this.value = value;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.setFont(courier);
if (value != null) {
g.drawString(value, 50, 50);
}
}
}
}

JButton Keyboard - convert setText to char

I am trying to use a JButton based keyboard in a GUI based game of Hangman. However when I want to check that the key pressed is in the hidden word, I am not sure where I need to change the type from String to char. I want to use the GUI based keyboard instead of allowing the user to use the keyboard, to try and minimise the validation that needs to be done. These are the classes that I have created thus far. I am struggling to get this working.
package guis;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MouseClick extends JFrame implements ActionListener, MouseListener
{
private static final long serialVersionUID = 1L;
private static ActionListener letterHandler = null;
private Container cPane;
private JLabel lblTitle, lblTries, lblCountryToGuess, chancesLabel, message;//, usedLettersPanel;
private JButton btnExit, btnStart, btn1, btn3, btn4, btnX;
private JButton [] btn = new JButton[26];
private JPanel pNorth, pSouth, pEast, pWest, pCenter, wordPanel, messagePanel, usedLettersPanel, hangPanel, drawingFrame;//, lblCountryToGuess;
private JMenuItem mIRules, mIDev, mIRestart, mIExit;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JPopupMenu.Separator jSeparator1;
private JFrame frame = new JFrame();
private JButton enter;
private JLabel[] wordArray, usedLetters;
//private JFrame drawingFrame;
private HangmanDrawing drawing;
private char[] incorrectGuesses;
private char[] buttonLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private String word;
private int chances;
char input;
private JFrame endFrame;
private JPanel top, bottom;
private JLabel doNow;
private JButton restart, exit;
MouseClick() throws IOException
{
super("Assignment 2 - Hangman");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
word = new WordHandler().getRandomWord();
chances = 7;
cPane = getContentPane();
cPane.setBackground(new Color (236, 128, 19));
pNorth = new JPanel();
pSouth = new JPanel();
pEast = new JPanel();
pWest = new JPanel();
pCenter = new JPanel();
lblTitle = new JLabel(" Hangman ", SwingConstants.CENTER);
lblTitle.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
lblTitle.setBorder(BorderFactory.createRaisedBevelBorder());
lblTitle.setBackground(new Color (38, 29, 226));
lblTitle.setOpaque(true);
lblTitle.setForeground(Color.white);
pNorth.add(lblTitle);
/*lblCountryToGuess = new JLabel("", SwingConstants.CENTER);
lblCountryToGuess.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
//lblCountryToGuess.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
lblCountryToGuess.setBounds(50, 1, 500, 60);
lblCountryToGuess.setBorder(BorderFactory.createTitledBorder("This is the country to be guessed..."));
//wordArray = new JLabel [hiddenCountry.length()];
//for (int i = 0 ; i < wordArray.length ; i++)
//{
// wordArray[i] = new JLabel("_");
// wordArray[i].setFont(new Font("Comic Sans MS.", Font.BOLD, 23));
// lblTitle4.add(wordArray[i]);
//}
pCenter.add(lblCountryToGuess);*/
hangPanel = new HangmanDrawing();
//drawing = new HangmanDrawing();
drawingFrame = new JPanel();
//drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//drawingFrame.setFocusableWindowState(false);
//drawingFrame.getContentPane().add(drawing);
//int xPosition = (int) ((scrnsize.width / 2) + (this.getWidth() / 2));
//drawingFrame.setSize(scrnsize.width - xPosition - 10,
//scrnsize.width - xPosition - 10);
// drawingFrame.setLocation(xPosition,
//(int) (scrnsize.height - this.getHeight())/3);
setVisible (true);
drawingFrame.setVisible(true);
pCenter.add(drawingFrame);
wordPanel = new JPanel();
wordPanel.setBounds(100, 100, 100, 60);
wordPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
wordPanel.setBorder(BorderFactory.createTitledBorder("This is the country to guess..."));
wordArray = new JLabel [word.length()];
for (int i = 0 ; i < wordArray.length ; i++)
{
wordArray[i] = new JLabel("_");
wordArray[i].setFont(new Font("Arial", Font.BOLD, 23));
wordPanel.add(wordArray[i]);
}
pCenter.add(wordPanel);
usedLettersPanel = new JPanel();
usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5));
incorrectGuesses = new char [chances];
usedLetters = new JLabel [incorrectGuesses.length];
for (int i = 0 ; i < usedLetters.length ; i++)
{
usedLetters[i] = new JLabel("~");
usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
usedLettersPanel.add(usedLetters[i]);
}
pCenter.add(usedLettersPanel);
messagePanel = new JPanel();
messagePanel.setLayout (new FlowLayout (FlowLayout.LEFT));
message = new JLabel ("Guess a letter...");
message.setFont (new Font ("Comic Sans MS", Font.BOLD, 17));
messagePanel.add(message);
pCenter.add(messagePanel);
/*usedLettersPanel = new JLabel();
usedLettersPanel.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
usedLettersPanel.setBounds(50, 1, 500, 60);
usedLettersPanel.setBorder(BorderFactory.createTitledBorder("Letters already guessed..."));
//usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5));
//incorrectGuesses = new char [chances];
//usedLetters = new JLabel [incorrectGuesses.length];
//for (int i = 0 ; i < usedLetters.length ; i++)
//{
//usedLetters[i] = new JLabel("~");
//usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
//usedLettersPanel.add(usedLetters[i]);
//}
pCenter.add(usedLettersPanel);*/
btnStart = new JButton(" Start / New Game ");
btnStart.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnStart.setBackground(Color.GREEN);
btnStart.setForeground(Color.white);
btnStart.setOpaque(true);
btnStart.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(btnStart);
btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
jMenuItem1.setVisible(true);
MouseClick sample = null;
try
{
sample = new MouseClick();
}
catch (IOException e1)
{
e1.printStackTrace();
}
sample.setTitle("Assignment 2 - Hangman Game");
sample.setSize(1200, 800);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
chancesLabel = new JLabel (chances + " chances left...");
chancesLabel.setFont (new Font ("Comic Sans MS", Font.BOLD, 17));
//lblTries = new JLabel(" Tries Remaining ");
//lblTries.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
chancesLabel.setBackground(new Color (38, 29, 226));
chancesLabel.setForeground(Color.white);
chancesLabel.setOpaque(true);
chancesLabel.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(chancesLabel);
btnExit = new JButton(" Exit Game");
btnExit.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnExit.setBackground(new Color (236, 19, 35));
btnExit.setForeground(Color.white);
btnExit.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(btnExit);
for(int i = 0; i < 26; i++)
{
//JButton btnX = new JButton();
btnX = new JButton(new KeyboardListener(buttonLetters[i]));
btnX.setText("" + buttonLetters[i]);
pSouth.add(btnX);
btnX.setVisible(true);
//btn[i] = btnX;
//btn[i].setText("" + (char)('A'+ i));
//btn[i].setText("" + buttonLetters[i]);
//input = buttonLetters[i];
//pSouth.add(btn[i]);
//btn[i].setVisible(true);
}
cPane.add(pNorth, BorderLayout.NORTH);
cPane.add(pSouth, BorderLayout.SOUTH);
pSouth.setLayout(new GridLayout(3,10,1,1));
cPane.add(pWest, BorderLayout.WEST);
pWest.setLayout(new GridLayout(3,1,1,10));
cPane.add(pEast, BorderLayout.EAST);
cPane.add(pCenter, BorderLayout.CENTER);
pCenter.setLayout(new GridLayout(4, 1, 1, 1));
/*Container chancesContainer = new Container();
chancesContainer.setLayout(new FlowLayout (FlowLayout.RIGHT));
chancesContainer.add(chancesLabel);
JPanel wrongGuessesContainer = new JPanel();
wrongGuessesContainer.setLayout(new GridLayout (1, 2));
wrongGuessesContainer.setBorder(BorderFactory.createTitledBorder ("Wrong Guesses"));
wrongGuessesContainer.add(usedLettersPanel);
wrongGuessesContainer.add (chancesContainer);
Container bottomContainer = new Container();
bottomContainer.setLayout(new BorderLayout());
bottomContainer.add(wrongGuessesContainer, BorderLayout.NORTH);
bottomContainer.add(messagePanel, BorderLayout.SOUTH);
getContentPane().setLayout(new BorderLayout());
//getContentPane().add (inputPanel, BorderLayout.NORTH);
getContentPane().add(wordPanel, BorderLayout.CENTER);
getContentPane().add(bottomContainer, BorderLayout.SOUTH);*/
btnExit.addActionListener(this);
pCenter.addMouseListener(this);
pNorth.addMouseListener(this);
pSouth.addMouseListener(this);
pEast.addMouseListener(this);
pWest.addMouseListener(this);
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jMenuItem4 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem5 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("New Game");
jMenuItem1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
jMenuItem1.setVisible(true);
MouseClick sample = null;
try
{
sample = new MouseClick();
}
catch (IOException e1)
{
e1.printStackTrace();
}
sample.setTitle("Assignment 2 - Hangman Game");
sample.setSize(1200, 800);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
jMenu2.setText("Help");
jMenuItem3.setText("Rules");
jMenuItem3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Hangman is a guessing game where the word"
+"\n to guess is represented by dashes. The player"
+"\n is given the option to enter a letter. If the letter"
+"\n guessed is contained in the word, the letter will"
+"\n replace the dash in its approprate placement."
+"\n You cannot exceed 7 wrong guesses or else you"
+"\n lose. Words are selected randomly.", "Instructions",
JOptionPane.INFORMATION_MESSAGE);
}
});
jMenu2.add(jMenuItem3);
jMenu2.add(jSeparator1);
jMenuItem4.setText("Developer");
jMenuItem4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Developer: Ryan Smith");
}
});
jMenu2.add(jMenuItem4);
jMenuBar1.add(jMenu2);
jMenu3.setText("Exit");
jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
jMenuItem5.setText("Exit Game");
jMenuItem5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
jMenu3.add(jMenuItem5);
jMenuBar1.add(jMenu3);
setJMenuBar(jMenuBar1);
pack();
/*drawing = new HangmanDrawing();
drawingFrame = new JFrame();
drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
drawingFrame.setFocusableWindowState(false);
drawingFrame.getContentPane().add(drawing);
int xPosition = (int) ((scrnsize.width / 2) + (this.getWidth() / 2));
drawingFrame.setSize(scrnsize.width - xPosition - 10,
scrnsize.width - xPosition - 10);
drawingFrame.setLocation(xPosition,
(int) (scrnsize.height - this.getHeight())/3);
setVisible (true);
drawingFrame.setVisible(true);*/
}
private void endGame()
{
enter.removeActionListener (this);
//inputField.removeActionListener(this);
//inputField.setEditable (false);
endFrame = new JFrame();
top = new JPanel();
bottom = new JPanel();
doNow = new JLabel ("What do you want to do now?");
restart = new JButton ("Start Again");
exit = new JButton ("Exit Hangman");
doNow.setFont (new Font ("Verdana", Font.BOLD, 17));
top.setLayout (new FlowLayout (FlowLayout.CENTER));
top.add (doNow);
restart.setFont (new Font ("Arial", Font.BOLD, 12));
restart.addActionListener(this);
exit.setFont (new Font ("Arial", Font.BOLD, 12));
exit.addActionListener(this);
bottom.setLayout (new FlowLayout (FlowLayout.CENTER, 44, 10));
bottom.add (restart);
bottom.add (exit);
endFrame.getContentPane().setLayout (new BorderLayout());
endFrame.getContentPane().add (top, BorderLayout.NORTH);
endFrame.getContentPane().add (bottom, BorderLayout.SOUTH);
endFrame.pack();
Dimension scrnsize = Toolkit.getDefaultToolkit().getScreenSize();
endFrame.setLocation ((int) (scrnsize.width - endFrame.getWidth())/2,
(int) (scrnsize.height - this.getHeight())/3 + this.getHeight());
endFrame.setResizable (false);
endFrame.setVisible (true);
this.setFocusableWindowState(false);
}
public void actionPerformed (ActionEvent event)
{
if(event.getSource().equals(btnExit))
{
System.exit(0);
}
else if (event.getSource().equals(restart))
{
endFrame.dispose();
MouseClick.this.dispose();
//drawingFrame.dispose();
//new HangmanMenu();
}
else if (event.getSource().equals(exit))
{
endFrame.dispose();
MouseClick.this.dispose();
//drawingFrame.dispose();
System.exit(0);
}
else
{
try
{
//char input = Character.toUpperCase(inputField.getText().charAt(0));
//if(event.getSource().equals(btn))
//{
//System.out.println("\n" + input);
boolean letterInWord = false;
for (int i = 0 ; i < word.length() ; i++)
{
if (word.charAt (i) == input)
{
letterInWord = true;
break;
}
}
if (!letterInWord) {
boolean alreadyGuessed = false;
for (int i = 0 ; i < incorrectGuesses.length ; i++) {
if (incorrectGuesses [i] == input) {
alreadyGuessed = true;
message.setText ("You already guessed that!");
break;
}
}
if (!alreadyGuessed) {
chances--;
drawing.addPart();
if (chances >= 0) {
incorrectGuesses [incorrectGuesses.length - chances - 1] = input;
usedLetters [usedLetters.length - chances - 1].setText ("" + input);
message.setText ("Woops, wrong! Try again!");
chancesLabel.setText (chances + " chances left...");
} else {
chancesLabel.setText ("Sorry, you lose.");
message.setText ("The word was: " + word);
endGame();
}
}
} else {
boolean alreadyGuessed = false;
for (int i = 0 ; i < wordArray.length ; i++) {
if (wordArray [i].getText().charAt (0) == input) {
alreadyGuessed = true;
message.setText ("You already guessed that!");
break;
}
}
if (!alreadyGuessed) {
for (int i = 0 ; i < word.length() ; i++) {
if (word.charAt (i) == input) {
wordArray [i].setText ("" + input);
}
}
boolean wordComplete = true;
for (int i = 0 ; i < wordArray.length ; i++) {
if (!Character.isLetter (wordArray [i].getText().charAt (0))) {
wordComplete = false;
break;
}
}
if (!wordComplete) {
message.setText ("Well done, you guessed right!");
} else {
message.setText ("Congratulations, you win the game!");
drawing.escape();
endGame();
}
}
//}
}
//inputField.setText ("");
}catch (Exception x)
{
}
}
}
#Override
public void mouseClicked(MouseEvent e){}
#Override
public void mouseEntered(MouseEvent e){}
#Override
public void mouseExited(MouseEvent e){}
#Override
public void mousePressed(MouseEvent e){}
#Override
public void mouseReleased(MouseEvent e){}
class KeyboardListener implements ActionListener
{
private final char letter;
public KeyboardListener(char letter)
{
this.letter = letter;
}
public char getLetter()
{
return letter;
}
#Override
public void actionPerformed(ActionEvent e)
{
char tempLetter;
if (e.getSource().equals(btnX))
{
tempLetter = 'A';
}
}
}
}
This is the code for the WordHandler class.
package guis;
import java.io.*;
class WordHandler
{
private BufferedReader fileIn;
private String[] wordArray;
private File wordFile;
public WordHandler() throws IOException
{
wordFile = new File("countriesnospaces.txt");
int arrayCounter = 0;
try {
BufferedReader fileIn = new BufferedReader(new FileReader(wordFile));
while (fileIn.readLine() != null)
{
arrayCounter++;
}
wordArray = new String [arrayCounter];
fileIn.close();
fileIn = new BufferedReader(new FileReader(wordFile));
for (int pos = 0 ; pos < arrayCounter ; pos++)
{
wordArray[pos] = fileIn.readLine();
}
fileIn.close();
} catch (FileNotFoundException e)
{
System.out.println("File not found. Please create it and add words.");
}
catch (Exception e)
{
System.out.println("Error: " + e);
}
}
public String getRandomWord() throws IOException
{
int random = (int) (Math.random() * wordArray.length);
return wordArray[random].toUpperCase();
}
public void sort()
{
String temp;
for (int loop = 0 ; loop < wordArray.length - 1 ; loop++) {
for (int pos = 0 ; pos < wordArray.length - 1 - loop ; pos++) {
if (wordArray[pos].compareTo(wordArray[pos + 1]) >0) {
temp = wordArray[pos];
wordArray[pos] = wordArray[pos + 1];
wordArray[pos + 1] = temp;
}
}
}
}
public String[] getArray()
{
return wordArray;
}
}
This is the test class.
package guis;
import java.io.IOException;
import javax.swing.JFrame;
public class TestMouseClick
{
public static void main(String[] args) throws IOException
{
MouseClick sample = new MouseClick();
sample.setTitle("Assignment 2 - Hangman");
sample.setSize(800, 750);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}
}
A simple fix would be getting the first character in the String returned by JButton tooltip text using the charAt(0) method and assign it to input:
char input = jButton26.getToolTipText().charAt(0);
or you could split it up to make it clearer:
String s = jButton26.getToolTipText();
char input = s.charAt(0);
Also just a tip, instead of manually coding each individual JButton for the GUI keyboard, you could create an array containing all 26 letters and then create the buttons and attach listeners using a for loop. This would significantly reduce the amount of code you have to write.
New Edit: creating and setting up lots of similar objects
(Also I noticed you created an array to store the buttons as well as a buttonLettersarray - this isn't necessary unless you have changed your code to utlise an array of buttons)
The important thing to note here is that ActionListener is an object in Java so it can be defined to store data and other method definitions like any other class. Personally I would prefer to write an inner class that extends ActionListener to store the letter that each button represents.
//define this inner class outside of the methods
class KeyboardListener extends ActionListener {
//field type depends on your buttonLetters array (not sure if it is chars or Strings)
private final String letter;
public KeyboardListener(String letter) {
this.letter = letter;
}
public String getLetter() {
return letter;
}
#Override
public void actionPerformed(ActionEvent ae) {
//do something when button is clicked
//you can make use of the getLetter() method to retrieve the letter
}
}
//this goes in the for loop when creating each button
JButton btnX = new JButton(new KeyboardListener(buttonLetters[i]));
//add button to interface and anything else
Note: one of the JButton constructors can take any class that implements the Action interface (or extends ActionListener in this case) to add it upon creation rather than having to call addActionListener().

Previous instance of table appends to the newly invoked table. The page should show only one table

When I click the button called Enrolled Subjects, a table showing enrolled subjects is invoked. The data is loaded from a text file. But when I go to another page of the application and go back to the Enrolled Subjects or when I click the Enrolled Subjects Button again, a new table loads and adds to the previously loaded table. This makes the table grow longer every time I click Enrolled Subjects. I have added a removeAll() method which clears the content of the pane before loading the table again, but the previously loaded table, for some reason, does not go away.
Here's the code of the panel where the table is attached.
public class EnrolledSubjectsPanel extends JPanel
{
public EnrolledSubjectsPanel(String path)
{
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
LoadTable table = new LoadTable(path);
table.setBounds(0,60,1129,600);
add(table);
JLabel lblEnrolledSubjects = new JLabel("Enrolled Subjects");
lblEnrolledSubjects.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblEnrolledSubjects.setBounds(446, 0, 292, 43);
add(lblEnrolledSubjects);
setVisible(true);
}
}
The class that creates the table
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}
The main class where the panel is attached to
public class LaunchPage extends JFrame
{ public LaunchPage(String path)
{
getContentPane().setBackground(Color.white);
getContentPane().setLayout(null);
StudentBasicInformationPanel studentBasicInfo = new StudentBasicInformationPanel(path);
getContentPane().add(studentBasicInfo);
JLabel universityTitleL = new JLabel("Evil Genuises University");
universityTitleL.setFont(new Font("Edwardian Script ITC", Font.ITALIC, 42));
universityTitleL.setBounds(514, 11, 343, 65);
getContentPane().add(universityTitleL);
JPanel panelToAttach = new JPanel();
panelToAttach.setBounds(173, 280, 1129, 404);
getContentPane().add(panelToAttach);
setSize(1366, 768);
JButton enrollmentButton = new JButton("Enrollment");
enrollmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrollmentPanel ep = new EnrollmentPanel();
ep.setBackground(Color.LIGHT_GRAY);
ep.setBounds(0, 0, 1129, 401);
panelToAttach.add(ep);
repaint();
}
});
enrollmentButton.setBounds(10, 280, 157, 58);
getContentPane().add(enrollmentButton);
JButton viewEnrolledSubjectsButton = new JButton("Enrolled Subjects");
viewEnrolledSubjectsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrolledSubjectsPanel es = new EnrolledSubjectsPanel(path);
es.setBackground(Color.LIGHT_GRAY);
es.setBounds(0, 0, 1129, 401);
panelToAttach.add(es);
repaint();
}
});
viewEnrolledSubjectsButton.setBounds(10, 349, 157, 58);
getContentPane().add(viewEnrolledSubjectsButton);
JButton viewGradesButton = new JButton("View Grades");
viewGradesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
GradesPanel gp = new GradesPanel();
gp.setBackground(Color.LIGHT_GRAY);
gp.setBounds(0, 0, 1129, 401);
panelToAttach.add(gp);
repaint();
}
});
viewGradesButton.setBounds(10, 418, 157, 58);
getContentPane().add(viewGradesButton);
JButton clearanceButton = new JButton("Clearance");
clearanceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
ClearancePanel cp = new ClearancePanel();
cp.setBackground(Color.LIGHT_GRAY);
cp.setBounds(0, 0, 1129, 401);
panelToAttach.add(cp);
repaint();
}
});
clearanceButton.setBounds(10, 487, 157, 58);
getContentPane().add(clearanceButton);
JButton viewAccountButton = new JButton("View Account");
viewAccountButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
AccountPanel ap = new AccountPanel();
ap.setBackground(Color.LIGHT_GRAY);
ap.setBounds(0, 0, 1129, 401);
panelToAttach.add(ap);
repaint();
}
});
viewAccountButton.setBounds(10, 556, 157, 58);
getContentPane().add(viewAccountButton);
JButton closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
closeButton.setBounds(10, 626, 157, 58);
getContentPane().add(closeButton);
setVisible(true);
}
}
Thanks in advance!
Try using below code in your LoadTable class before you adding the rows to the table. It will clear the rows in the table model.
dtm.setRowCount(0);
So your new LoadTable class should look like this:
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
dtm.setRowCount(0); //THIS WILL CLEAR THE ROWS IN YOUR STATIC TABLEMODEL
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}

Java: Components disappearing after event

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. :)

Update JLabel every X seconds from ArrayList<List> - Java

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);
}
}

Categories