Related
My professor told me to put both of these together to make a running program. I am utilizing Netbeans, and it keeps telling me that there is no main class. Am I supposed to create one or am I missing something? How do I put these together into a working gui java application?
Here is the first file, it is called NumberGame
import java.util.Random;
public class NumberGame {
private Random rand = new Random();
private int min, max;
private int num1, num2;
public NumberGame(int min, int max) {
this.min = min;
this.max = max;
newNums();
}
public int getNum1() {
return num1;
}
public int getNum2() {
return num2;
}
public void newNums() {
num1 = rand.nextInt(max - min + 1) + min;
num2 = rand.nextInt(max - min + 1) + min;
}
public int calcSum() {
return num1 + num2;
}
public boolean checkSum(int num) {
return num == calcSum();
}
}
The second file is called App here it is
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class App extends JFrame implements ActionListener {
/* Canvas ============================================ */
private NumberGame numbers;
private Font mainFont = new Font(Font.SANS_SERIF, Font.PLAIN,16);
/* Components for Canvas ============================= */
private JTextField messageField;
private JLabel lblNum1;
private JLabel lblNum2;
private JTextField sumField;
private JButton btnNext;
private JButton btnCheck;
public App(String title, int width, int height) {
// initialize new number game
numbers = new NumberGame(10, 49);
// initialize components
messageField = new JTextField("", 10);
messageField.setEditable(false);
messageField.setHorizontalAlignment(JTextField.CENTER);
messageField.setFont(mainFont);
// add components to board
add(messageField, BorderLayout.NORTH);
add(createCenter(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.SOUTH);
// add action listeners
btnCheck.addActionListener(this);
btnNext.addActionListener(this);
sumField.addActionListener(this);
// create the window
createWindow(title, width, height);
pack();
}
private void createWindow(String title, int width, int height) {
setVisible(true);
setTitle(title);
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createCenter() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
JLabel lblNumPrompt1 = new JLabel("Number 1 = ", JLabel.RIGHT);
lblNumPrompt1.setFont(mainFont);
lblNum1 = new JLabel(Integer.toString(numbers.getNum1()), JLabel.CENTER);
lblNum1.setFont(mainFont);
JLabel lblNumPrompt2 = new JLabel("Number 2 = ", JLabel.RIGHT);
lblNumPrompt2.setFont(mainFont);
lblNum2 = new JLabel(Integer.toString(numbers.getNum2()), JLabel.CENTER);
lblNum2.setFont(mainFont);
JLabel lblSumPrompt = new JLabel("Sum = ", JLabel.RIGHT);
lblSumPrompt.setFont(mainFont);
sumField = new JTextField("0", 10);
sumField.setHorizontalAlignment(JTextField.CENTER);
sumField.setFont(mainFont);
// add objects to the panel
panel.add(lblNumPrompt1);
panel.add(lblNum1);
panel.add(lblNumPrompt2);
panel.add(lblNum2);
panel.add(lblSumPrompt);
panel.add(sumField);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
btnNext = new JButton("Next");
btnCheck = new JButton("Check");
panel.add(btnNext);
panel.add(btnCheck);
return panel;
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(btnNext)) {
numbers.newNums();
lblNum1.setText(Integer.toString(numbers.getNum1()));
lblNum2.setText(Integer.toString(numbers.getNum2()));
} else {
int num = Integer.parseInt(sumField.getText());
if (numbers.checkSum(num))
messageField.setText("Correct!");
else
messageField.setText("Try Again!");
}
}
}
Simply create a main class and initialize the app class as below, HTH.
public static void main(String args[])
{
//Put in the title and size of the Panel
App app1 = new App("MY game", 1000, 900);
}
Create a main class .
Put all 3 classes into same package.
Simply create an object of App class in main class.
Run the main class.
I'm trying to create a "Tic Tac Toe" game. I've chosen to create a variation of JPanel to represent each square. The class beneath represents one of 9 panels that together make up my game board.
Now the problem I'm having is that when I click the panel a 'X' should be displayed inside of the panel, but nothing happens. I'd very much appreciate it if someone steered me in the right direction.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToePanel extends JPanel implements MouseListener {
private boolean isPlayer1Turn = true;
private boolean isUsed = false;
private JLabel ticTacLbl = new JLabel();
public TicTacToePanel() {
setBorder(BorderFactory.createLineBorder(Color.BLACK));
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
if (!isUsed) {
if (isPlayer1Turn) {
ticTacLbl.setForeground(Color.red);
ticTacLbl.setText("X");
add(ticTacLbl, 0);
isUsed = true;
} else {
ticTacLbl.setForeground(Color.blue);
ticTacLbl.setText("O");
add(ticTacLbl, 0);
isUsed = true;
}
} else {
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, new TicTacToePanel());
}
}
EDIT:
I simply added my label component in the constructor of my TicTacToePanel so that I no longer have to call revalidate() and I'm not adding components during runtime.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToePanel extends JPanel implements MouseListener{
private boolean isPlayer1Turn = true;
private boolean isUsed = false;
private JLabel ticTacLbl = new JLabel();
public TicTacToePanel(){
add(ticTacLbl, 0);
setBorder(BorderFactory.createLineBorder(Color.BLACK));
addMouseListener(this);
}
public void mouseClicked(MouseEvent e){
}
public void mousePressed(MouseEvent e){
if (!isUsed) {
if (isPlayer1Turn) {
ticTacLbl.setForeground(Color.red);
ticTacLbl.setText("X");
isUsed = true;
} else {
ticTacLbl.setForeground(Color.blue);
ticTacLbl.setText("O");
isUsed = true;
}
}
else{
}
}
public void mouseReleased(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public static void main(String[] args){
JOptionPane.showMessageDialog(null, new TicTacToePanel());
}
}
The GUI constructor:
public TicTacToeGUI(int gameMode){
if(gameMode == 0){
amountOfPanels = 9;
TicTacToePanel[] panelArr = new TicTacToePanel[amountOfPanels];
add(gamePanel, new GridLayout(3, 3));
setPreferredSize(new Dimension(100, 100));
for(int i = 0; i < amountOfPanels; i++){
panelArr[i] = new TicTacToePanel();
gamePanel.add(panelArr[i]);
}
}
else if(gameMode == 1){
amountOfPanels = 225;
TicTacToePanel[] panelArr = new TicTacToePanel[amountOfPanels];
add(gamePanel, new GridLayout(15, 15));
setPreferredSize(new Dimension(500, 500));
for(int i = 0; i < amountOfPanels; i++){
panelArr[i] = new TicTacToePanel();
gamePanel.add(panelArr[i]);
}
}
}
public static void main(String[] args){
JOptionPane.showMessageDialog(null, new TicTacToeGUI(0));
}
}
When you add/remove components at runtime, always call revalidate() afterwards. revalidate() makes the component refresh/relayout.
So just call revalidate() after you add the label and it will work.
If you're goal is to create a Tic Tac Toe game, then you may wish to re-think your current strategy of adding components to the GUI on the fly. Much better would be to create a grid of components, say of JLabel, and place them on the JPanel at program start up. This way you can change the pressed JLabel's text and color, and even its Icon if you want to be fancy during program run without having to add or remove components. For example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class TicTacToePanel extends JPanel {
private static final int ROWS = 3;
private static final int MY_C = 240;
private static final Color BG = new Color(MY_C, MY_C, MY_C);
private static final int PTS = 60;
private static final Font FONT = new Font(Font.SANS_SERIF, Font.BOLD, PTS);
public static final Color X_COLOR = Color.BLUE;
public static final Color O_COLOR = Color.RED;
private JLabel[][] labels = new JLabel[ROWS][ROWS];
private boolean xTurn = true;
public TicTacToePanel() {
setLayout(new GridLayout(ROWS, ROWS, 2, 2));
setBackground(Color.black);
MyMouse myMouse = new MyMouse();
for (int row = 0; row < labels.length; row++) {
for (int col = 0; col < labels[row].length; col++) {
JLabel label = new JLabel(" ", SwingConstants.CENTER);
label.setOpaque(true);
label.setBackground(BG);
label.setFont(FONT);
add(label);
label.addMouseListener(myMouse);
}
}
}
private class MyMouse extends MouseAdapter {
#Override // override mousePressed not mouseClicked
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
String text = label.getText().trim();
if (!text.isEmpty()) {
return;
}
if (xTurn) {
label.setForeground(X_COLOR);
label.setText("X");
} else {
label.setForeground(O_COLOR);
label.setText("O");
}
// information to help check for win
int chosenX = -1;
int chosenY = -1;
for (int x = 0; x < labels.length; x++) {
for (int y = 0; y < labels[x].length; y++) {
if (labels[x][y] == label) {
chosenX = x;
chosenY = y;
}
}
}
// TODO: check for win here
xTurn = !xTurn;
}
}
private static void createAndShowGui() {
TicTacToePanel mainPanel = new TicTacToePanel();
JFrame frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This is the class that makes the Frame and Tabbed Panes:
package homeworkToolkitRevised;
import javax.swing.*;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.event.*;
public class MakeGUI extends JFrame
{
private static final long serialVersionUID = 1L;
JTabbedPane TabPane;
public MakeGUI()
{
this.setTitle("The Homework Toolkit!");
setSize(700, 500);
setAlwaysOnTop(false);
setNimbus();
JTabbedPane TabPane = new JTabbedPane();
add(TabPane);
TabPane.addTab("Main Menu", new MainScreen());
TabPane.addTab("Quadratic Equations", new Quadratic());
setVisible(true);
}
public void setAlwaysTop()
{
setAlwaysOnTop(true);
}
public void setNotAlwaysTop()
{
setAlwaysOnTop(false);
}
public final void setNimbus()
{
try
{
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (UnsupportedLookAndFeelException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new MakeGUI();
}
}
And this is a tab in the tabbed pane:
package homeworkToolkitRevised;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quadratic extends JPanel implements ActionListener, ItemListener
{
private static final long serialVersionUID = 1L;
JLabel lblX2 = new JLabel ("Co-Efficient Of x²:", JLabel.LEFT);
JLabel lblX = new JLabel ("Co-Efficient of x:", JLabel.LEFT);
JLabel lblNum = new JLabel ("Number:", JLabel.LEFT);
JLabel lblNature = new JLabel ("Nature Of Roots:", JLabel.LEFT);
JLabel lblVal1 = new JLabel ("Value 1:", JLabel.LEFT);
JLabel lblVal2 = new JLabel ("Value 2:", JLabel.LEFT);
JTextField tfX2 = new JTextField (20);
JTextField tfX = new JTextField (20);
JTextField tfNum = new JTextField (20);
JTextField tfNature = new JTextField (20);
JTextField tfVal1 = new JTextField (20);
JTextField tfVal2 = new JTextField (20);
JPanel[] row = new JPanel[7];
JButton btnNature = new JButton ("Nature Of Roots");
JButton btnCalc = new JButton ("Calculate");
JButton btnClear = new JButton ("Clear");
double a = 0, b = 0, c = 0;
double Val1 = 0, Val2 = 0, Discriminant = 0;
String StrVal1, StrVal2;
Quadratic()
{
setLayout(new GridLayout(8,1));
for(int i = 0; i < 7; i++)
{
row[i] = new JPanel();
add(row[i]);
row[i].setLayout(new GridLayout (1,2));
}
row[3].setLayout(new GridLayout (1,3));
row[0].add(lblX2);
row[0].add(tfX2);
row[1].add(lblX);
row[1].add(tfX);
row[2].add(lblNum);
row[2].add(tfNum);
row[3].add(btnNature);
{
btnNature.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Nature();
}
}
);
}
row[3].add(btnCalc);
{
btnCalc.setEnabled(false);
btnCalc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Calculate();
}
}
);
}
row[3].add(btnClear);
{
btnClear.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Clear();
}
}
);
}
row[4].add(lblNature);
row[4].add(tfNature);
row[5].add(lblVal1);
row[5].add(tfVal1);
row[6].add(lblVal2);
row[6].add(tfVal2);
tfNature.setEditable(false);
tfVal1.setEditable(false);
tfVal2.setEditable(false);
JCheckBox chckbxAlwaysOnTop = new JCheckBox("Always On Top");
chckbxAlwaysOnTop.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie)
{
if(ie.getStateChange() == ItemEvent.SELECTED)
{
//setAlwaysTop();
//This is method from main class to change always on top condition of jframe
}
else if (ie.getStateChange() == ItemEvent.DESELECTED)
{
//setNotAlwaysTop();
//This is method from main class to change always on top condition of jframe
}
}
});
add(chckbxAlwaysOnTop);
setVisible(true);
}
public void Calculate()
{
a = Double.parseDouble(tfX2.getText());
b = Double.parseDouble(tfX.getText());
c = Double.parseDouble(tfNum.getText());
Val1 = (-b + Math.sqrt(Discriminant)) / (2 * a);
Val2 = (-b - Math.sqrt(Discriminant)) / (2 * a);
StrVal1 = String.valueOf(Val1);
StrVal2 = String.valueOf(Val2);
tfVal1.setText(StrVal1);
tfVal2.setText(StrVal2);
tfX2.setText("");
tfX.setText("");
tfNum.setText("");
btnCalc.setEnabled(false);
}
public void Clear()
{
a = 0; b = 0; c = 0;
Val1 = 0; Val2 = 0; Discriminant = 0;
tfX2.setText("");
tfX.setText("");
tfNum.setText("");
tfVal1.setText("");
tfVal2.setText("");
tfNature.setText("");
}
public void Nature()
{
a = Double.parseDouble(tfX2.getText());
b = Double.parseDouble(tfX.getText());
c = Double.parseDouble(tfNum.getText());
Discriminant = (b*b) - (4*(a*c));
if (Discriminant == 0)
{
tfNature.setText("Equal");
btnCalc.setEnabled(true);
}
else if (Discriminant < 0)
{
tfNature.setText("Imaginary");
}
else
{
tfNature.setText("Real, Distinct");
btnCalc.setEnabled(true);
}
}
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
}
public void itemStateChanged(ItemEvent arg0)
{
// TODO Auto-generated method stub
}
}
So what I want to do is to add a checkbox to the tab that allows me to set the property of the JFrame made in the main class to be always on top.
First of all I don't understand how to call the method properly so that it alters the always on top property. I tried making an object for it and also tried making the methods static but it just doesn't work.
What I would like to know is what modifier to use for the methods and how to alter properties of parent JFrame from inside a JTabbedPane.
Thanks.
EDIT: It would also work if I could add this checkbox to the JFrame itself like below the JTabbed Pane or something which would make it easier to manage with multiple tabs.
I'm building a GUI, my program runs a series of tests. I end up closing my first JPanel window, and opening another one. When I run the second GUI window's class, it works just great. But after closing the first one, the window will come up, but no components will display. Is this a memory issue? What can I do about it?
Code:
package GUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class guiRun extends JFrame {
public guiRun() {
JPanel Window = new JPanel();
getContentPane().add(Window);
JLabel greeting = new JLabel("Automated Module Tester-Running");
JLabel Browser = new JLabel("Current Browser:");
JLabel cFailures = new JLabel("Current Fails:");
JLabel cSuccess = new JLabel("Current Successes:");
JLabel RunTime = new JLabel("Total RunTime:");
JLabel totalTests = new JLabel("Total Tests:");
JLabel Username = new JLabel("Username Under Test:");
JLabel Router = new JLabel("Router Under Test:");
JLabel TestType = new JLabel("Test Type: ");
final JLabel RunTimetime = new JLabel("00:00:00");
final JLabel cBrowser = new JLabel(currentBrowser);
final JLabel Failures = new JLabel(Integer.toString(tFails));
final JLabel Successes = new JLabel(Integer.toString(tSuccesses));
final JLabel Total = new JLabel (Integer.toString(tFails+tSuccesses));
final JLabel cUsername = new JLabel(currentUser);
final JLabel cRouter = new JLabel(currentRouter);
final JLabel theTestType = new JLabel(currentTest);
JButton End = new JButton("End Test");
JLabel loopProgress = new JLabel("Loop Progress:");
final JProgressBar PBar = new JProgressBar(currentProgress);
Window.setLayout(null);
greeting.setBounds(350,10,200,40);
Browser.setBounds(670,150,150,20);
cBrowser.setBounds(695,170,100,30);
totalTests.setBounds(100,130,100,20);
Total.setBounds(250,130,50,20);
cFailures.setBounds(100,170,100,20);
Failures.setBounds(250,170,50,20);
cSuccess.setBounds(100,210,150,20);
Successes.setBounds(250,210,50,20);
RunTime.setBounds(100,250,150,20);
RunTimetime.setBounds(250,250,100,20);
TestType.setBounds(350,150,150,25);
theTestType.setBounds(500,150,100,25);
Username.setBounds(350,175,150,25);
Router.setBounds(350,200,150,25);
cUsername.setBounds(500,175,100,25);
cRouter.setBounds(500,200,100, 25);
End.setBounds(320, 320, 200, 60);
loopProgress.setBounds(375,390,200,40);
PBar.setValue(currentProgress);
PBar.setMaximum(maxProgress);
PBar.setBounds(100, 430, 700, 50);
End.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
ActionListener updateClockAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PBar.setValue(currentProgress);
PBar.setMaximum(maxProgress);
theTestType.setText(currentTest);
cRouter.setText(currentRouter);
cUsername.setText(currentUser);
Total.setText(Integer.toString(tFails+tSuccesses));
Successes.setText(Integer.toString(tSuccesses));
Failures.setText(Integer.toString(tFails));
cBrowser.setText(currentBrowser);
secs++;
if (secs>=60){
mins++;
secs = 0;
}
if (mins >=60){
hours++;
mins = 0;
}
RunTimetime.setText(hours+":"+mins+":"+secs);
}
};
//ActionListener
Timer time = new Timer(1000, updateClockAction);
time.start();
Window.add(Username);
Window.add(cUsername);
Window.add(Router);
Window.add(cRouter);
Window.add(theTestType);
Window.add(TestType);
Window.add(End);
Window.add(totalTests);
Window.add(Total);
Window.add(cFailures);
Window.add(cSuccess);
Window.add(Successes);
Window.add(Failures);
Window.add(RunTimetime);
Window.add(RunTime);
Window.add(Browser);
Window.add(cBrowser);
Window.add(greeting);
Window.add(loopProgress);
Window.add(PBar);
setTitle("Module Tester - Running ");
setSize(900,600);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void setBrowser(String thebrowser){currentBrowser = thebrowser;}
public void setUser(String theUser){currentUser = theUser;}
public void setRouter(String theRouter){currentRouter = theRouter;}
public void setProgress(int set){currentProgress = set;}
public void setMaxProgress(int max){maxProgress = max;}
public void addFail(){tFails++;}
public void addSuccess(){tSuccesses++;}
public void setCurrentTest(String test){currentTest = test;}
private
int hours = 0;
int mins = 0;
int secs = 0;
String currentBrowser;
String currentUser;
String currentRouter;
int currentProgress = 0;
int maxProgress = 100;
int tFails = 0;
int tSuccesses = 0;
String currentTest;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
guiRun window = new guiRun();
window.setVisible(true);
}
});
}
}
use window.repaint() or jpanel.repaint()
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);
}
}