below my code i code wright for gps is give me coninue data on 4800 baud rate this data display continue by "System.out.println(st)" but same data not dispaly in a.setText(st) where a is Textbox variable. some know how to my textbox update like System.out.println line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.UnsupportedCommOperationException;
import javax.comm.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* test.java
*
* Created on Mar 11, 2013, 9:08:52 AM
*/
/**
*
* #author DJ ROCKS
*/
public class test extends javax.swing.JFrame {
public boolean bp=true;
/** Creates new form test */
public test() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
ok = new javax.swing.JButton();
a = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
ok.setText("ok");
ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okActionPerformed(evt);
}
});
a.setText(" ");
a.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(238, 238, 238)
.addComponent(ok)))
.addContainerGap(124, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)
.addComponent(ok)
.addContainerGap(160, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void okActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==ok)
{
CommPortIdentifier portId = null;
String wantedPortName="COM16";
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
while(portIdentifiers.hasMoreElements())
{
CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL &&
pid.getName().equals(wantedPortName))
{
portId = pid;
break;
}
}
if(portId == null)
{
System.err.println("Could not find serial port " + wantedPortName);
System.exit(1);
}
else
{
System.out.println("system find gps reciever");
}
SerialPort port = null;
try {
port = (SerialPort) portId.open(
"RMC",
1);
System.out.println("all are ok");
} catch(PortInUseException e) {
System.err.println("Port already in use: " + e);
System.exit(1);
}
try {
//int i=Integer.parseInt(new vps().baud_rate.getItemAt(new vps().baud_rate.getItemCount()));
port.setSerialPortParams(
4800,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader is = null;
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
System.out.println("data is ok");
} catch (IOException e) {
System.err.println("Can't open input stream: write-only");
is = null;
}
//this is variable is ouside of class and define by public it work
while(true)
{
String st = null;
try {
st = is.readLine();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(st);
//st = st.replace(st, "");
a.setText(st);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
System.out.printf(ie.getMessage());
}
}
/*if (is != null) try {
is.close();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
if (port != null) port.close();
*/
}
}
private void aActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField a;
private javax.swing.JButton ok;
// End of variables declaration
}
It seems as though you may be trying to rewrite the same String. I would try to call a "get" method that returns a String instead of referring to the variable "st". I do this to avoid a situations in which the program will try to rewrite the String since Strings are immutable.
I would try something like this:
private String getString()
{
try {
String st = new String(""+is.ReadLine());
return st;
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
Use this to refer to the new String from BufferedReader "is":
a.setText(getString());
Also, it looks as if you have a code block within comment lines here:
/*if (is != null) try {
is.close();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
if (port != null) port.close();
}*/
Please correct me if I'm wrong here.
Related
I am trying to update a JTextBox with data from a serial port in java swing. The problem I am facing is that the JTextBox is not getting updated.
I tried repaint() and revalidate functions also but not use. I also tried putting the setText() inside a runnable. Nothing works. Please guide me in this.
public class PrinterUI extends javax.swing.JFrame{
/**
* Creates new form PrinterUI
*/
public PrinterUI() {
initComponents();
initOtherUI();
}
public void initOtherUI(){
menu = new ArrayList<javax.swing.JMenuItem>();
}
public void showSensorValueOnScreen(long id, int pres, int temp){
System.out.println(Long.toHexString(id));
sensorID = id;
System.out.println(Long.toHexString(sensorID));
opText.setText(Long.toHexString(sensorID));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMenu3 = new javax.swing.JMenu();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
opText = new javax.swing.JTextField();
jMenuBar1 = new javax.swing.JMenuBar();
printerMenuBar = new javax.swing.JMenu();
mobileMenuBar = new javax.swing.JMenu();
jMenu3.setText("jMenu3");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Print");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jLabel1.setText("Sensor Output");
opText.setText("jTextField1");
opText.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
opTextPropertyChange(evt);
}
});
printerMenuBar.setText("Printer");
printerMenuBar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
printerMenuBarMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
printerMenuBarMouseEntered(evt);
}
});
jMenuBar1.add(printerMenuBar);
mobileMenuBar.setText("Mobile");
jMenuBar1.add(mobileMenuBar);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(203, 203, 203)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(opText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jButton1))
.addContainerGap(236, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(108, Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(opText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(52, 52, 52)
.addComponent(jButton1)
.addGap(105, 105, 105))
);
getAccessibleContext().setAccessibleName("jLabel1");
pack();
}// </editor-fold>
private void printerMenuBarMouseClicked(java.awt.event.MouseEvent evt) {
System.out.println("clicked");
}
private void printerMenuBarMouseEntered(java.awt.event.MouseEvent evt) {
String[] portNames = null;
portNames = SerialPortList.getPortNames();
for (String string : portNames) {
System.out.println(string);
}
if (portNames.length == 0) {
System.out.println("There are no serial-ports");
} else {
SerialPort serialPort = new SerialPort("COM25");
try {
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
PortReader portReader = new PortReader(serialPort);
serialPort.addEventListener(portReader, SerialPort.MASK_RXCHAR);
} catch (Exception e) {
System.out.println("There are an error on writing string to port т: " + e);
}
}
}
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
System.out.println("Print Click");
opText.setText(Long.toString(sensorID));
System.out.println(Long.toHexString(sensorID));
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PrinterUI().setVisible(true);
}
});
}
private List<javax.swing.JMenuItem> menu;
PrintService pservice = null;
public static long sensorID;
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenu mobileMenuBar;
private javax.swing.JTextField opText;
private javax.swing.JMenu printerMenuBar;
// End of variables declaration
}
class PortReader implements SerialPortEventListener{
SerialPort serialPort;
public int[] incomingData = new int[20];
public int dataIndex=0;
public long sensorID=0;
public int pressure;
public int temperature;
public PortReader(SerialPort serialPort) {
this.serialPort = serialPort;
}
#Override
public void serialEvent(SerialPortEvent event) {
if (event.isRXCHAR() && event.getEventValue() > 0) {
try {
String receivedData = serialPort.readHexString();
for(int x=0;x<receivedData.length();x=x+2){
int data = Integer.parseInt(receivedData.substring(x, x+2),16);
//System.out.println(data);
if((dataIndex==0)&&(data==170)){
incomingData[dataIndex++]=data;
}else if(dataIndex>0){
incomingData[dataIndex++]=data;
if(dataIndex>=14){
dataIndex=0;
long tyreId =(long)(((int)incomingData[6])*16777216 + ((int)incomingData[7])*65536 + ((int)incomingData[8])*256 + ((int)incomingData[9]));
tyreId = tyreId & 0x00000000FFFFFFFFL;
int press = incomingData[10];
int temp = incomingData[11];
sensorID = tyreId;
pressure = press;
temperature = temp;
PrinterUI obj = new PrinterUI();
obj.showSensorValueOnScreen(sensorID, pressure, temperature);
System.out.println("ID: " + Long.toHexString(tyreId) + ", Pressure: " + pressure + ", Temperature: " + temperature);
}
}else{
dataIndex=0;
}
}
} catch (SerialPortException ex) {
System.out.println("Error in receiving string from COM-port: " + ex);
}
}
}
}
When a serial data is received, serialEvent is called in PortReader class which in turn calls the showSensorValueOnScreen() method in the PrinterUI class. The JTextBox widget doesnt gets updated.
But when a button on the UI is pressed, the JTextBox gets updated.
Why doesnt it get updated when I call it from outside the class?. Please help me out here.
I found out the issue. I am trying to update the UI from another class by creating a new object for the UI. The actual UI was created from void main using a different object.
I resolved it by passing the existing object to the class that was calling the UI update function.
Thank you for your help people.
I make a menu like simple socket program. But after I successfully send and print one menu, the console print "null" and, I can't send or print any menu anymore and console print "Connection refused: connect"
Like this
4 input, one success print and a null, another 3 looks like below.
null
Connection refused: connect
Connection refused: connect
Connection refused: connect
I'm still a newbie indeed, and I use jframe which is I rarely see in Stack Overflow.
Server.java
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Delayed;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Dicko
*/
public class Server extends javax.swing.JFrame {
public static int PORT = 1111;
public static int PORT2 = 1996;
public static DataInputStream DIS;
static String bon = "";
static String harga = "";
/**
* Creates new form Server
*/
public Server() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
btn_ok = new javax.swing.JButton();
lbl_total = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
txa_bon = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Server");
btn_ok.setText("OK");
btn_ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_okActionPerformed(evt);
}
});
lbl_total.setText("0");
jLabel2.setText("Rp");
txa_bon.setColumns(20);
txa_bon.setRows(5);
txa_bon.setEditable(false);
jScrollPane1.setViewportView(txa_bon);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 182, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_total, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_ok))
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_ok)
.addComponent(lbl_total)
.addComponent(jLabel2))
.addContainerGap())
);
setBounds(500, 150, 377, 345);
}// </editor-fold>
private void btn_okActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server().setVisible(true);
Client cl = new Client();
cl.setVisible(true);
}
});
try {
ServerSocket SS = new ServerSocket(PORT);
JOptionPane.showMessageDialog(null, "Koneksi Terhubung", "Server Info", INFORMATION_MESSAGE);
Socket clientSocket = SS.accept();
DIS = new DataInputStream(clientSocket.getInputStream());
String tmp = "";
while (!tmp.equals("stop")) {
tmp = DIS.readUTF();
bon = tmp;
txa_bon.append(bon);
}
DIS.close();
SS.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
// Variables declaration - do not modify
private javax.swing.JButton btn_ok;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lbl_total;
private static javax.swing.JTextArea txa_bon;
// End of variables declaration
}
Client.java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
/**
*
* #author Dicko
*/
public class Client extends javax.swing.JFrame {
public static int Port = 1111;
public static int Port2 = 1996;
public static String IP = "localhost";
public static PrintStream cetak;
/**
* Creates new form Client
*/
public Client() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
btn_nasi = new javax.swing.JButton();
btn_bakso = new javax.swing.JButton();
btn_mie = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Client");
setResizable(false);
btn_nasi.setText("Nasi");
btn_nasi.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_nasiActionPerformed(evt);
}
});
btn_bakso.setText("Bakso");
btn_bakso.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_baksoActionPerformed(evt);
}
});
btn_mie.setText("Mie Ayam");
btn_mie.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_mieActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btn_nasi)
.addGap(18, 18, 18)
.addComponent(btn_mie)
.addGap(18, 18, 18)
.addComponent(btn_bakso)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_nasi)
.addComponent(btn_bakso)
.addComponent(btn_mie))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
setBounds(150, 150, 265, 84);
}// </editor-fold>
private void btn_nasiActionPerformed(java.awt.event.ActionEvent evt) {
String str = "Nasi Rp 2.000 ,-";
try {
Socket cs = new Socket(IP, Port);
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
dout.writeUTF(str);
dout.flush();
dout.close();
cs.close();
} catch (IOException e) {
System.out.println(e);
}
}
private void btn_mieActionPerformed(java.awt.event.ActionEvent evt) {
String str = "Mie Ayam Rp 4.000 ,-";
try {
Socket cs = new Socket(IP, Port);
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
dout.writeUTF(str);
dout.flush();
dout.close();
cs.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void btn_baksoActionPerformed(java.awt.event.ActionEvent evt) {
String str = "Bakso Rp 5.000 ,-";
try {
Socket cs = new Socket(IP, Port);
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
dout.writeUTF(str);
dout.flush();
dout.close();
cs.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Client().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btn_bakso;
private javax.swing.JButton btn_mie;
private javax.swing.JButton btn_nasi;
// End of variables declaration
}
Close up Server.java
try {
ServerSocket SS = new ServerSocket(PORT);
JOptionPane.showMessageDialog(null, "Koneksi Terhubung", "Server Info", INFORMATION_MESSAGE);
Socket clientSocket = SS.accept();
DIS = new DataInputStream(clientSocket.getInputStream());
String tmp = "";
while (!tmp.equals("stop")) {
tmp = DIS.readUTF();
bon = tmp;
txa_bon.append(bon);
}
DIS.close();
SS.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
Close up Client.java
String str = "Nasi Rp 2.000 ,-";
try {
Socket cs = new Socket(IP, Port);
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
dout.writeUTF(str);
dout.flush();
dout.close();
cs.close();
} catch (IOException e) {
System.out.println(e);
}
I have a problem. My splash program isn't running. please excuse me as I am new and cant put the code properly.i Think my Timer code is wrong. Any help will be appreciated. My connection to the database is working perfectly fine.
My splash code
package Splash_package;
import DataConnection.connection;
import Mainframe.main_frame;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.Timer;
/**
*
* #author Aaqib Jan
*/
public class Splash extends javax.swing.JFrame {
/**
* Creates new form splash
*/
public Splash() {
initComponents();
}
connection cn=new connection();
Timer tm = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
count+=5;
if(count==10)
{
jLabel2.setText("Initializing");
jProgressBar1.setStringPainted(true);
jProgressBar1.setValue(10);
}
if (count == 20) {
try {
Class.forName(cn.classname);
jLabel2.setText("Loading ...");
jProgressBar1.setValue(20);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 30) {
try {
cn.con = DriverManager.getConnection(cn.url);
jLabel2.setText("Checking database ...");
jProgressBar1.setValue(30);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 40) {
try {
cn.st = cn.con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
jLabel2.setText("Finding resources ...");
jProgressBar1.setValue(40);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 50) {
try {
cn.rs = cn.st.executeQuery("select * from usertable");
jLabel2.setText("Checking Errors ...");
jProgressBar1.setValue(50);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 60) {
try {
cn.rs = cn.st.executeQuery("select * from labourinfo");
jLabel2.setText("No Error Getting ...");
jProgressBar1.setValue(60);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 70) {
try {
cn.rs = cn.st.executeQuery("select * from salarygrade");
jLabel2.setText("Checking Modules ...");
jProgressBar1.setValue(70);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 80) {
try {
cn.rs = cn.st.executeQuery("select * from labourattendence");
jLabel2.setText("Almost Finish ...");
jProgressBar1.setValue(80);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 90) {
try {
cn.rs = cn.st.executeQuery("select * from labourattendence");
jLabel2.setText("Starting ...");
jProgressBar1.setValue(90);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
}
}
if(count==95){
jProgressBar1.setValue(100);
}
if (count == 100) {
main_frame main = new main_frame();
main.show();
dispose();
}
}
});
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jProgressBar1 = new javax.swing.JProgressBar();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
jLabel2.setText("jLabel2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(207, 207, 207)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(jLabel1)))
.addContainerGap(307, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(217, 217, 217))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(jLabel2)
.addGap(37, 37, 37)
.addComponent(jLabel1)
.addGap(59, 59, 59)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(230, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void formWindowOpened(java.awt.event.WindowEvent evt) {
this.setLocationRelativeTo(null);
this.setBackground(new Color(0, 255, 0, 0));
tm.start();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Splash().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JProgressBar jProgressBar1;
// End of variables declaration
int count=0;
}
My Main class
import Splash_package.Splash;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
public class Main_Class {
public static void main(String[] args) {
new Splash().setVisible(true);
}
}
The following method is never called and this causes the timer to never start:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
this.setLocationRelativeTo(null);
this.setBackground(new Color(0, 255, 0, 0));
tm.start();
}
Move tm.start() as follow:
public Splash() {
initComponents();
tm.start();
}
I've recently learned how to use the NetBeans GUI editor and I'm really liking it, but I've run across a problem. I'm making a program for personal use that requires a login. The password for the login is retrieved from a file and can be changed. So far, making the text file, putting contents and changing contents is not the issue. My issue is setting the String password to equal whatever is in the text file. Please help me out. Here is the code. (jPasswordField1 is the password box and jButton1 is the button to open menus to change password.)
package my.shortcutApp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class shotcutApp extends javax.swing.JFrame
{
File passwordFile = new File("C:/Program Files (x86)/Steam/userdata/193530500/7/remote/Game Data.txt");
String password; // I need this to equal ^^
String reset = "";
public shotcutApp()
{
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
loginPanel = new javax.swing.JPanel();
jPasswordField1 = new javax.swing.JPasswordField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
loginPanel.setName("Organizer"); // NOI18N
jPasswordField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jPasswordField1ActionPerformed(evt);
}
});
jLabel1.setText("Login");
jButton1.setText("change");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout loginPanelLayout = new javax.swing.GroupLayout(loginPanel);
loginPanel.setLayout(loginPanelLayout);
loginPanelLayout.setHorizontalGroup(
loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(loginPanelLayout.createSequentialGroup()
.addGap(128, 128, 128)
.addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(loginPanelLayout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(128, Short.MAX_VALUE))
);
loginPanelLayout.setVerticalGroup(
loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, loginPanelLayout.createSequentialGroup()
.addContainerGap(259, Short.MAX_VALUE)
.addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPasswordField1)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(loginPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(loginPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void jPasswordField1ActionPerformed(java.awt.event.ActionEvent evt) {
String input = evt.getActionCommand();
if (input.equals(password))
{
loginPanel.setVisible(false);
}
else if (!input.equals(password))
{
JOptionPane.showMessageDialog(this, "Wrong password.");
}
jPasswordField1.setText("");
}
#SuppressWarnings("ConvertToTryWithResources")
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (!passwordFile.exists())
{
reset = JOptionPane.showInputDialog("Please enter new password.");
try {passwordFile.createNewFile();} catch (IOException ex) {Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);}
try {
BufferedWriter output = new BufferedWriter(new FileWriter(passwordFile));
output.write(reset);
output.close();
} catch (IOException ex) {
Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (passwordFile.exists())
{
reset = JOptionPane.showInputDialog("Please enter old password.");
if (reset.equals(password))
{
try {PrintWriter pw = new PrintWriter(passwordFile);pw.close();} catch (FileNotFoundException ex) {Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);}
password = JOptionPane.showInputDialog("Please enter new password.");
try {
BufferedWriter output = new BufferedWriter(new FileWriter(passwordFile));
output.write(password);
output.close();
} catch (IOException ex) {
Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (!reset.equals(password))
{
JOptionPane.showMessageDialog(this, "Wrong password.");
}
}
}
public static void main(String args[])
{
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new shotcutApp().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JPanel loginPanel;
// End of variables declaration
}
if i did understood you correctly you need actually a configuration file and read-write properties from it. I have make one for you please see. I made the password in textfield to show you what is going on , you can later change it to passwordfield. You can also open configuration file and make changes and save.You can give whatever name you want to your configuration file. You can change the password as much as you can when you enter the new ones and press save button and then the configuration file will be updated.
Configuration File
Create Class Configs
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Configs {
public static Properties prop = new Properties();
public void SaveProp(String title, String value) {
try {
prop.setProperty(title, value);
prop.store(new FileOutputStream("configuration.con"), null);
} catch (IOException e) {
}
}
public String GetProp(String title) {
String value = "";
try {
prop.load(new FileInputStream("configuration.con"));
value = prop.getProperty(title);
} catch (IOException e) {
}
return value;
}
}
Your Fields in Login Class
Configs con = new Configs();
String UserName = "UserName";
String Password = "Password";
String newpassword;
String newuser;
Save Button Action Performed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
con.SaveProp(UserName, jTextField1.getText());
con.SaveProp(Password, jTextField2.getText());
}
Display Button Action Performed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
newuser = con.GetProp("UserName");
newpassword = con.GetProp("Password");
jTextField3.setText(newuser);
jTextField4.setText(newpassword);
}
I am making a client-server Java app that is going to be MV(C, P) like. My current problem is once the client get's a Player object it needs to tell the GUI that the Player was changed and it should update everything on GUI. (Not too detailed, so entire update shouldn't be bad)
/*
* ClientGUI.java
*
* Created on Dec 10, 2009, 7:51:31 PM
*/
package inequity;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Administrator
*/
public class ClientGUI extends javax.swing.JFrame
{
private Socket socClient;
private ObjectOutputStream socketOut;
private ObjectInputStream socketIn;
PriorityBlockingQueue<Command> clientQ = null;
private Player me;
public ClientGUI()
{
initComponents();
setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
clientQ = new PriorityBlockingQueue<Command>(Server.CLIENT_QUEUE_SIZE, new CompObj());
me = new Player();
}
public void initPlayer(String name, String color)
{
me.name = name;
me.color = color;
}
public boolean connect(int port)
{
try
{
socClient = new Socket("127.0.0.1", port);
if(socClient.isConnected())
System.out.println("Connected");
socketOut = new ObjectOutputStream(socClient.getOutputStream());
socketIn = new ObjectInputStream(socClient.getInputStream());
socketOut.writeObject(new PlayerUpdate(me, 2));
new ClientListener(socketIn).start();
}
catch(Exception e)
{
try
{
if(socketOut != null)
{
socketOut.flush();
socketOut.close();
}
if(socketIn != null)
{
socketIn.close();
}
System.out.println("Unable to connect");
}
catch (IOException ex)
{
System.out.println("IOException caught");
return false;
}
}
return true;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
txtMsg = new javax.swing.JTextField();
btnSend = new javax.swing.JButton();
PlayerName = new javax.swing.JLabel();
ID = new javax.swing.JLabel();
chat = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
txtMsg.setText("Test");
txtMsg.setName("txtMsg"); // NOI18N
txtMsg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtMsgActionPerformed(evt);
}
});
btnSend.setText("Send");
btnSend.setName("btnSend"); // NOI18N
btnSend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSendActionPerformed(evt);
}
});
PlayerName.setText("N/A");
PlayerName.setName("PlayerName"); // NOI18N
ID.setText("ID:");
ID.setName("ID"); // NOI18N
chat.setText("Chatbox");
chat.setName("chat"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnSend, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
.addComponent(txtMsg, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
.addComponent(PlayerName, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(ID)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
.addComponent(chat)
.addGap(41, 41, 41))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ID)
.addComponent(chat))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(PlayerName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtMsg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnSend)
.addContainerGap())
);
pack();
}// </editor-fold>
private void txtMsgActionPerformed(java.awt.event.ActionEvent evt) {
}
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
try
{
if(socketOut != null)
socketOut.writeObject(new ChatCmd(txtMsg.getText(), 10));
}
catch (IOException ex)
{
Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{
String name = "";
String color = "";
JoinGUI join = new JoinGUI(name, color);
ClientGUI client = new ClientGUI();
client.initPlayer(name, color);
client.setVisible(join.prompt());
client.connect(1345);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel ID;
private javax.swing.JLabel PlayerName;
private javax.swing.JButton btnSend;
private javax.swing.JLabel chat;
private javax.swing.JTextField txtMsg;
// End of variables declaration
// End of variables declaration
public class ClientListener extends Thread
{
private ObjectInputStream recieving;
public ClientListener(ObjectInputStream in)
{
recieving = in;
}
#Override
public void run()
{
Command cmd;
while(true)
{
try
{
cmd = (Command) recieving.readObject();
clientQ.add(cmd);
//temp code! Put in clientProxy? Drop to clientQ?
clientQ.take().exec(me);
ID.setText("" + me.getID());
PlayerName.setText("" + me.name);
chat.setText(me.latestChatMsg);
}
catch (InterruptedException ex)
{
Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(ClientListener.class.getName()).log(Level.SEVERE, null, ex);
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(ClientListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
package inequity;
import java.io.Serializable;
import java.util.ArrayList;
/**
*
* #author Administrator
*/
public class Player implements Serializable
{
public ArrayList openHandShakes;
public String latestChatMsg;
private int ID;
public String name;
public String color;
public Player()
{
openHandShakes = new ArrayList();
ID = -1;
name = "";
color = "";
}
public void setID(int id)
{
ID = id;
}
public int getID()
{
return ID;
}
public void openHandShake(int shakeID)
{
openHandShakes.add(shakeID);
}
public boolean closeHandShake(int shakeID)
{
return true;
}
public void latestChat(String message)
{
latestChatMsg = message;
}
}
package inequity;
import javax.swing.Box;
import javax.swing.JTextField;
/**
*
* #author Administrator
*/
public class JoinGUI extends javax.swing.JFrame
{
private JTextField nameBox;
private JTextField colorBox;
public JoinGUI(String name, String color)
{
//give back name and color to clientgui
nameBox = new JTextField("Enter Name");
colorBox = new JTextField("Enter Color");
Box inputMenu = Box.createVerticalBox();
inputMenu.add(nameBox);
inputMenu.add(colorBox);
add(inputMenu);
}
public boolean prompt()
{
setVisible(false);
//wait for enter to be pressed then return true, as clientGUI is waiting to started
//then give name and color to client
return true;
}
}
/*
* Server.java
*/
package inequity;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import java.net.*;
import java.util.concurrent.PriorityBlockingQueue;
/**
* The main class of the application.
*/
public class Server extends JFrame
{
public static final int CLIENT_QUEUE_SIZE = 10;
public static final int SERVER_QUEUE_SIZE = 10;
public Server()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public PlayerProxy wait4client(int playerID, ServerSocket server, PriorityBlockingQueue<Command> srvQ)
{
Socket incoming;
PriorityBlockingQueue<Command> clientQ = null;
Runnable rIn;
Runnable rOut;
Thread tIn = null;
Thread tOut = null;
try
{
incoming = server.accept();
clientQ = new PriorityBlockingQueue<Command>(CLIENT_QUEUE_SIZE, new CompObj());
rIn = new Net2QRunnable(playerID, incoming, srvQ);
rOut = new Q2NetRunnable(playerID, incoming, clientQ);
tIn = new Thread(rIn);
tOut = new Thread(rOut);
tIn.start();
tOut.start();
}
catch (Exception e)
{
e.printStackTrace();
}
clientQ.add(new HelloMsg());
return new PlayerProxy(playerID, tIn, tOut, clientQ);
}
public static void main(String[] args)
{
PriorityBlockingQueue<Command> srvQ = new PriorityBlockingQueue<Command>(SERVER_QUEUE_SIZE, new CompObj());
try
{
Game game = new Game(srvQ);
Server srv = new Server();
ServerSocket server = new ServerSocket(1345);
srv.setVisible(true);
System.out.println("Lobby");
while (game.numPlayers() < 2)
{
game.addPlayer(srv.wait4client(game.numPlayers(), server, srvQ));
}
game.play();
System.out.println("Game Finished");
}
catch (SocketException e)
{
System.out.println("Socket already taken, exiting.");
}
catch (Exception ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I can provide full source if you'd like, but I think that's all that's needed.
Again, a Player object get's sent to the client, which accepts and sets it's Player object to the received one. I want client's Player to say, "Hey GUI! I just got modified. Lemme call an update method that extracts/parses all my data!"
Any help would be appreciated.
UPDATE:
public class ClientListener extends Thread
{
private ObjectInputStream recieving;
public ClientListener(ObjectInputStream in)
{
recieving = in;
}
#Override
public void run()
{
Command cmd;
while(true)
{
try
{
cmd = (Command) recieving.readObject();
clientQ.add(cmd);
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
clientQ.take().exec(me);
if(me.changed == true)
updateGUI();
}
catch (Exception ex)
{
Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
catch (Exception ex)
{
Logger.getLogger(ClientListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Seems like it should be what I want right?
Use SwingUtilities.invokeLater to run a handler in the GUI thread.
Just put your update code in a Runnable instance and pass it to SwingUtilities.InvokeLater(). That will put your runnable into the event dispatch queue
Or you could call invokeAndWait to block until the update is complete.
If you try to call code that updates Swing elements in another thread, it can cause instability in the rest of your code.