JPanel doesn't load when called after another JPanel - java

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()

Related

Error on getting values from an array in a thread (JAVA GUI SLOT MACHINE GAME)

I'm creating a slot machine game using java.After the user click the 'spin button' I need to get the values of the 3 pics which will be assigned to the 3 labels as slots in the GUI which is assigned by and array. But when i added threads to show the pictures changing in the array before assigning the last element to a slot, the proper values for the pics are not properly taken. instead it shows the values for the previous 3 pics which are assigned to the slots.
GUI class
public class SlotMachineGUI extends JFrame {
private JLabel titleLabel;
private JLabel pcnameLabel;
private JLabel symLbl;
private JLabel symLb2;
private JLabel symLb3;
private JLabel creditTxtLbl;
private JLabel creditValLbl;
private JLabel betTxtLbl;
private JLabel betValLbl;
private JLabel winsTxtLbl;
private JLabel winsValLbl;
private JLabel lossValLbl;
private JLabel lossTxtLbl;
private JButton spinBtn;
private JButton resetBtn;
private JButton addCoinBtn;
private JButton betOneBtn;
private JButton betMaxBtn;
private JButton startBtn;
private JPanel pcPanel;
private JPanel btnPanel;
private JPanel mainBtnPanel;
private JPanel detailPanel;
private JPanel mainPanel;
private JPanel namePanel;
private int count = 0;
private int creditV = 10;
private final int maxCredit = 3;
private int picVal1=0;
private int picVal2=0;
private int picVal3=0;
private int wonCredit=0;
int val1=0;
int val2 = 0;
int val3=0;
private int credit;
public SlotMachineGUI() {
setSize(800, 400);
//to title
titleLabel = new JLabel("--Slot Machine--");
titleLabel.setFont(new Font("", 2, 30));
titleLabel.setForeground(Color.decode("#FF0000"));
titleLabel.setHorizontalAlignment(JLabel.CENTER);
add("North", titleLabel);
pcPanel = new JPanel(new GridLayout(1, 3, 0, 0));
pcPanel.setBackground(Color.WHITE);
symLbl = new JLabel(new ImageIcon("src/cswrk2/clear.png"));
symLb2 = new JLabel(new ImageIcon("src/cswrk2/clear.png"));
symLb3 = new JLabel(new ImageIcon("src/cswrk2/clear.png"));
symLbl.setBorder(BorderFactory.createLineBorder(Color.black));
symLb2.setBorder(BorderFactory.createLineBorder(Color.black));
symLb3.setBorder(BorderFactory.createLineBorder(Color.black));
pcPanel.add(symLbl);
pcPanel.add(symLb2);
pcPanel.add(symLb3);
btnPanel = new JPanel(new GridLayout(2, 1, 0, 0));
btnPanel.setBackground(Color.decode("#310138"));
spinBtn = new JButton("Spin");
resetBtn = new JButton("Reset");
btnPanel.add(spinBtn);
btnPanel.add(resetBtn);
detailPanel = new JPanel(new GridLayout(2, 4, 0, 0));
detailPanel.setBackground(Color.decode("#000000"));
creditTxtLbl = new JLabel("Credit Left ");
creditTxtLbl.setFont(new Font("", 1, 14));
creditTxtLbl.setForeground(Color.white);
creditValLbl = new JLabel(String.valueOf(creditV));
creditValLbl.setFont(new Font("", 1, 14));
creditValLbl.setForeground(Color.white);
betTxtLbl = new JLabel("Bet ");
betTxtLbl.setFont(new Font("", 1, 14));
betTxtLbl.setForeground(Color.white);
betValLbl = new JLabel("0");
betValLbl.setFont(new Font("", 1, 14));
betValLbl.setForeground(Color.white);
winsTxtLbl = new JLabel("Wins ");
winsTxtLbl.setFont(new Font("", 1, 14));
winsTxtLbl.setForeground(Color.white);
winsValLbl = new JLabel("Wins Val ");
winsValLbl.setFont(new Font("", 1, 14));
winsValLbl.setForeground(Color.white);
lossTxtLbl = new JLabel("Wins ");
lossTxtLbl.setFont(new Font("", 1, 14));
lossTxtLbl.setForeground(Color.white);
lossValLbl = new JLabel("Wins Val ");
lossValLbl.setFont(new Font("", 1, 14));
lossValLbl.setForeground(Color.white);
detailPanel.add(creditTxtLbl);
detailPanel.add(creditValLbl);
detailPanel.add(betTxtLbl);
detailPanel.add(betValLbl);
detailPanel.add(winsTxtLbl);
detailPanel.add(winsValLbl);
detailPanel.add(lossTxtLbl);
detailPanel.add(lossValLbl);
mainPanel = new JPanel(new GridLayout(2, 1, 0, 0));
mainPanel.setBackground(Color.decode("#310138"));
mainPanel.add(pcPanel);
// mainPanel.add(btnPanel);
mainPanel.add(detailPanel);
add("East", btnPanel);
add("Center", mainPanel);
mainBtnPanel = new JPanel(new GridLayout(1, 4, 0, 0));
mainBtnPanel.setBackground(Color.decode("#310138"));
addCoinBtn = new JButton("Add Coin");
betOneBtn = new JButton("Bet One");
betMaxBtn = new JButton("Bet Max");
startBtn = new JButton("Starts");
mainBtnPanel.add(addCoinBtn);
mainBtnPanel.add(betOneBtn);
mainBtnPanel.add(betMaxBtn);
mainBtnPanel.add(startBtn);
add("South",mainBtnPanel);
setVisible(true);
addCoinBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
spinBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
{
Thread thread1 = new Thread(new Runnable() {
Reel spinner1 = new Reel();
//System.out.println(spinner1.spin());
Symbol[] url1 = spinner1.spin();
#Override
public void run() {
for (Symbol symbol : url1) {
try {
ImageIcon a=symbol.getImage();
Thread.sleep(100);
val1=symbol.getValue();
symLbl.setIcon(a);
} catch (InterruptedException ex) {
Logger.getLogger(SlotMachineGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
thread1.start();
picVal1=val1;
System.out.println(picVal1);
}
{
Thread thread2 = new Thread(new Runnable() {
Reel spinner2 = new Reel();
//System.out.println(spinner1.spin());
Symbol[] url2 = spinner2.spin();
#Override
public void run() {
for (Symbol symbol : url2) {
try {
ImageIcon a=symbol.getImage();
Thread.sleep(100);
val2=symbol.getValue();
symLb2.setIcon(a);
} catch (InterruptedException ex) {
Logger.getLogger(SlotMachineGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
thread2.start();
picVal1=val2;
System.out.println(picVal1);
}
{
Thread thread3 = new Thread(new Runnable() {
Reel spinner3 = new Reel();
//System.out.println(spinner1.spin());
Symbol[] url3 = spinner3.spin();
#Override
public void run() {
for (Symbol symbol : url3) {
try {
ImageIcon a=symbol.getImage();
Thread.sleep(100);
val3=symbol.getValue();
symLb3.setIcon(a);
} catch (InterruptedException ex) {
Logger.getLogger(SlotMachineGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
thread3.start();
picVal3=val3;
System.out.println(picVal3);
System.out.println();
}
//symLbl = new JLabel(new ImageIcon("src/cswrk2/Banana.png"));
if(val1==val2 && val2==val3 && val3==val1){
System.out.println("samanaaaaaaai");
wonCredit=((count)*picVal1);
creditV+=wonCredit;
creditValLbl.setText(String.valueOf(creditV));
betValLbl.setText(String.valueOf(0));
JOptionPane.showMessageDialog(startBtn,
"You won "+wonCredit+" credits",
"!!JACKPOT!!",
JOptionPane.PLAIN_MESSAGE);
}
}
});
betOneBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if(count<4){
betValLbl.setText(String.valueOf(count));
creditV--;
creditValLbl.setText(String.valueOf(creditV));
count++;
}else{
count--;
}
}
});
betMaxBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
creditV-=maxCredit;
//creditValLbl.setText(String.valueOf(creditV));
betValLbl.setText(String.valueOf(maxCredit));
}
});
startBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
}
public static void main(String[] args) {
SlotMachineGUI mainWindow = new SlotMachineGUI();
}
}
Reel Class
import java.util.Random;
public class Reel {
Symbol Cherry = new Symbol();
Symbol Lemon = new Symbol();
Symbol Plum = new Symbol();
Symbol WaterMellon = new Symbol();
Symbol Bell = new Symbol();
Symbol Seven = new Symbol();
public Reel(){
}
public Symbol[] spin(){
Symbol[] symArr=new Symbol[6];
Random r = new Random();
for (int i =0 ; i<symArr.length ; i++){
int randomNum = r.nextInt(6)+1;
//System.out.println(randomNum);
switch (randomNum) {
case 1:
Seven.setValue(7);
Seven.setImage();
symArr[i]=Seven;
break;
case 2:
Bell.setValue(6);
Bell.setImage();
symArr[i]=Bell;
break;
case 3:
WaterMellon.setValue(5);
WaterMellon.setImage();
symArr[i]=WaterMellon;
break;
case 4:
Plum.setValue(4);
Plum.setImage();
symArr[i]=Plum;
break;
case 5:
Lemon.setValue(3);
Lemon.setImage();
symArr[i]=Lemon;
break;
case 6:
Cherry.setValue(2);
Cherry.setImage();
symArr[i]=Cherry;
break;
}
}
return symArr;
}
}
Symbol Class(implements from ISymbol interface)
import javax.swing.ImageIcon;
public class Symbol implements ISymbol {
private int imgValue;
private ImageIcon imgPath;
#Override
public void setImage() {
//System.out.println("valur "+imgValue);
switch (imgValue) {
case 7:
ImageIcon svn = new ImageIcon("src/img/redseven.png");
imgPath = svn;
break;
case 6:
ImageIcon bell = new ImageIcon("src/img/bell.png");
imgPath = bell;
break;
case 5:
ImageIcon wmln = new ImageIcon("src/img/watermelon.png");
imgPath = wmln;
break;
case 4:
ImageIcon plum = new ImageIcon("src/img/plum.png");
imgPath = plum;
break;
case 3:
ImageIcon lmn = new ImageIcon("src/img/lemon.png");
imgPath = lmn;
break;
case 2:
ImageIcon chry = new ImageIcon("src/img/cherry.png");
imgPath = chry;
break;
}
//System.out.println(imgPath);
//System.out.println("Image value "+imgValue);
}
#Override
public void setValue(int v) {
// TODO Auto-generated method stub
this.imgValue=v;
}
#Override
public ImageIcon getImage() {
// TODO Auto-generated method stub
return imgPath;
}
#Override
public int getValue() {
// TODO Auto-generated method stub
return imgValue;
}
}
ISymbol interface
import javax.swing.ImageIcon;
public interface ISymbol {
public void setImage();
public ImageIcon getImage();
public void setValue(int v);
public int getValue();
}
Swing GUI components should only be updated from the Event Dispatch Thread (EDT).
If you are trying to update the GUI repeatedly with a fixed delay in between, consider using a Timer to perform the GUI updates. The Timer will fire an ActionEvent at the specified interval and that ActionEvent will be on the EDT so you can safely update Swing components.
If it takes a long, or indeterminate, time to determine which images to load (perhaps because they're being fetched from a service), then you might need to add a SwingWorker into the mix to avoid blocking the EDT while you wait for the array of images to be returned.
(I'll update my answer with an example of how to use these in your code if you post a SSCCE - at the moment the absence of the Reel and Symbol classes prevent your code from compiling)
* UPDATE *
After looking at the SSCCE, it appears the problem has more to do with threading in general rather than interaction between the EDT and worker threads. In the code below, I made a couple changes which I believe will address the problem you've described:
Moved logic that checks for winner onto a separate thread, resultThread, which starts the three spinners and waits on their completion before determining if the spin is a winner.
Removed the blocks around thread1, thread2 and thread3 so they could be referenced by resultThread
Moved swing component updates to EDT through use of SwingUtilities.invokeLater() (note: this Oracle's recommended practice for interacting with Swing components, however I do not believe it's a fundamental part of this solution)
SlotMachineGUI.java
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SlotMachineGUI extends JFrame {
private JLabel titleLabel;
private JLabel pcnameLabel;
private JLabel symLbl;
private JLabel symLb2;
private JLabel symLb3;
private JLabel creditTxtLbl;
private JLabel creditValLbl;
private JLabel betTxtLbl;
private JLabel betValLbl;
private JLabel winsTxtLbl;
private JLabel winsValLbl;
private JLabel lossValLbl;
private JLabel lossTxtLbl;
private JButton spinBtn;
private JButton resetBtn;
private JButton addCoinBtn;
private JButton betOneBtn;
private JButton betMaxBtn;
private JButton startBtn;
private JPanel pcPanel;
private JPanel btnPanel;
private JPanel mainBtnPanel;
private JPanel detailPanel;
private JPanel mainPanel;
private JPanel namePanel;
private int count = 0;
private int creditV = 10;
private final int maxCredit = 3;
private int picVal1 = 0;
private int picVal2 = 0;
private int picVal3 = 0;
private int wonCredit = 0;
int val1 = 0;
int val2 = 0;
int val3 = 0;
private int credit;
public SlotMachineGUI() {
setSize(800, 400);
//to title
titleLabel = new JLabel("--Slot Machine--");
titleLabel.setFont(new Font("", 2, 30));
titleLabel.setForeground(Color.decode("#FF0000"));
titleLabel.setHorizontalAlignment(JLabel.CENTER);
add("North", titleLabel);
pcPanel = new JPanel(new GridLayout(1, 3, 0, 0));
pcPanel.setBackground(Color.WHITE);
symLbl = new JLabel(new ImageIcon("src/cswrk2/clear.png"));
symLb2 = new JLabel(new ImageIcon("src/cswrk2/clear.png"));
symLb3 = new JLabel(new ImageIcon("src/cswrk2/clear.png"));
symLbl.setBorder(BorderFactory.createLineBorder(Color.black));
symLb2.setBorder(BorderFactory.createLineBorder(Color.black));
symLb3.setBorder(BorderFactory.createLineBorder(Color.black));
pcPanel.add(symLbl);
pcPanel.add(symLb2);
pcPanel.add(symLb3);
btnPanel = new JPanel(new GridLayout(2, 1, 0, 0));
btnPanel.setBackground(Color.decode("#310138"));
spinBtn = new JButton("Spin");
resetBtn = new JButton("Reset");
btnPanel.add(spinBtn);
btnPanel.add(resetBtn);
detailPanel = new JPanel(new GridLayout(2, 4, 0, 0));
detailPanel.setBackground(Color.decode("#000000"));
creditTxtLbl = new JLabel("Credit Left ");
creditTxtLbl.setFont(new Font("", 1, 14));
creditTxtLbl.setForeground(Color.white);
creditValLbl = new JLabel(String.valueOf(creditV));
creditValLbl.setFont(new Font("", 1, 14));
creditValLbl.setForeground(Color.white);
betTxtLbl = new JLabel("Bet ");
betTxtLbl.setFont(new Font("", 1, 14));
betTxtLbl.setForeground(Color.white);
betValLbl = new JLabel("0");
betValLbl.setFont(new Font("", 1, 14));
betValLbl.setForeground(Color.white);
winsTxtLbl = new JLabel("Wins ");
winsTxtLbl.setFont(new Font("", 1, 14));
winsTxtLbl.setForeground(Color.white);
winsValLbl = new JLabel("Wins Val ");
winsValLbl.setFont(new Font("", 1, 14));
winsValLbl.setForeground(Color.white);
lossTxtLbl = new JLabel("Wins ");
lossTxtLbl.setFont(new Font("", 1, 14));
lossTxtLbl.setForeground(Color.white);
lossValLbl = new JLabel("Wins Val ");
lossValLbl.setFont(new Font("", 1, 14));
lossValLbl.setForeground(Color.white);
detailPanel.add(creditTxtLbl);
detailPanel.add(creditValLbl);
detailPanel.add(betTxtLbl);
detailPanel.add(betValLbl);
detailPanel.add(winsTxtLbl);
detailPanel.add(winsValLbl);
detailPanel.add(lossTxtLbl);
detailPanel.add(lossValLbl);
mainPanel = new JPanel(new GridLayout(2, 1, 0, 0));
mainPanel.setBackground(Color.decode("#310138"));
mainPanel.add(pcPanel);
// mainPanel.add(btnPanel);
mainPanel.add(detailPanel);
add("East", btnPanel);
add("Center", mainPanel);
mainBtnPanel = new JPanel(new GridLayout(1, 4, 0, 0));
mainBtnPanel.setBackground(Color.decode("#310138"));
addCoinBtn = new JButton("Add Coin");
betOneBtn = new JButton("Bet One");
betMaxBtn = new JButton("Bet Max");
startBtn = new JButton("Starts");
mainBtnPanel.add(addCoinBtn);
mainBtnPanel.add(betOneBtn);
mainBtnPanel.add(betMaxBtn);
mainBtnPanel.add(startBtn);
add("South", mainBtnPanel);
setVisible(true);
addCoinBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
spinBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Thread thread1 = new Thread(new Runnable() {
Reel spinner1 = new Reel();
//System.out.println(spinner1.spin());
Symbol[] url1 = spinner1.spin();
#Override
public void run() {
for (Symbol symbol : url1) {
try {
ImageIcon a = symbol.getImage();
Thread.sleep(100);
val1 = symbol.getValue();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
symLbl.setIcon(a);
}
});
} catch (InterruptedException ex) {
Logger.getLogger(SlotMachineGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
picVal1 = val1;
System.out.println(picVal1);
Thread thread2 = new Thread(new Runnable() {
Reel spinner2 = new Reel();
//System.out.println(spinner1.spin());
Symbol[] url2 = spinner2.spin();
#Override
public void run() {
for (Symbol symbol : url2) {
try {
ImageIcon a = symbol.getImage();
Thread.sleep(100);
val2 = symbol.getValue();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
symLb2.setIcon(a);
}
});
} catch (InterruptedException ex) {
Logger.getLogger(SlotMachineGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
picVal1 = val2;
System.out.println(picVal1);
Thread thread3 = new Thread(new Runnable() {
Reel spinner3 = new Reel();
//System.out.println(spinner1.spin());
Symbol[] url3 = spinner3.spin();
#Override
public void run() {
for (Symbol symbol : url3) {
try {
ImageIcon a = symbol.getImage();
Thread.sleep(100);
val3 = symbol.getValue();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
symLb3.setIcon(a);
}
});
} catch (InterruptedException ex) {
Logger.getLogger(SlotMachineGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
picVal3 = val3;
System.out.println(picVal3);
System.out.println();
Thread resultThread = new Thread(new Runnable() {
#Override
public void run() {
thread1.start();
thread2.start();
thread3.start();
try {
thread1.join();
thread2.join();
thread3.join();
if (val1 == val2 && val2 == val3 && val3 == val1) {
System.out.println("samanaaaaaaai");
wonCredit = ((count) * picVal1);
creditV += wonCredit;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
creditValLbl.setText(String.valueOf(creditV));
betValLbl.setText(String.valueOf(0));
JOptionPane.showMessageDialog(startBtn,
"You won " + wonCredit + " credits",
"!!JACKPOT!!",
JOptionPane.PLAIN_MESSAGE);
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
resultThread.start();
}
});
betOneBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (count < 4) {
betValLbl.setText(String.valueOf(count));
creditV--;
creditValLbl.setText(String.valueOf(creditV));
count++;
} else {
count--;
}
}
});
betMaxBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
creditV -= maxCredit;
//creditValLbl.setText(String.valueOf(creditV));
betValLbl.setText(String.valueOf(maxCredit));
}
});
startBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
}
public static void main(String[] args) {
SlotMachineGUI mainWindow = new SlotMachineGUI();
}
}

Change JFrame Properties From JTabbedPane

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.

Java GUI Programming Only Restarts once

I have a program here that changes an avatars hat and earrings
the problem is that it only restarts once (the load button only works once)
This is what I have:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.JTextArea;
public class Lab14_Navarro extends JFrame {
private int x,y,z;
private Container game;
private JComboBox Head;
private JComboBox Ear;
private JLabel Avatar;
private JTextArea details;
private String []Hat = {"No Hat", "Captain Hat", "Black Leather Hat"};
private JButton load;
private String []Earrings = {"No Earrings", "Silver Dangling Earrings", "Gold Dangling Earrings"};
private ImageIcon [] Accessories =
{ new ImageIcon("blackleather.PNG"),//0
new ImageIcon("blackleather_goldear.PNG"),//1
new ImageIcon("blackleather_silverear.PNG"),//2
new ImageIcon("captainhat.PNG"),//3
new ImageIcon("captainhat_goldear.PNG"),//4
new ImageIcon("captainhat_silverear.PNG"),//5
new ImageIcon("goldear.PNG"),//6
new ImageIcon("noaccessories.PNG"),//7
new ImageIcon("silverear.PNG")};//8
/**
* Creates a new instance of <code>Lab14_Navarro</code>.
*/
public Lab14_Navarro() {
getContentPane().removeAll();
setTitle("Avatar!");
setSize(250,450);
setLocationRelativeTo(null);
game = getContentPane();
game.setLayout(new FlowLayout());
Head = new JComboBox(Hat);
Ear = new JComboBox(Earrings);
Avatar = new JLabel(Accessories[7]);
load = new JButton("Load Image");
details = new JTextArea("AVATAR DETAILS: "+"\n"+" Hat: "+Hat[Head.getSelectedIndex()]+"\n"+" Earrings: "+Earrings[Ear.getSelectedIndex()]);
game.add(Avatar);
game.add(Head);
game.add(Ear);
game.add(load);
game.add(details, BorderLayout.SOUTH);
setVisible(true);
details.setEditable(false);
Head.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox temphead = (JComboBox) e.getSource();
int temphat = (int) temphead.getSelectedIndex();
x = temphat;
}
});
Ear.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox tempear = (JComboBox) e.getSource();
int tempearrings = (int) tempear.getSelectedIndex();
y = tempearrings;
}
});
load.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
getContentPane().removeAll();
if(x==0&&y==0){
z = 7;
}
if(x==0&&y==1){
z = 8;
}
if(x==0&&y==2){
z = 6;
}
if(x==1&&y==0){
z = 3;
}
if(x==1&&y==1){
z = 5;
}
if(x==1&&y==2){
z = 4;
}
if(x==2&&y==0){
z = 0;
}
if(x==2&&y==1){
z = 2;
}
if(x==2&&y==2){
z = 1;
}
setTitle("Avatar");
setSize(250,450);
setLocationRelativeTo(null);
game = getContentPane();
game.setLayout(new FlowLayout());
Head = new JComboBox(Hat);
Ear = new JComboBox(Earrings);
Avatar = new JLabel(Accessories[z]);
load = new JButton("Load Image");
details = new JTextArea("AVATAR DETAILS: "+"\n"+" Hat: "+Hat[x]+"\n"+" Earrings: "+Earrings[y]);
game.add(Avatar);
game.add(Head);
game.add(Ear);
game.add(load);
game.add(details, BorderLayout.SOUTH);
setVisible(true);
details.setEditable(false);
}
});
}
public static void main(String[] args) {
Lab14_Navarro fs = new Lab14_Navarro();
fs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Any help is accepted thanks
I just started Java so I'm not that good... yet
When you write, for the second time:
load = new JButton("Load Image");
you're creating a new button, however, you are not giving it a new ActionListener
On another note, you don't need to create a new Button, your original load button is still there, you need only to add it to the contentPane again.

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

JComboBox is throwing a NullPointerException when told to addItemListener()

I am getting a NullPointerException on line 27 (listOfWindTurbines.addItemListener(new dropDownListener());) when I try to run my program. Please Help!
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class PlannerMain {
JFrame frame;
JButton makeMap;
JPanel panel;
JLabel outcome;
JComboBox listOfWindTurbines;
String[] windTurbineSpace = new String[10];
Integer[] windTurbineLengths = new Integer[10];
Integer[] windTurbineWidths = new Integer[10];
JTextField lengthOfRoom, widthOfRoom, widthObjectNeeds, lengthObjectNeeds;
int lengthOfRoomInt, widthOfRoomInt, widthObjectNeedsInt, lengthObjectNeedsInt, largerObjectMeasurement, numberOfItems, numberOfItemsShort;
public static void main(String[] args){
PlannerMain p = new PlannerMain();
}
public PlannerMain(){
windTurbineLengths[0] = 1;
windTurbineWidths[0] = 1;
for(int i = 0;i<=9;i++){
int wNum = i + 1;
windTurbineSpace[i] = "Windturbine "+ wNum;
}
listOfWindTurbines.addItemListener(new dropDownListener());
frame = new JFrame("Minecraft Land Planner");
outcome = new JLabel();
panel = new JPanel();
makeMap = new JButton("Make Map");
lengthOfRoom = new JTextField("Length of Room");
widthOfRoom = new JTextField("Width of Room");
widthObjectNeeds = new JTextField("Width Object Needs");
lengthObjectNeeds = new JTextField("Length Object Needs");
listOfWindTurbines = new JComboBox(windTurbineSpace);
makeMap.addActionListener(new makeMapListener());
frame.setSize(580,550);
frame.add(panel);
panel.add(makeMap);
panel.add(lengthOfRoom);
panel.add(widthOfRoom);
panel.add(lengthObjectNeeds);
panel.add(widthObjectNeeds);
panel.add(listOfWindTurbines);
panel.add(outcome);
frame.setVisible(true);
}
class makeMapListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
lengthOfRoomInt = Integer.parseInt(lengthOfRoom.getText());
widthOfRoomInt = Integer.parseInt(widthOfRoom.getText());
lengthObjectNeedsInt = Integer.parseInt(lengthObjectNeeds.getText());
widthObjectNeedsInt = Integer.parseInt(widthObjectNeeds.getText());
if(lengthObjectNeedsInt<=widthObjectNeedsInt){
largerObjectMeasurement = widthObjectNeedsInt;
}
if(widthObjectNeedsInt<=lengthObjectNeedsInt){
largerObjectMeasurement = lengthObjectNeedsInt;
}
numberOfItems = (lengthOfRoomInt/lengthObjectNeedsInt)*(widthOfRoomInt/widthObjectNeedsInt);
outcome.setText(String.valueOf(numberOfItems));
lengthOfRoom.setSize(30, 20);
widthOfRoom.setSize(30, 20);
widthObjectNeeds.setSize(30, 10);
lengthObjectNeeds.setSize(100, 20);
}
}
class dropDownListener implements ItemListener{
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED){
lengthObjectNeeds.setText(Integer.toString(windTurbineLengths[listOfWindTurbines.getSelectedIndex()]));
widthObjectNeeds.setText(Integer.toString(windTurbineLengths[listOfWindTurbines.getSelectedIndex()]));
}
}
}
}
You need to initialize the listOfWindTurbines variable, for example:
JComboBox listOfWindTurbines = new JComboBox();

Categories