Cannot send (Service) object from RMI server to Client - java

I have been killing my brain trying to figure out the problem, i am pretty sure the server connection is established neatly. i have even put some system prints to make sure the object is sent and received. let me post my code first.
RemoteService.java (interface):
package testrmi;
import java.rmi.*;
import javax.swing.JPanel;
public interface RemoteService extends Remote {
public Object[] getServiceList() throws RemoteException;
public Service getService(Object SvcKey) throws RemoteException;
}
Service.java (interface) used by Services offered by server:
package testrmi;
import javax.swing.*;
import java.io.*;
import java.rmi.Remote;
public interface Service extends Serializable {
public JPanel getGuiPanel();
}
RSimpl.java (RemoteService interface implementer)
package testrmi;
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
public class RSimpl implements RemoteService {
HashMap<String, Service> map;
public RSimpl() throws RemoteException
{
//super();
setUpServices();
}
public void setUpServices()
{
map = new HashMap<String, Service>();
map.put("Dice Roll Service", new DiceRoll());
map.put("Calculator Service", new Calculator());
map.put("Clock Service", new DigitalClock1());
// Keep Adding Services On The Go!
}
public Object[] getServiceList()
{
return map.keySet().toArray();
}
public Service getService(Object SvcKey)
{
System.out.println(SvcKey + " request has been recieved");
Service theService = map.get(SvcKey);
return theService;
}
}
Client.java (The client, this looks dirty :p )
package testrmi;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
JFrame frame;
JPanel mainPanel;
JComboBox<Object> comboBox;
RemoteService server;
int i = 0;
Object[] error = {"Cannot Load Services"};
public void buildGUI()
{
frame = new JFrame("Service Browser");
mainPanel = new JPanel();
attemptConnect();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.getContentPane().add(BorderLayout.NORTH, comboBox);
frame.setVisible(true);
frame.setSize(300, 150);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//centerFrame();
}
public void attemptConnect()
{
if(i==0)
{
i++;
Object[] services = getServiceList();
try {
comboBox = new JComboBox<Object>(services);
if (!services.toString().equalsIgnoreCase("Cannot Load Services"))
comboBox.addActionListener(new MyListListener());
}
catch(Exception ex) {
System.out.println("Cannot Establish Connection");
}
}
}
public void centerFrame()
{
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) (d.getWidth()-frame.getWidth() / 2);
int y = (int) (d.getHeight()-frame.getHeight() / 2);
frame.setLocation(x, y);
}
public Object[] getServiceList()
{
boolean connectionsuccess = false;
Object[] objList = null;
try {
Registry rs = LocateRegistry.getRegistry("127.0.0.1", 9797); //CHANGE TO 192.168.1.97
server = (RemoteService) rs.lookup("RService");
connectionsuccess = true;
}
catch(Exception ex) {
Object[] options = {"Retry","Cancel"};
int o = JOptionPane.showOptionDialog(frame, "Cannot Establish Connection To The Server. \n Do You Want To Retry?", "Connection Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
if(o==0)
{
i=0;
attemptConnect();
}
else
{
i=1;
return error;
}
}
if(connectionsuccess) {
try {
objList = server.getServiceList();
}
catch(Exception ex) {
Object[] options = {"Retry","Cancel"};
int o = JOptionPane.showOptionDialog(frame, "Cannot Fetch Services List From The Server. \n Do You Want To Retry?", "Fetch Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
if(o==0)
{
i=0;
attemptConnect();
}
else
{
i=1;
return error;
}
}
}
return objList;
}
public void loadService(Object SvcKey)
{
try {
System.out.println(" I am going to send key: " + SvcKey);
Service svc = (Service) server.getService(SvcKey); //THIS IS CAUSING THE ERROR!
System.out.println("i am yet working"); //THIS LINE IS NOT WORKING
mainPanel.removeAll();
//frame.setContentPane(svc.getGuiPanel());
mainPanel.add(svc.getGuiPanel());
mainPanel.validate();
mainPanel.repaint();
frame.pack();
frame.setMinimumSize(new Dimension(300,150));
}
catch(Exception ex) {
Object[] options = {"Retry","Cancel"};
int o = JOptionPane.showOptionDialog(frame, "Cannot Load The Service From The Server. \n Do You Want To Retry?", "Connection Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
if(o==0)
{
new MyListListener();
}
else
{
i=1;
frame.repaint();
}
}
}
public class MyListListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
Object selection = comboBox.getSelectedItem();
System.out.println(comboBox.getSelectedItem()); //DO NOT FORGET TO TEST THIS!
loadService(selection);
}
}
public static void main(String[] args)
{
Client cl = new Client();
cl.buildGUI();
}
}
StartServer.java (instantiates RSimpl object and starts server)
package testrmi;
import java.net.InetAddress;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class StartServer {
public static void main(String[] args)
{
try {
RSimpl obj = new RSimpl();
RemoteService stub = (RemoteService) UnicastRemoteObject.exportObject(obj, 0);
System.setProperty("java.rmi.server.hostname","192.168.1.97");
//RemoteService rs = new RSimpl();
Registry r = LocateRegistry.getRegistry(9797);
r.rebind("RService", stub);
System.out.println("Remote Service Is Running");
System.out.println(""+ InetAddress.getLocalHost().getHostAddress());
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("Sorry, Cannot Start Remote Service");
}
}
}
Calculator.java (Calculator Service, no need to check this)
package testrmi;
import javax.script.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
public class Calculator implements Service, Serializable {
JPanel mainPanel;
public JPanel getGuiPanel()
{
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
//JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,4));
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
final JTextField t = new JTextField(10);
t.setEditable(false);
t.setBackground(Color.green);
t.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
Font myFont = new Font("MS Sans Serif", Font.BOLD, 24);
t.setFont(myFont);
mainPanel.add(t,BorderLayout.NORTH);
final JButton n1 = new JButton("1");
n1.setFocusable(false);
n1.setFont(myFont);
n1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n1.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n2 = new JButton("2");
n2.setFocusable(false);
n2.setFont(myFont);
n2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n2.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n3 = new JButton("3");
n3.setFocusable(false);
n3.setFont(myFont);
n3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n3.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n4 = new JButton("4");
n4.setFocusable(false);
n4.setFont(myFont);
n4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n4.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n5 = new JButton("5");
n5.setFocusable(false);
n5.setFont(myFont);
n5.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n5.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n6 = new JButton("6");
n6.setFocusable(false);
n6.setFont(myFont);
n6.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n6.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n7 = new JButton("7");
n7.setFocusable(false);
n7.setFont(myFont);
n7.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n7.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n8 = new JButton("8");
n8.setFocusable(false);
n8.setFont(myFont);
n8.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n8.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n9 = new JButton("9");
n9.setFocusable(false);
n9.setFont(myFont);
n9.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n9.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n10 = new JButton("0");
n10.setFocusable(false);
n10.setFont(myFont);
n10.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n10.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n11 = new JButton("+");
n11.setFocusable(false);
n11.setFont(myFont);
n11.setForeground(Color.MAGENTA);
n11.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n11.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n12 = new JButton("-");
n12.setFocusable(false);
n12.setFont(myFont);
n12.setForeground(Color.MAGENTA);
n12.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n12.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n13 = new JButton("*");
n13.setFocusable(false);
n13.setFont(myFont);
n13.setForeground(Color.MAGENTA);
n13.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n13.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n14 = new JButton("/");
n14.setFocusable(false);
n14.setFont(myFont);
n14.setForeground(Color.MAGENTA);
n14.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n14.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n15 = new JButton("=");
n15.setFocusable(false);
n15.setFont(myFont);
n15.setForeground(Color.BLUE);
n15.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//String num1 = n15.getText();
String global = t.getText();
//global = global.concat(num1);
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
String s = engine.eval(global).toString();
t.setText(s);
}
catch (ScriptException e1) {
e1.printStackTrace();
}
}
});
final JButton n16 = new JButton("C");
n16.setFocusable(false);
n16.setFont(myFont);
n16.setForeground(Color.RED);
n16.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//String num1 = n16.getText();
String global = t.getText();
global = null;
t.setText(global);
}
});
p1.add(n1);
p1.add(n2);
p1.add(n3);
p1.add(n4);
p2.add(n5);
p2.add(n6);
p2.add(n7);
p2.add(n8);
p3.add(n9);
p3.add(n10);
p3.add(n11);
p3.add(n12);
p4.add(n13);
p4.add(n14);
p4.add(n15);
p4.add(n16);
JPanel pPanel = new JPanel();
pPanel.setLayout(new BoxLayout(pPanel, BoxLayout.Y_AXIS));
pPanel.add(p1);
pPanel.add(p2);
pPanel.add(p3);
pPanel.add(p4);
mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
mainPanel.add(pPanel);
return mainPanel;
}
}
DiceRoll.java (DiceRoll Service, no need to check this)
package testrmi;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DiceRoll implements Service {
int i = 0;
int h = 0;
JPanel mainPanel;
JButton roll;
MyDrawPanel drawPanel;
public JPanel getGuiPanel()
{
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
roll = new JButton("Roll The Dice!");
roll.setFont(new Font("Comic Sans Ms", Font.BOLD, 16));
roll.setFocusable(false);
roll.setAlignmentX(Component.CENTER_ALIGNMENT);
roll.addActionListener(new rollListener());
drawPanel = new MyDrawPanel();
drawPanel.setPreferredSize(new Dimension(150,150));
mainPanel.add(roll);
mainPanel.add(Box.createRigidArea(new Dimension(0,10)));
mainPanel.add(drawPanel);
mainPanel.setBorder(BorderFactory.createEmptyBorder(5,0,5,0));
return mainPanel;
}
public int roll()
{
while (i==0 || i==h)
{
i = (int) (Math.random()*7);
}
h = i;
return i;
}
public class rollListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
int x = roll();
drawPanel.sendNum(x);
drawPanel.repaint();
}
}
public class MyDrawPanel extends JPanel
{
Graphics g;
int least = 0, x;
int fx=0, fy=0, fw=150, fh=150;
int dw=100, dh=100;
int dx=((fw-dw)/2), dy=((fh-dh)/2);
int dxc,dyc,dx1,dy1,dx2,dy2,dx3,dy3,dx4,dy4,dx5,dy5,dx6,dy6;
public void paintComponent(Graphics gn)
{
g = gn;
super.paintComponent(g);
g.setColor(Color.LIGHT_GRAY);
g.fillRect(fx, fy, fw, fh);
g.setColor(Color.WHITE);
g.fillRoundRect(dx, dy, dw, dh, 30, 30);
g.setColor(Color.BLACK); // set black for dots and border
g.drawRoundRect(dx, dy, dw, dh, 30, 30);
if(least>=1)
{
if(x==1)
{
g.fillOval(dxc, dyc, 20, 20);
}
else if(x==2)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
else if(x==3)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dxc, dyc, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
else if(x==4)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dx2, dy2, 20, 20);
g.fillOval(dx5, dy5, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
else if(x==5)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dx2, dy2, 20, 20);
g.fillOval(dxc, dyc, 20, 20);
g.fillOval(dx5, dy5, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
else if(x==6)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dx2, dy2, 20, 20);
g.fillOval(dx3, dy3, 20, 20);
g.fillOval(dx4, dy4, 20, 20);
g.fillOval(dx5, dy5, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
}
}
public void sendNum(int xx)
{
least = 1;
x = xx;
// REMEMBER: dx+40=CENTER_X and dy+40=CENTER_Y because dice size 100, dot size 20
dxc=dx+40;
dyc=dy+40;
dx1=dx+10;
dy1=dy+10;
dx2=dx+70;
dy2=dy+10;
dx3=dx+10;
dy3=dy+40;
dx4=dx+70;
dy4=dy+40;
dx5=dx+10;
dy5=dy+70;
dx6=dx+70;
dy6=dy+70;
}
} // close class MyDrawPanel
}
DigitalClock1.java (no need to check -- these are only for compilation purposes)
package testrmi;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
public class DigitalClock1 implements Service
{
public JPanel getGuiPanel()
{
SimpleDigitalClock clock1 = new SimpleDigitalClock();
return clock1;
}
static class SimpleDigitalClock extends JPanel
{
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc)
{
this.stringTime = abc;
}
public int Number(int a, int b)
{
return (a <= b) ? a : b;
}
SimpleDigitalClock()
{
Timer t = new Timer(1000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v)
{
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10)
{
this.aHour = "0";
}
if (hour >= 10)
{
this.aHour = "";
}
if (minute < 10)
{
this.bMinute = "0";
}
if (minute >= 10)
{
this.bMinute = "";
}
if (second < 10)
{
this.cSecond = "0";
}
if (second >= 10)
{
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute+ minute + ":" + cSecond + second);
v.setColor(Color.BLACK);
int length = Number(this.getWidth(),this.getHeight());
Font Font1 = new Font("Comic Sans MS", Font.PLAIN, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length/6, length/2);
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(200, 200);
}
}
}
I am running start rmiregistry 9797 from the directory in which the testrmi directory(package) is also placed. Then I run java testrmi.StartServer from the same directory. I get the server is running message, then I run the client from another directory but with same package name, which only contains Client.class, RemoteService.class and Service.class; the client starts fine, displays all three services, but when I select from the list, I get the exception error 'Cannot load service, retry?'.
NOTE: The client loads the services properly if I copy the services (calculator.class, diceroll.class and digitalclock1.class) in the client package directory. I don't want the services to be accessible to the clients directly without connecting to server.

