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);
}
}
Related
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();
}
}
I'm trying to make a program that load 4 images, put it in 4 labels and change the icons of each label in the frame regarding the random number in the list, like if it was blinking the images. It need to blink each image in the order that is sorted in comecaJogo() but when I press the btnComecar in the actionPerformed all imagens seems to change at the same time:
Here is my logic class:
public class Logica {
List<Integer> seqAlea = new ArrayList<Integer>();
List<Integer> seqInsere = new ArrayList<Integer>();
int placar = 0;
boolean cabouGame = false;
Random geraNumero = new Random();
int numero;
Timer timer = new Timer(1500,null);
public void comecaJogo() {
for (int i = 0; i < 4; i++) {
numero = geraNumero.nextInt(4) + 1;
seqAlea.add(numero);
}
}
public void piscaImagen(ImageIcon img1, ImageIcon img1b, JLabel lbl) {
timer.addActionListener(new ActionListener() {
int count = 0;
#Override
public void actionPerformed(ActionEvent evt) {
if(lbl.getIcon() != img1){
lbl.setIcon(img1);
} else {
lbl.setIcon(img1b);
}
count++;
if(count == 2){
((Timer)evt.getSource()).stop();
}
}
});
timer.setInitialDelay(1250);
timer.start();
}
}
In the frame:
public class Main extends JFrame implements ActionListener {
JLabel lblImg1 = new JLabel();
JButton btnImg1 = new JButton("Economize Energia");
final URL resource1 = getClass().getResource("/br/unip/IMGs/img1.jpg");
final URL resource1b = getClass().getResource("/br/unip/IMGs/img1_b.png");
ImageIcon img1 = new ImageIcon(resource1);
ImageIcon img1b = new ImageIcon(resource1b);
JButton btnImg2 = new JButton("Preserve o Meio Ambiente");
JLabel lblImg2 = new JLabel("");
final URL resource2 = getClass().getResource("/br/unip/IMGs/img2.jpg");
final URL resource2b = getClass().getResource("/br/unip/IMGs/img2_b.jpg");
ImageIcon img2 = new ImageIcon(resource2);
ImageIcon img2b = new ImageIcon(resource2b);
JButton btnImg3 = new JButton("N\u00E3o \u00E0 polui\u00E7\u00E3o!");
JLabel lblImg3 = new JLabel("");
final URL resource3 = getClass().getResource("/br/unip/IMGs/img3.jpg");
final URL resource3b = getClass().getResource("/br/unip/IMGs/img3_b.jpg");
ImageIcon img3 = new ImageIcon(resource3);
ImageIcon img3b = new ImageIcon(resource3b);
JButton btnImg4 = new JButton("Recicle!");
JLabel lblImg4 = new JLabel("");
final URL resource4 = getClass().getResource("/br/unip/IMGs/img4.jpg");
final URL resource4b = getClass().getResource("/br/unip/IMGs/img4_b.jpg");
ImageIcon img4 = new ImageIcon(resource4);
ImageIcon img4b = new ImageIcon(resource4b);
Logica jogo = new Logica();
JButton btnComecar = new JButton("Come\u00E7ar");
public static void main(String[] args) {
Main window = new Main();
window.setVisible(true);
}
public Main() {
lblImg1.setIcon(img1b);
lblImg1.setBounds(78, 48, 250, 200);
add(lblImg1);
btnImg1.setBounds(153, 259, 89, 23);
btnImg1.addActionListener(this);
add(btnImg1);
setBounds(100, 100, 800, 600);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnImg2.setBounds(456, 272, 186, 23);
btnImg2.addActionListener(this);
lblImg2.setIcon(img2b);
lblImg2.setBounds(421, 61, 250, 200);
add(btnImg2);
add(lblImg2);
btnImg3.setBounds(114, 525, 186, 23);
btnImg3.addActionListener(this);
lblImg3.setIcon(img3b);
lblImg3.setBounds(78, 314, 250, 200);
add(lblImg3);
add(btnImg3);
btnImg4.setBounds(456, 525, 186, 23);
btnImg4.addActionListener(this);
lblImg4.setIcon(img4b);
lblImg4.setBounds(421, 314, 250, 200);
add(lblImg4);
add(btnImg4);
btnComecar.setBounds(68, 14, 89, 23);
btnComecar.addActionListener(this);
add(btnComecar);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(btnImg1)) {
jogo.piscaImagen(img1, img1b, lblImg1);
} else if (e.getSource().equals(btnComecar)) {
jogo.comecaJogo();
System.out.println(jogo.seqAlea);
for (int i = 0; i < jogo.seqAlea.size(); i++) {
switch (jogo.seqAlea.get(i)) {
case 1:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img1, img1b, lblImg1);
break;
case 2:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img2, img2b, lblImg2);
break;
case 3:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img3, img3b, lblImg3);
break;
case 4:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img4, img4b, lblImg4);
break;
}
}
}
}
}
Thanks for the help!
one at time, like a memory game :)
There are multitudes of ways this might work, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements ActionListener {
JButton btnImg1 = new JButton();
JButton btnImg2 = new JButton();
JButton btnImg3 = new JButton();
JButton btnImg4 = new JButton();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new Main();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public Main() {
JPanel buttons = new JPanel(new GridLayout(2, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
buttons.add(btnImg1);
buttons.add(btnImg2);
buttons.add(btnImg3);
buttons.add(btnImg4);
add(buttons);
JButton play = new JButton("Play");
add(play, BorderLayout.SOUTH);
play.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
List<JButton> sequence = new ArrayList<>(Arrays.asList(new JButton[]{btnImg1, btnImg2, btnImg3, btnImg4}));
Collections.shuffle(sequence);
Timer timer = new Timer(1000, new ActionListener() {
private JButton last;
#Override
public void actionPerformed(ActionEvent e) {
if (last != null) {
last.setBackground(null);
}
if (!sequence.isEmpty()) {
JButton btn = sequence.remove(0);
btn.setBackground(Color.RED);
last = btn;
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setInitialDelay(0);
timer.start();
}
}
This just places all the buttons into a List, shuffles the list and then the Timer removes the first button from the List until all the buttons have been "flashed".
Now this is just using the button's backgroundColor, so you'd need to create a class which allows you to associate the JButton with "on" and "off" images, these would then be added to the List and the Timer executed in a similar manner as above
So far I have this:
The logic is that:
a.)I will press the keybutton 'S' then the game will start
b.)The JTextArea will show the conversation of the users(note: I didn't disable it for debugging purposes)
c.)The JTextField will be the field the user will type text.
I have these working code:
package game;
//import
public class Game extends JFrame {
public static final String SERVER_IP = "localhost";
public static final int WIDTH = 1200;
public static final int HEIGHT = 800;
public static final int SCALE = 1;
private final int FPS = 60;
private final long targetTime = 1000 / FPS;
private BufferedImage backBuffer;
public KeyboardInput input;
private Stage stage;
public String username = "";
public GameClient client;
public static Game game;
public static String message = "";
private Tank tank;
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
public Game() throws HeadlessException {
setSize(1000, 1000);
addWindowListener(new WinListener());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
//setUndecorated(false);
addKeyListener(input);
setVisible(true);
}
public void init() {
this.game = this;
input = new KeyboardInput();
//this.setSize(WIDTH, HEIGHT);
//this.setLocationRelativeTo(null);
//this.setResizable(false);
Dimension expectedDimension = new Dimension(900, 50);
Dimension expectedDimension2 = new Dimension(100, 50);
jButton1 = new JButton("jButton1");
jTextArea1 = new JTextArea(6,6);
jTextArea1.setBounds(0,200,200,200);
jTextArea1.setBackground(Color.BLUE);
//jTextArea1.setFocusable(false);
jTextField1 = new JTextField("jTextField1");
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.add(jTextField1);
panel2.add(jButton1);
panel2.setBackground(Color.BLACK); // for debug only
panel2.setPreferredSize(expectedDimension);
panel2.setMaximumSize(expectedDimension);
panel2.setMinimumSize(expectedDimension);
jPanel1 = new JPanel();
jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.Y_AXIS));
jPanel1.add(jTextArea1);
jPanel1.add(panel2);
jPanel1.setBackground(Color.RED); // for debug only
jPanel1.setPreferredSize(expectedDimension2);
jPanel1.setMaximumSize(expectedDimension2);
jPanel1.setMinimumSize(expectedDimension2);
jScrollPane1 = new JScrollPane(jPanel1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
setContentPane(jScrollPane1);
System.out.println("init");
revalidate();
client = new GameClient(SERVER_IP, this);
backBuffer = new BufferedImage(800* SCALE,600 * SCALE, BufferedImage.TYPE_INT_RGB);
}
public Stage getStage() {
return stage;
}
public class WinListener extends WindowAdapter {
#Override
public void windowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}
}
public void disconnect() {
Packet01Disconnect p = new Packet01Disconnect(username);
p.writeData(client);
client.closeSocket();
System.exit(0);
}
private Font font = new Font("Munro Small", Font.PLAIN, 96);
private Font font2 = new Font("Munro Small", Font.PLAIN, 50);
private Font fontError = new Font("Munro Small", Font.PLAIN, 25);
private int op = 0;
public void updateMenu() {
if (input.up.isPressed()) {
if (op == 1) {
op = 0;
} else {
op++;
}
input.up.toggle(false);
} else if (input.down.isPressed()) {
if (op == 0) {
op = 1;
} else {
op--;
}
input.down.toggle(false);
} else if (input.enter.isPressed() && op == 0) {
runningMenu = false;
input.enter.toggle(false);
} else if (input.enter.isPressed() && op == 1) {
System.exit(0);
}
}
public void drawMenu() {
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setFont(font);
bbg.setColor(Color.white);
bbg.drawString("Sample", 189, 180);
bbg.setFont(font2);
if (op == 0) {
bbg.setColor(Color.red);
bbg.drawString("Start", 327, 378);
bbg.setColor(Color.white);
bbg.drawString("Quit", 342, 425);
} else if (op == 1) {
bbg.setColor(Color.white);
bbg.drawString("Start", 327, 378);
bbg.setColor(Color.red);
bbg.drawString("Quit", 342, 425);
}
g.drawImage(backBuffer, 0, 0, this);
}
public void draw() {
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setColor(Color.black);
bbg.fillRect(0, 0, WIDTH, HEIGHT);
stage.drawStage(bbg, this);
for (Tank t : stage.getPlayers()) {
t.draw(bbg, SCALE, this);
}
g.drawImage(backBuffer, 0, 0, this);
}
public void update() {
tank.update(stage);
stage.update();
}
private long time = 0;
public void updateLogin() {
if (username.length() < 8) {
if (input.letter.isPressed()) {
username += (char) input.letter.getKeyCode();
input.letter.toggle(false);
}
}
if (input.erase.isPressed() && username.length() > 0) {
username = username.substring(0, username.length() - 1);
input.erase.toggle(false);
}
if (input.enter.isPressed() && username.length() > 0) {
input.enter.toggle(false);
time = System.currentTimeMillis();
Packet00Login packet = new Packet00Login(username, 0, 0, 0);
packet.writeData(client);
}
if (message.equalsIgnoreCase("connect server success")) {
time = 0;
runningLogin = false;
return;
}
if (message.equalsIgnoreCase("Username already exists")) {
drawLogin();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
message = "";
username = "";
time = 0;
}
if (message.equalsIgnoreCase("Server full")) {
drawLogin();
try {
Thread.sleep(2000);
} catch (Exception e) {
}
System.exit(0);
}
if (time != 0 && message.equals("") && (System.currentTimeMillis() - time) >= 5000) {
message = "cannot connect to the server";
drawLogin();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
}
message = "";
time = 0;
}
}
public void drawLogin() {
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setColor(Color.black);
bbg.fillRect(0, 0, 800, 600);
bbg.setColor(Color.red);
bbg.setFont(fontError);
bbg.drawString(message, 100, 100);
bbg.setFont(font2);
bbg.setColor(Color.white);
bbg.drawString("Username", 284, 254);
bbg.setColor(Color.red);
bbg.drawString(username, 284, 304);
g.drawImage(backBuffer, 0, 0, this);
}
public static String waitPlayers = "Waiting for others players";
public String auxWaitPlayers = waitPlayers;
public static int quantPlayers = 0;
public class StringWait extends Thread {
public void run() {
while (true) {
try {
waitPlayers = "waiting for others players";
Thread.sleep(1000);
waitPlayers = "waiting for others players.";
Thread.sleep(1000);
waitPlayers = "waiting for others players..";
Thread.sleep(1000);
waitPlayers = "waiting for others players...";
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
public void updateWaitPlayers() {
if (quantPlayers == 1) {
runningWaitPlayer = false;
}
}
public void drawWaitPlayers() {
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setColor(Color.black);
bbg.fillRect(0, 0, 800, 600);
bbg.setColor(Color.white);
bbg.setFont(fontError);
bbg.drawString(waitPlayers, 100, 100);
g.drawImage(backBuffer, 0, 0, this);
}
public boolean runningMenu = true, runningLogin = true, runningWaitPlayer = true, runningGame = true;
public int op2 = 0;
public void start() {
long start;
long elapsed;
long wait;
init();
while (true) {
runningGame = true;
runningMenu = true;
runningWaitPlayer = true;
runningLogin = true;
switch (op2) {
//..
}
}
public void setGameState(boolean state) {
//...
}
public static void main(String[] args) throws InterruptedException {
Game g = new Game();
Thread.sleep(1000);
g.start();
}
}
And these is my objective interface:
I hope someone will help me with my problem.
Set the "main" containers layout manager to BorderLayout
On to this, add the GameInterface in the BorderLayout.CENTER position
Create another ("interaction") container and set it's layout manager to BorderLayout, add this to the "main" container's BorderLayout.SOUTH position
Wrap the JTextArea in a JScrollPane and add it to the BorderLayout.CENTER position of your "interaction" container
Create another container ("message"), this could use a GridBagLayout. On to this add the JTextField (with GridBagConstraints#weightx set to 0 and GridBagConstraints#weightx set to 1) and add the button to the next cell (GridBagConstraints#gridx set to 1 and GridBagConstraints#weightx set to 0)
For more details, see:
Laying Out Components Within a Container
How to Use Borders
How to Use GridBagLayout
Note:
Graphics g = getGraphics(); is NOT how custom painting should be done. Instead, override the paintComponent of a component like JPanel and perform your custom painting there!
For more details see
Painting in AWT and Swing
Performing Custom Painting
Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JPanel master = new JPanel(new BorderLayout());
master.setBackground(Color.BLUE);
JPanel gameInterface = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
};
gameInterface.setBackground(Color.MAGENTA);
master.add(gameInterface);
JPanel interactions = new JPanel(new BorderLayout());
interactions.add(new JScrollPane(new JTextArea(5, 20)));
JTextField field = new JTextField(15);
JButton btn = new JButton("Button");
JPanel message = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
message.add(field, gbc);
gbc.gridx = 1;
gbc.weightx = 0;
message.add(btn, gbc);
interactions.add(message, BorderLayout.SOUTH);
master.add(interactions, BorderLayout.SOUTH);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(master);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
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 java application - a calculator. I want to resize font of buttons dynamically with resizing the window of the app. How to implement it?
My idea is using ComponentEvents. I have initial size of the window of application and initial fonts' sizes. I want to change font size according to button's size, affected by window size change. The problem is how to use the ratio [initial window size] / [initial font size] in the overriden method? The ratio is different for each font.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
public class Main extends JFrame {
public Main() {
super("Test");
JPanel cPane = (JPanel) getContentPane();
cPane.setLayout(new BorderLayout());
MyButton sampleButton = new MyButton("Sample text");
sampleButton.setFont(new Font("Sans Serif", Font.PLAIN, 20));
MyButton a, b, c, d;
a = new MyButton("a");
b = new MyButton("b");
c = new MyButton("c");
d = new MyButton("d");
cPane.add(a, BorderLayout.PAGE_START);
cPane.add(b, BorderLayout.PAGE_END);
cPane.add(c, BorderLayout.LINE_START);
cPane.add(d, BorderLayout.LINE_END);
cPane.add(sampleButton, BorderLayout.CENTER);
setSize(300, 200);
setResizable(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String... args) {
new Main();
}
class MyButton extends JButton implements ComponentListener {
public MyButton(String title) {
super(title);
}
#Override
public void componentResized(ComponentEvent e) {
//resizing font
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
}
}
See how you go with this code using GlyphVector to determine the largest Font that will fit.
The GUI was a little shaky unless there was a delay between setting the frame visible and adding the ComponentListener. I solved that by delaying adding the listener using a single shot Swing Timer.
Is is based on Calculet which is a fully functioning (if simple) calculator using the ScriptEngine.
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
import javax.script.*;
import javax.swing.border.Border;
class SwingCalculator implements ActionListener, KeyListener {
JTextField io;
ScriptEngine engine;
ArrayList<JButton> controls;
final BufferedImage textImage = new BufferedImage(
100, 100,
BufferedImage.TYPE_INT_ARGB);
public int getMaxFontSizeForControls() {
Graphics2D g = textImage.createGraphics();
FontRenderContext frc = g.getFontRenderContext();
int maxSize = 500;
for (JButton b : controls) {
// skip the = button..
if (!b.getText().equals("=")) {
int max = getMaxFontSizeForControl(b, frc);
if (maxSize > max) {
maxSize = max;
}
}
}
g.dispose();
return maxSize;
}
public int getMaxFontSizeForControl(JButton button, FontRenderContext frc) {
Rectangle r = button.getBounds();
Insets m = button.getMargin();
Insets i = button.getBorder().getBorderInsets(button);
Rectangle viewableArea = new Rectangle(
r.width -
(m.right + m.left + i.left + i.right),
r.height -
(m.top + m.bottom + i.top + i.bottom)
);
Font font = button.getFont();
int size = 1;
boolean tooBig = false;
while (!tooBig) {
Font f = font.deriveFont((float) size);
GlyphVector gv = f.createGlyphVector(frc, button.getText());
Rectangle2D box = gv.getVisualBounds();
if (box.getHeight() > viewableArea.getHeight()
|| box.getWidth() > viewableArea.getWidth()) {
tooBig = true;
size--;
}
size++;
}
return size;
}
SwingCalculator() {
// obtain a reference to the JS engine
engine = new ScriptEngineManager().getEngineByExtension("js");
JPanel gui = new JPanel(new BorderLayout(2, 2));
controls = new ArrayList<JButton>();
JPanel text = new JPanel(new GridLayout(0, 1, 3, 3));
gui.add(text, BorderLayout.NORTH);
io = new JTextField(15);
Font font = io.getFont();
font = font.deriveFont(font.getSize() * 1.7f);
io.setFont(font);
io.setHorizontalAlignment(SwingConstants.TRAILING);
io.setFocusable(false);
text.add(io);
JPanel buttons = new JPanel(new GridLayout(4, 4, 2, 2));
gui.add(buttons, BorderLayout.CENTER);
addButton(buttons, "7");
addButton(buttons, "8");
addButton(buttons, "9");
addButton(buttons, "/");
addButton(buttons, "4");
addButton(buttons, "5");
addButton(buttons, "6");
addButton(buttons, "*");
addButton(buttons, "1");
addButton(buttons, "2");
addButton(buttons, "3");
addButton(buttons, "-");
addButton(buttons, "0");
addButton(buttons, ".");
addButton(buttons, "C");
addButton(buttons, "+");
JButton equals = new JButton("=");
equals.addKeyListener(this);
controls.add(equals);
equals.addActionListener(this);
gui.add(equals, BorderLayout.EAST);
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
final JFrame f = new JFrame("Calculet");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(gui);
f.pack();
f.setMinimumSize(f.getSize());
f.setLocationByPlatform(true);
f.setVisible(true);
final ComponentListener cl = new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
int ii = getMaxFontSizeForControls();
for (JButton b : controls) {
if (!b.getText().equals("=")) {
b.setFont(b.getFont().deriveFont((float) ii));
}
}
}
};
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
f.addComponentListener(cl);
}
};
Timer t = new Timer(500, al);
t.setRepeats(false);
t.start();
}
public void addButton(Container c, String text) {
JButton b = new JButton(text);
b.addActionListener(this);
b.addKeyListener(this);
controls.add(b);
c.add(b);
}
public void calculateResult() {
try {
Object result = engine.eval(io.getText());
if (result == null) {
io.setText("Output was 'null'");
} else {
io.setText(result.toString());
}
} catch (ScriptException se) {
io.setText(se.getMessage());
}
}
public void actionPerformed(ActionEvent ae) {
String command = ae.getActionCommand();
if (command.equals("C")) {
io.setText("");
} else if (command.equals("=")) {
calculateResult();
} else {
io.setText(io.getText() + command);
}
}
private JButton getButton(String text) {
for (JButton button : controls) {
String s = button.getText();
if (text.endsWith(s)
|| (s.equals("=")
&& (text.equals("Equals") || text.equals("Enter")))) {
return button;
}
}
return null;
}
/*
* START - Because I hate mice.
*/
public void keyPressed(KeyEvent ke) {
}
public void keyReleased(KeyEvent ke) {
String s = ke.getKeyText(ke.getKeyCode());
JButton b = getButton(s);
if (b != null) {
b.requestFocusInWindow();
b.doClick();
}
}
public void keyTyped(KeyEvent ke) {
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new SwingCalculator();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
Compare the approaches shown here and here. The former uses an available JComponent.sizeVariant.
The latter cites an example using FontMentrics.
Or TextLayout.