How to debug this simple socket client-server application? - java

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

Related

JavaFX app crashing or freezing when button clicked for downloading and showing the progress in a jprogressbar

I am writing a java app using netbeans IDE and using the gui creator, I created a simple project and some buttons for downloading a jar from a website, but, when I click on the button app freezes/crashes and doesn't allow me to click any buttons or anything else and when I maximize the app then minimize the window turn into black thing.
Here is the code generated by gui creator :
/*
* 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.
*/
package mcsm;
/**
*
* #author YReza
*/
import mcsm.download;
public class MCSM1 extends javax.swing.JFrame {
/**
* Creates new form MCSM1
*/
public MCSM1() {
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() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jProgressBar1 = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("MCSM");
setBackground(new java.awt.Color(0, 0, 0));
setForeground(java.awt.Color.white);
jButton1.setText("Run...");
jButton1.setToolTipText("Run Your Server");
jButton1.setFocusPainted(false);
jButton2.setText("Create...");
jButton2.setToolTipText("Create The Server Using Th Downoaded Jar");
jButton2.setFocusPainted(false);
jButton3.setText("Configuration..");
jButton3.setToolTipText("Configure The Server");
jButton3.setFocusPainted(false);
jButton4.setText("Download");
jButton4.setToolTipText("Download The Jar From Official WebSite");
jButton4.setBorderPainted(false);
jButton4.setFocusPainted(false);
jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton4MouseClicked(evt);
}
});
jProgressBar1.setToolTipText("The Progress Of Your Task");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(122, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3))
.addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(125, 125, 125))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(130, Short.MAX_VALUE)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addGap(153, 153, 153))
);
pack();
}// </editor-fold>
private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {
download task = new download();
task.Task();
}
/**
* #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(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MCSM1.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 MCSM1().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JButton jButton1;
public javax.swing.JButton jButton2;
public javax.swing.JButton jButton3;
public javax.swing.JButton jButton4;
public javax.swing.JProgressBar jProgressBar1;
// End of variables declaration
}
And it is my Download class (I used This method for showing the progress on jprogressbar) :
package mcsm;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
public class download extends javax.swing.JFrame {
public void Task() {
MCSM1 jp = new MCSM1();
JProgressBar jp1 = jp.jProgressBar1;
try {
URL url = new URL("https://cdn.getbukkit.org/spigot/spigot-1.16.5.jar");
try {
HttpURLConnection httpConnection = (HttpURLConnection)(url.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
try {
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in .read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100000d);
// update progress bar
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
jp1.setValue(currentProgress);
}
});
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
} catch (IOException ioe2) {
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
}
try {
java.io.FileOutputStream fos = new java.io.FileOutputStream("Spigot.jar");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
}
// calculate progress
}
}
If you want to run it you should have these in lib folder :

Why is my Java timer not working?

I am trying to make a simple Java GUI that allows you to enter a time, and once the time runs out, it plays a sound. For some reason I find an error despite looking a many different sources that all tell me to use Timer or Handler. Here is my code:
/*
* 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 CIS
*/
import java.io.*;
import sun.audio.*;
import java.util.TimerTask;
public class Timer extends javax.swing.JFrame {
public Timer() {
initComponents();
initEditable();
}
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop1 = null;
AudioPlayer ABC = AudioPlayer.player;
AudioStream ABCD;
AudioData ABCDE;
ContinuousAudioDataStream loop2 = null;
public void initEditable(){
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
textFieldTimer = new javax.swing.JTextField();
buttonTest = new javax.swing.JButton();
buttonSet = new javax.swing.JButton();
labelTimeRemaining = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonTest.setText("Test Sound");
buttonTest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonTestActionPerformed(evt);
}
});
buttonSet.setText("Set");
buttonSet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSetActionPerformed(evt);
}
});
labelTimeRemaining.setText("time remaing");
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.TRAILING, false)
.addComponent(textFieldTimer)
.addComponent(buttonTest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(buttonSet)
.addComponent(labelTimeRemaining)))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonSet, buttonTest, labelTimeRemaining, textFieldTimer});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldTimer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelTimeRemaining))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonTest)
.addComponent(buttonSet)))
);
pack();
}// </editor-fold>
int hello = 1000;
public void music1(){
ContinuousAudioDataStream loop = null;
try
{
InputStream alert = new FileInputStream("alert.wav");
BGM = new AudioStream(alert);
AudioPlayer.player.start(BGM);
//MD = BGM.getData();
//loop = new ContinuousAudioDataStream(MD)
}
catch(FileNotFoundException e){
System.out.print(e.toString());
}
catch(IOException error)
{
System.out.print(error.toString());
}
MGP.start(loop1);
}
private void buttonSetActionPerformed(java.awt.event.ActionEvent evt) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
music1();
}
}, 2000);
}
private void buttonTestActionPerformed(java.awt.event.ActionEvent evt) {
music1();
}
/**
* #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(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Timer.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 Timer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonSet;
private javax.swing.JButton buttonTest;
private javax.swing.JLabel labelTimeRemaining;
private javax.swing.JTextField textFieldTimer;
// End of variables declaration
}
When I get to the line new Timer().schedule(new TimerTask() {
I get on error on the schedule.
I apologize if my method of presenting my problem is incorrect, I'm new here and new to Java programming as well.
Your class has the same name as the java.util.Timer class. You must disambiguate by fully qualifying that class name:
new java.util.Timer().schedule(new TimerTask() {

Java - setting password from file in GUI

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

Update JList Elements

I'm trying to update a JList. I have defined it to use a listModel. In that regard, it works fine because in my main() method I can add elements to the listModel and they will be reflected in the JList. However, I'm trying to force update it with new information by calling a function (below). This code does not work at all. Any help would be appreciated.
public void updateList(List<String> gamelist) {
listModel.removeAllElements();
for (int i=0;i<gamelist.size();i++) {
System.out.println(gamelist.get(i).toString());
listModel.addElement(gamelist.get(i).toString());
}
listGames.setModel(listModel);
}
public class Main extends javax.swing.JFrame {
/**
* Creates new form Main
*/
private javax.swing.JEditorPane editorWeb = new JEditorPane();
private DefaultListModel listModel = new DefaultListModel();
public Main() {
initComponents();
scrollWeb.setViewportView( editorWeb );
editorWeb.setEditable(false);
editorWeb.setSize(scrollWeb.getWidth(), scrollWeb.getHeight());
try {
editorWeb.setPage("http://www.futureretrogaming.tk/news.html");
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
listModel.addElement("test");
}
I think the problem is that I"m making a new main to return the value from my other form.
public class LoginWindow extends javax.swing.JFrame {
/**
* Creates new form LoginWindow
*/
List<String> games = new ArrayList<String>();
Main program = new Main();
public LoginWindow() {
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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
textUsername = new javax.swing.JTextField();
textPassword = new javax.swing.JPasswordField();
buttonLogin = new javax.swing.JButton();
jLabel1.setText("Please provide your username and password:");
jLabel1.setToolTipText("");
jLabel2.setText("Username:");
jLabel3.setText("Password:");
buttonLogin.setText("Submit");
buttonLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonLoginActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textUsername))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(buttonLogin))
.addContainerGap(84, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(textUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addComponent(buttonLogin)
.addContainerGap())
);
pack();
}// </editor-fold>
private void buttonLoginActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
String loginurl = "http://futureretrogaming.tk/scripts/checklogin.php?username="+textUsername.getText()+"&password="+textPassword.getText();
System.out.println(loginurl);
URL checklogin = new URL(loginurl);
URLConnection yc = checklogin.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
URL file2 = new URL(loginurl);
Scanner sc2 = new Scanner(file2.openStream());
String inputLine = "";
int i = 0;
while (/*(inputLine = in.readLine()) != null*/sc2.hasNext()) {
inputLine = inputLine.trim();
String input = sc2.next();
input = input.trim();
if (inputLine.equalsIgnoreCase("false") || input.equalsIgnoreCase("false")) {
JOptionPane.showMessageDialog(this,"Username or Password is incorrect. Please try again.", "Error", JOptionPane.PLAIN_MESSAGE);
break;
}
else if (inputLine.equalsIgnoreCase("empty") || input.equalsIgnoreCase("empty")) {
JOptionPane.showMessageDialog(this,"You must type in a username and a password.", "Error",JOptionPane.PLAIN_MESSAGE);
break;
}
else {
System.out.println(input);
if (games == null)
System.out.print("games is null");
games.add(input);
}
}
in.close();
if (games!=null) {
games.remove(0);
Collections.sort(games);
program.updateList(games);
}
} catch (MalformedURLException ex) {
Logger.getLogger(LoginWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(LoginWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #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(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoginWindow.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 LoginWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonLogin;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPasswordField textPassword;
private javax.swing.JTextField textUsername;
// End of variables declaration
}

why textbox is not auto update in java?

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.

Categories