If you want to be able to return serializable objects to the client that aren't in the client's classpath, you need to use the RMI codebase feature, which among other things requires you to deploy a codebase server, and use a SecurityManager at the client.

Related

Swing Components invisible

When I run my code there is only the empty frame. To see the JButton and the JTextFields I have to search and click on them before they are visible. I searched everywhere on the Internet but I found nothing. I also set the visibility to true and added the JComponents. Here is my Code:
Frame Fenster = new Frame();
And this...
package me.JavaProgramm;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Frame extends JFrame {
private JButton bChange;
private JTextField tvonEur;
private JTextField tzuOCur; //andere Währung (other Currency)
private JTextField tzuEur;
private JTextField tvonOCur;
private JComboBox cbCur; //Wärhung wählen
private String curName;
private double faktorUSD;
private double faktorGBP;
private static String[] comboCur = {"USD", "GBP"};
public Frame() {
setLayout(null);
setVisible(true);
setSize(400, 400);
setTitle("Währungsrechner");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setResizable(false);
Font schrift = new Font("Serif", Font.PLAIN + Font.ITALIC, 30);
tvonEur = new JTextField("Euro");
tvonEur.setSize(80, 25);
tvonEur.setLocation(20, 50);
tvonEur.requestFocusInWindow();
tvonEur.selectAll();
tzuEur = new JTextField("Euro");
tzuEur.setSize(80, 25);
tzuEur.setLocation(20, 150);
tzuEur.requestFocusInWindow();
tzuEur.selectAll();
bChange = new JButton("Euro zu US-Dollar");
bChange.setSize(120, 25);
bChange.setLocation(110, 50);
tzuOCur = new JTextField("US-Dollar");
tzuOCur.setSize(80, 25);
tzuOCur.setLocation(240, 50);
tzuOCur.requestFocusInWindow();
tzuOCur.selectAll();
tvonOCur = new JTextField("US-Dollar");
tvonOCur.setSize(80, 25);
tvonOCur.setLocation(240, 50);
tvonOCur.requestFocusInWindow();
tvonOCur.selectAll();
cbCur = new JComboBox(comboCur);
cbCur.setSize(100, 20);
cbCur.setLocation(100, 100);
tvonEur.setVisible(true);
tzuEur.setVisible(true);
tzuOCur.setVisible(true);
tvonOCur.setVisible(true);
bChange.setVisible(true);
cbCur.setVisible(true);
add(tvonEur);
add(bChange);
add(tzuOCur);
add(cbCur);
Currency currency = new Currency();
String strUSD = currency.convertUSD();
try {
NumberFormat formatUSD = NumberFormat.getInstance(Locale.GERMANY);
Number numberUSD = formatUSD.parse(strUSD);
faktorUSD = numberUSD.doubleValue();
System.out.println(faktorUSD);
} catch (ParseException e) {
System.out.println(e);
}
String strGBP = currency.convertGBP();
try {
NumberFormat formatGBP = NumberFormat.getInstance(Locale.GERMANY);
Number numberGBP = formatGBP.parse(strGBP);
faktorGBP = numberGBP.doubleValue();
System.out.println(faktorGBP);
} catch (ParseException e) {
System.out.println(e);
}
cbCur.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cbCur = (JComboBox) e.getSource();
curName = (String) cbCur.getSelectedItem();
if (curName == "USD") {
tzuOCur.setText("US-Dollar");
} else if (curName == "GBP") {
tzuOCur.setText("British-Pound");
}
}
});
bChange.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (curName == "USD") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleUSD = doubleEUR * faktorUSD;
tzuOCur.setText(Double.toString(roundScale3(doubleUSD)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
} else if (curName == "GBP") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleGBP = doubleEUR * faktorGBP;
tzuOCur.setText(Double.toString(roundScale3(doubleGBP)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
}
}
});
}
public static double roundScale3(double d) {
return Math.rint(d * 1000) / 1000.;
}
}
Try moving setVisible(true) after you add the children to the parent container.
Generally with Swing it's considered good practice to put code that updates visible components in the event dispatching thread, like this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame.this.setVisible(true);
}
});

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

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

