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();
}
}
How to make TableView with query select * from tableXXX where status='1'
if status = 1 data shown in jtable
else if status = 0 data not shown in jtable
or how to refresh jtable after status updated from 1 to 0`
This mycode
public class ViewDapur extends JInternalFrame implements ListenerDapur, ListSelectionListener{
private static final long serialVersionUID = -1108049190501656840L;
Connection konek;
Statement state;
//private ControllerDapur controllermak,controllermin;
private ModelDapur modelmak,modelmin;
private TableModelDapur tableModelmak, tableModelmin;
private JTable table;
private JTable tablemak;
private JTable tablemin;
public JTable getInputTable(){
return table;
}
public ViewDapur() {
setSize(1320, 590);
setTitle("DATA ORDERAN TRIPLE SIX");
setMaximizable(false);
setIconifiable(true);
setClosable(true);
setResizable(true);
setFrameIcon(new ImageIcon(ViewDapur.class.getResource("/com/sun/javafx/scene/web/skin/Undo_16x16_JFX.png")));
setBorder(new MatteBorder(2, 2, 2, 2, (Color) Color.MAGENTA));
setNormalBounds(new Rectangle(20, 0, 0, 0));
//controllermak = new ControllerPramusaji();
tableModelmak = new TableModelDapur();
modelmak = new ModelDapur();
modelmak.setListener(this);
//controllermak.setModel(modelmak);
//controllermin = new ControllerPramusaji();
tableModelmin = new TableModelDapur();
modelmin = new ModelDapur();
modelmin.setListener(this);
//controllermin.setModel(modelmin);
init();
tablemak.setModel(tableModelmak);
tablemak.getTableHeader().setReorderingAllowed(false);
tablemin.setModel(tableModelmin);
tablemin.getTableHeader().setReorderingAllowed(false);
try {
loadDatabasemak();
} catch (Exception ex) {
// TODO: handle exception
}
try {
loadDatabasemin();
} catch (Exception ex) {
// TODO: handle exception
}
/* Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
viewTabelMakanan("1");
viewTabelMinuman("1");
}
});
timer.start();timer.setRepeats(false);
*/ //refreshTablemamin();
//viewTabelMakanan("1");
//viewTabelMinuman("1");
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//Timer timer = new Timer(1000, new ActionListener() {
// public void actionPerformed(ActionEvent e) {
ViewDapur frame = new ViewDapur();
frame.setVisible(true);
// }
// });
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
#SuppressWarnings({ "rawtypes", "unchecked" })
private void init(){
JPanel panel = new JPanel();
panel.setBackground(new Color(119, 136, 153));
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "......"));
getContentPane().add(panel);
panel.setLayout(null);
tablemak = new JTable();
tablemak.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"No Meja", "Menu", "Jumlah", "No Antri"
}
));
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 11, 640, 540);
panel_2.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Daftar Order Makanan"));
panel_2.setLayout(null);
panel_2.add(tablemak);
panel.add(panel_2);
JScrollPane scrollPane2 = new JScrollPane(tablemak,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setBounds(10, 26, 616, 502);
panel_2.add(scrollPane2);
scrollPane2.setViewportView(tablemak);
JPanel panel_1 = new JPanel();
panel_1.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Daftar Order Minuman"));
panel_1.setBounds(660, 11, 650, 537);
panel.add(panel_1);
panel_1.setLayout(null);
tablemin = new JTable();
tablemin.setBounds(241, 24, 0, 0);
panel_1.add(tablemin);
JScrollPane scrollPane = new JScrollPane(tablemin,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(10, 25, 627, 501);
panel_1.add(scrollPane);
scrollPane.setViewportView(tablemin);
}
private void loadDatabasemak() throws ErrorInfo, SQLException{
DAOdapur daovi = UtilGlobal.getDAOdapur();
tableModelmak.setList(daovi.selectAll());
}
private void loadDatabasemin() throws ErrorInfo, SQLException{
DAOdapur daovi = UtilGlobal.getDAOdapur();
tableModelmin.setList(daovi.selectAll2());
}
#Override
public void valueChanged(ListSelectionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDelete() {
// TODO Auto-generated method stub
}
#Override
public void onChange(ModelDapur model) {
// TODO Auto-generated method stub
}
public void refreshTablemamin() {
tablemak.revalidate();
tablemak.repaint();
tablemak.getSelectionModel().clearSelection();
tablemin.revalidate();
tablemin.repaint();
tablemin.getSelectionModel().clearSelection();
tableModelmak.fireTableDataChanged();
tableModelmin.fireTableDataChanged();
}
public void viewTabelMakanan(String status){
//mejahe="";
try {
konek = Koneksi.getKoneksi();
state = konek.createStatement();
String query = "select * from tbtrans where katmenu='MAKANAN' AND stord='"+status+"' AND stdpr='0'";
ResultSet result= state.executeQuery(query);
while(result.next()){
Dapur p = new Dapur();
p.setNokey(result.getString("nokey"));
p.setNovisitor(result.getString("novisitor"));
p.setNomeja(result.getInt("nomeja"));
p.setNoantri(result.getInt("noantri"));
p.setAddedpeg(result.getString("addedpeg"));
p.setKdmc(result.getInt("kdmc"));
p.setMncafe(result.getString("mncafe"));
p.setKatmenu(result.getString("katmenu"));
p.setQty(result.getDouble("qty"));
p.setHrg(result.getDouble("hrg"));
p.setSubtotal(result.getDouble("subtotal"));
p.setWorder(result.getString("worder"));
p.setStord(result.getInt("stord"));
p.setWsaji(result.getString("wsaji"));
p.setStdpr(result.getInt("stdpr"));
p.setStkasir(result.getInt("stkasir"));
p.setPegkasir(result.getString("pegkasir"));
tableModelmak.add(p);
tableModelmak.fireTableDataChanged();
}
}
catch(Exception e){
e.printStackTrace();
}
//Pramusaji p = new Pramusaji();
}
public void viewTabelMinuman(String status){
//mejahe="";
try {
konek = Koneksi.getKoneksi();
state = konek.createStatement();
String query = "select * from tbtrans where katmenu='MINUMAN' AND stord='"+status+"' AND stdpr='0'";
ResultSet result= state.executeQuery(query);
while(result.next()){
Dapur p = new Dapur();
p.setNokey(result.getString("nokey"));
p.setNovisitor(result.getString("novisitor"));
p.setNomeja(result.getInt("nomeja"));
p.setNoantri(result.getInt("noantri"));
p.setAddedpeg(result.getString("addedpeg"));
p.setKdmc(result.getInt("kdmc"));
p.setMncafe(result.getString("mncafe"));
p.setKatmenu(result.getString("katmenu"));
p.setQty(result.getDouble("qty"));
p.setHrg(result.getDouble("hrg"));
p.setSubtotal(result.getDouble("subtotal"));
p.setWorder(result.getString("worder"));
p.setStord(result.getInt("stord"));
p.setWsaji(result.getString("wsaji"));
p.setStdpr(result.getInt("stdpr"));
p.setStkasir(result.getInt("stkasir"));
p.setPegkasir(result.getString("pegkasir"));
tableModelmin.add(p);
tableModelmin.fireTableDataChanged();
}
}
catch(Exception e){
e.printStackTrace();
}
//Pramusaji p = new Pramusaji();
}
}
from my MainFrame I create a internal Frame and add that to my desktop pane, but the internal Frame just won't show up. I tried to figure it out for 3 hours now and I kinda need some help with it. Before I implemented the observer pattern it just worked fine. So I thought it got something to do with that and changed some stuff and double checked the crucial code. No solution so far. I just realized how crappy my english is sometimes. Sorry for that!
The 2 code blocks are already shortened. Sorry that they are still pretty long. But I am just not sure where I made the mistake. If you need more code or anything else, just tell me. Thank you very much in advance.
This is the code of my main frame:
public class LangtonsAmeise extends JFrame implements ActionListener {
private JDesktopPane desk;
private JPanel panelButtons;
JMenuBar jmb;
JMenu file,modus;
JMenuItem load,save, exit, mSetzen,mMalen,mLaufen;
JSlider slider;
static int xInt, yInt,xFrame=450,yFrame=450;
static boolean bSetzen = false, bMalen = false, running = false;
Random randomGenerator = new Random();
JLabel xLabel, yLabel, speed, statusText,status;
JButton start, stop, addAnt;
JTextField xField, yField;
public LangtonsAmeise() {
// Desktop
desk = new JDesktopPane();
getContentPane().add(desk, BorderLayout.CENTER);
/* Those 4 lines work just fine. Internal Frame gets displayed.
JInternalFrame j = new JInternalFrame();
desk.add(j);
j.setSize(new Dimension(300,300));
j.setVisible(true);
*/
speed = new JLabel("Geschwindigkeit");
xLabel = new JLabel("x:");
yLabel = new JLabel("y:");
xLabel.setHorizontalAlignment(JLabel.RIGHT);
yLabel.setHorizontalAlignment(JLabel.RIGHT);
xLabel.setOpaque(true);
yLabel.setOpaque(true);
xField = new JTextField();
yField = new JTextField();
xField.setDocument(new IntegerDocument(2));
yField.setDocument(new IntegerDocument(2));
start = new JButton("Fenster erstellen");
stop = new JButton("Stopp");
start.setMargin(new Insets(0, 0, 0, 0));
stop.setMargin(new Insets(0, 0, 0, 0));
// Buttons
panelButtons = new JPanel();
panelButtons.setLayout(new GridLayout());
panelButtons.add(start);
panelButtons.add(xLabel);
panelButtons.add(xField);
panelButtons.add(yLabel);
panelButtons.add(yField);
panelButtons.add(speed);
panelButtons.add(slider);
panelButtons.add(new Panel());
panelButtons.add(stop);
start.addActionListener(this);
stop.addActionListener(this);
add(panelButtons, BorderLayout.NORTH);
statusText = new JLabel("Aktueller Modus:");
status = new JLabel("Stopp");
// JMenuBar
jmb = new JMenuBar();
setJMenuBar(jmb);
file = new JMenu("Datei");
modus = new JMenu("Modus");
mLaufen = new JMenuItem("Laufen");
mMalen = new JMenuItem("Malen");
mSetzen = new JMenuItem("Setzen");
load = new JMenuItem("Simulation laden");
save = new JMenuItem("Simulation speichern");
mSetzen.addActionListener(this);
mMalen.addActionListener(this);
mLaufen.addActionListener(this);
exit = new JMenuItem("Exit");
file.add(save);
file.add(load);
file.addSeparator();
file.add(exit);
save.addActionListener(this);
load.addActionListener(this);
modus.add(mLaufen);
modus.add(mSetzen);
modus.add(mMalen);
jmb.add(file);
jmb.add(modus);
for (int i = 0; i < 20; i++) {
jmb.add(new JLabel(" "));
}
jmb.add(statusText);
jmb.add(status);
setSize(new Dimension(1000, 900));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height
/ 2 - this.getSize().height / 2);
xField.setText("5");
yField.setText("5");
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Fenster erstellen")) {
if (xField.getText().equals("") || yField.getText().equals("")) {
new popUpWindow(
"Sie müssen eine Zahl zwischen 2 und 99 angeben!!");
} else {
xInt = Integer.parseInt(xField.getText());
yInt = Integer.parseInt(yField.getText());
state s = new state();
kindFenster k = new kindFenster(s, xInt, yInt);
s.addObserver(k);
addChild(k, this.getSize().width, this.getSize().height);
}
}
if (e.getActionCommand().equals("Stopp")) {
running=!running;
status.setText("Stopp");
}
}
public void addChild(JInternalFrame kind, int xPixel, int yPixel) {
// kind.setSize(370, 370);
kind.setLocation(randomGenerator.nextInt(xPixel - kind.getSize().height),
randomGenerator.nextInt(yPixel - kind.getSize().height - 100));
kind.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
desk.add(kind);
kind.setVisible(true);
kind.repaint();
kind.validate();
}
public static void main(String[] args) {
LangtonsAmeise hauptFenster = new LangtonsAmeise();
}
}
And this is my Internal Frame:
public class kindFenster extends JInternalFrame implements ActionListener,
Serializable,Observer {
/**
*
*/
private static final long serialVersionUID = 8939449766068226519L;
static int nr = 0;
static int x,y,xScale,yScale,xFrame,yFrame;
static int sleeptime;
state s;
ArrayList<JButton> jbArray = new ArrayList<>();
ArrayList<ImageIcon> ameisen = new ArrayList<ImageIcon>();
public static ArrayList<AmeiseThread> threadList = new ArrayList<>();
Color alteFarbe, neueFarbe;
JButton save, addAnt;
JPanel panelButtonsKind;
JSlider sliderKind;
public JPanel panelSpielfeld;
static SetzenActionListener sal = new SetzenActionListener();
static MouseMotionActionListener mmal = new MouseMotionActionListener();
public kindFenster(state s,int x, int y) {
super("Kind " + (++nr), true, true, true, true);
setLayout(new BorderLayout());
this.s=s;
setSize(new Dimension(xFrame, yFrame));
panelSpielfeld = new JPanel();
panelSpielfeld.setLayout(new GridLayout(y, x));
panelButtonsKind = new JPanel();
panelButtonsKind.setLayout(new GridLayout(1, 3));
save = new JButton("Simulation speichern");
addAnt = new JButton("Ameise hinzufügen");
save.setMargin(new Insets(0, 0, 0, 0));
addAnt.setMargin(new Insets(0, 0, 0, 0));
addAnt.addActionListener(this);
save.addActionListener(this);
sliderKind = new JSlider(JSlider.HORIZONTAL, 1, 10, 5);
sliderKind.setSnapToTicks(true);
sliderKind.setPaintTicks(true);
sliderKind.setPaintTrack(true);
sliderKind.setMajorTickSpacing(1);
sliderKind.setPaintLabels(true);
sliderKind.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (threadList.size() >= 0) {
for (AmeiseThread t : threadList) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
int speed = source.getValue();
sleeptime = 1000 / speed;
}
}
}
}
});
panelButtonsKind.add(save);
panelButtonsKind.add(sliderKind);
panelButtonsKind.add(addAnt);
add(panelButtonsKind, BorderLayout.NORTH);
add(panelSpielfeld, BorderLayout.CENTER);
this.addComponentListener(new MyComponentAdapter());
setVisible(true);
repaint();
validate();
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Ameise hinzufügen")) {
threadList.add(new AmeiseThread(this));
threadList.get(threadList.size() - 1).start();
}
if (e.getActionCommand().equals("Simulation speichern")) {
OutputStream fos = null;
try {
fos = new FileOutputStream("test");
ObjectOutputStream o = new ObjectOutputStream(fos);
o.writeObject(this );
} catch (IOException e1) {
System.err.println(e1);
} finally {
try {
fos.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
I think it is because you didn't set size for your JInternalFrame. In your code it is as a comment:
//kind.setSize(370, 370);
when I remove "//" it works for me.
So I'm creating a game in Java and I ran into a little problem. Whenever I run the application the GUI does not show on the screen and the only way to close the application is to use the Windows Task Manager. In the application, you choose a username and click an enter button which creates a new window in which the game is played. But after you click the button, none of the GUI loads and you can't close the application.
Basically, when you click the button, a method is called that disposes the current window and starts the game window. The code for that method is below:
public void login(String name) {
String[] args={};
dispose();
SingleplayerGUI.main(args);
}
And here is the code of the SingleplayerGUI class:
public SingleplayerGUI(String userName, Singleplayer sp) {
this.userName = userName;
setResizable(false);
setTitle("Console Clash Singleplayer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(880, 550);
setLocationRelativeTo(null);
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
} catch (IOException e1) {
e1.printStackTrace();
}
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] { 28, 815, 30, 7 }; // SUM = 880
gbl_contentPane.rowHeights = new int[] { 25, 485, 40 }; // SUM = 550
contentPane.setLayout(gbl_contentPane);
history = new JTextPane();
history.setEditable(false);
JScrollPane scroll = new JScrollPane(history);
caret = (DefaultCaret) history.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints scrollConstraints = new GridBagConstraints();
scrollConstraints.insets = new Insets(0, 0, 5, 5);
scrollConstraints.fill = GridBagConstraints.BOTH;
scrollConstraints.gridx = 0;
scrollConstraints.gridy = 0;
scrollConstraints.gridwidth = 2;
scrollConstraints.gridheight = 2;
scrollConstraints.weightx = 1;
scrollConstraints.weighty = 1;
scrollConstraints.insets = new Insets(0, 0, 5, -64);
contentPane.add(scroll, scrollConstraints);
txtMessage = new JTextField();
txtMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
}
});
GridBagConstraints gbc_txtMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(0, 0, 0, 25);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(txtMessage, gbc_txtMessage);
chat = new JTextPane();
chat.setEditable(false);
JScrollPane chatscroll = new JScrollPane(chat);
caret = (DefaultCaret) chat.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints chatscrollConstraints = new GridBagConstraints();
chatscrollConstraints.insets = new Insets(0, 0, 5, 5);
chatscrollConstraints.fill = GridBagConstraints.BOTH;
chatscrollConstraints.gridx = 0;
chatscrollConstraints.gridy = 0;
chatscrollConstraints.gridwidth = 2;
chatscrollConstraints.gridheight = 2;
chatscrollConstraints.weightx = 1;
chatscrollConstraints.weighty = 1;
chatscrollConstraints.insets = new Insets(150, 600, 5, -330);
contentPane.add(chatscroll, chatscrollConstraints);
chatMessage = new JTextField();
final String name = this.userName;
chatMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
chatconsole(name + ": " + chatMessage.getText());
}
}
});
GridBagConstraints gbc_chatMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(000, 600, 000, -330);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(chatMessage, gbc_txtMessage);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
});
GridBagConstraints gbc_btnSend = new GridBagConstraints();
gbc_btnSend.insets = new Insets(0, 0, 0, 275);
gbc_btnSend.gridx = 2;
gbc_btnSend.gridy = 2;
gbc_btnSend.weightx = 0;
gbc_btnSend.weighty = 0;
contentPane.add(btnSend, gbc_btnSend);
list = new JList();
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.insets = new Insets(0, 600, 330, -330);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 0;
gbc_list.gridy = 0;
gbc_list.gridwidth = 2;
gbc_list.gridheight = 2;
JScrollPane p = new JScrollPane();
p.setViewportView(list);
contentPane.add(p, gbc_list);
list.setFont(new Font("Verdana", 0, 24));
System.out.println("HEY");
setVisible(true);
new SwingWorker<Void, String>() {
protected Void doInBackground() throws Exception {
Scanner s = new Scanner(outPipe);
while (s.hasNextLine()) {
String line = s.nextLine();
publish(line);
}
return null;
}
#Override protected void process(java.util.List<String> chunks) {
for (String line : chunks) {
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), line + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
}
}.execute();
Singleplayer spp = new Singleplayer();
Singleplayer.startOfGame();
setVisible(true);
}
public static void console(String message, Color color) {
txtMessage.setText("");
try {
StyledDocument doc = history.getStyledDocument();
Style style = history.addStyle("", null);
StyleConstants.setForeground(style, color);
doc.insertString(doc.getLength(), message + "\r\n", style);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void console(String message) {
txtMessage.setText("");
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public void chatconsole(String message) {
chatMessage.setText("");
try {
Document doc = chat.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void single() {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
public static void main(String[] args) {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
And the singleplayer class:
public static void startOfGame(){
System.out.println("HEY");
SingleplayerGUI.console("Welcome to Console Clash Pre Alpha Version 1!");
SingleplayerGUI.console("Created by Drift");
SingleplayerGUI.console("Published by Boring Games");
SingleplayerGUI.console("");
SingleplayerGUI.console("");
menuScreen();
}
static void menuScreen() {
Scanner scan = new Scanner(System.in);
System.out.println("To play the game, type 'start'. To quit, type 'quit'.");
String menu = scan.nextLine();
if (menu.equals("start")) {
start();
} else if (menu.equals("quit")) {
quit();
} else {
menuScreen();
}
}
private static void quit() {
SingleplayerGUI.console("You quit the game.");
}
private static void start() {
SingleplayerGUI.console("You started the game.");
}
So far I've figured out that the problem most likey occurs when adding the outPipe to the console. Would I be able to fix this or am I just not able to use outPipes with this application?
Thanks in advance for your help.
The setVisible() method is invoked twice.. Remove the second setVisible() call after the Singleplayer.startOfGame(); line in SingleplayerGUI constructor.
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);
}
}