Why wont my simon game work and what do i need to do so it works

Im making a simon game and i have no idea what to do. I got sound and all that good stuff working but as for everything else I have no idea what im doing. I need some help making the buttons work and flash in the right order. (comments are failed attempts) Any help is very much appreciated.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.ArrayList;
public class Game extends JFrame
{
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int sequence1;
int[] anArray;
public Game()
{
anArray = new int[1000];
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score");
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try{sound1 = Applet.newAudioClip(wavFile1.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound2 = Applet.newAudioClip(wavFile2.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound3 = Applet.newAudioClip(wavFile3.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound4 = Applet.newAudioClip(wavFile4.toURL());}
catch(Exception e){e.printStackTrace();}
setVisible(true);
}
public class Button1Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound1.play();
}
}
public class Button2Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound2.play();
}
}
public class Button3Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound3.play();
}
}
public class Button4Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound4.play();
}
}
/*
public static int[] buttonClicks(int[] anArray)
{
return anArray;
}
*/
public class Button5Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
for (int i = 1; i <= 159; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
anArray[i] = randomNum;
System.out.println("Element at index: "+ i + " Is: " + anArray[i]);
}
buttonClicks(anArra[3]);
/*
for (int i = 1; i <= 100; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if(randomNum == 1)
{
button1.doClick();
sequence1 = 1;
System.out.println(sequence1);
}
else if(randomNum == 2)
{
button2.doClick();
sequence1 = 2;
System.out.println(sequence1);
}
else if(randomNum == 3)
{
button3.doClick();
sequence1 = 3;
System.out.println(sequence1);
}
else
{
button4.doClick();
sequence1 = 4;
System.out.println(sequence1);
}
}
*/
}
}
}
Below is some code to get you started. The playback of the sequences is executed in a separate thread, as you need to use delays in between. This code is by no means ideal. You should use better names for the variables and refactor to try to create a better and more encapsulated game model. Maybe you could use this opportunity to learn about the MVC design pattern?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends JFrame {
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int level;
int score;
int[] anArray;
int currentArrayPosition;
public Game() {
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
level = 0;
score = 0;
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score: " + String.valueOf(score));
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try {
sound1 = Applet.newAudioClip(wavFile1.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound2 = Applet.newAudioClip(wavFile2.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound3 = Applet.newAudioClip(wavFile3.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound4 = Applet.newAudioClip(wavFile4.toURL());
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
public class Button1Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound1.play();
buttonClicked(button1);
}
}
public class Button2Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound2.play();
buttonClicked(button2);
}
}
public class Button3Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound3.play();
buttonClicked(button3);
}
}
public class Button4Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound4.play();
buttonClicked(button4);
}
}
private void buttonClicked(JButton clickedButton) {
if (isCorrectButtonClicked(clickedButton)) {
currentArrayPosition++;
addToScore(1);
if (currentArrayPosition == anArray.length) {
playNextSequence();
} else {
}
} else {
JOptionPane.showMessageDialog(this, String.format("Your scored %s points", score));
score = 0;
level = 0;
label1.setText("Score: " + String.valueOf(score));
}
}
private boolean isCorrectButtonClicked(JButton clickedButton) {
int correctValue = anArray[currentArrayPosition];
if (clickedButton.equals(button1)) {
return correctValue == 1;
} else if (clickedButton.equals(button2)) {
return correctValue == 2;
} else if (clickedButton.equals(button3)) {
return correctValue == 3;
} else if (clickedButton.equals(button4)) {
return correctValue == 4;
} else {
return false;
}
}
public class Button5Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
playNextSequence();
}
}
private void playNextSequence() {
level++;
currentArrayPosition = 0;
anArray = createSequence(level);
(new Thread(new SequenceButtonClicker())).start();
}
private int[] createSequence(int sequenceLength) {
int[] sequence = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
sequence[i] = randomNum;
}
return sequence;
}
private JButton getButtonFromInt(int sequenceNumber) {
switch (sequenceNumber) {
case 1:
return button1;
case 2:
return button2;
case 3:
return button3;
case 4:
return button4;
default:
return button1;
}
}
private void flashButton(JButton button) throws InterruptedException {
Color originalColor = button.getBackground();
button.setBackground(new Color(255, 255, 255, 200));
Thread.sleep(250);
button.setBackground(originalColor);
}
private void soundButton(JButton button) {
if (button.equals(button1)) {
sound1.play();
} else if (button.equals(button2)) {
sound2.play();
} else if (button.equals(button3)) {
sound3.play();
} else if (button.equals(button4)) {
sound4.play();
}
}
private void addToScore(int newPoints) {
score += newPoints;
label1.setText("Score: " + String.valueOf(score));
}
private class SequenceButtonClicker implements Runnable {
public void run() {
for (int i = 0; i < anArray.length; i++) {
try {
JButton nextButton = getButtonFromInt(anArray[i]);
soundButton(nextButton);
flashButton(nextButton);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, "Interrupted", ex);
}
}
}
}
}

Swing delay between calls

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

How to add JPanel in a JFrame that is a BufferedImage()

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

Categories