Multi-threaded Progress Bar not updating while Reading from text file - java

My problem is that It only shows two output in the progress bar 0% if not started and 100% instantly when the program finished scanning the file. I want it to show the process while scanning the file not 100% instantly.(its not updating the progress bar) Any help would be great. Thanks! :) Here is the full code:
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.FileReader;
import java.io.BufferedReader;
import javax.swing.JOptionPane;
import javax.swing.*;
import javax.swing.SwingWorker;
import javax.swing.SwingUtilities;
import java.util.List;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import
public class Log_in extends javax.swing.JFrame {
/**
* Creates new form Log_in
*/
FileOutputStream fos;
DataOutputStream dos;
FileInputStream fis ;
DataInputStream dis;
private Timer time;
private ActionListener ActionL;
public static String r;
public Log_in(){
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Gondar\\Music\\bg.jpg")));
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() {
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("Student Name");
jTextField1.setToolTipText("Enter your profile name.");
jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButton1.setText("Submit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Rockwell", 0, 26)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Curriculum Simulator with Recommendation System");
jProgressBar1.setStringPainted(true);
jLabel2.setForeground(new java.awt.Color(102, 255, 102));
jLabel2.setText("Loading Profile....");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 208, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(203, 203, 203))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(477, 477, 477)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(465, 465, 465)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(420, 420, 420)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(83, 83, 83)
.addComponent(jLabel1)
.addGap(74, 74, 74)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 244, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
SwingWorker sw= new SwingWorker<Boolean,Integer>() {
protected Boolean doInBackground() throws Exception {
try {
double lengthPerPercent = 100.0;
long readLength = 0;
FileReader fr=new FileReader("mario.txt");
BufferedReader br=new BufferedReader(fr);
while((r = br.readLine())!= null){
readLength += r.length();
jProgressBar1.setValue((int)(lengthPerPercent * readLength));
}
fr.close();
}catch(Exception err) {
System.out.println(err);
}
return true;
}
protected void process(List<Integer> chunks) {
for (Integer i : chunks)
jProgressBar1.setValue(i);
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("Student Name");
jTextField1.setToolTipText("Enter your profile name.");
jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButton1.setText("Submit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Rockwell", 0, 26)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Curriculum Simulator with Recommendation System");
jProgressBar1.setStringPainted(true);
jLabel2.setForeground(new java.awt.Color(102, 255, 102));
jLabel2.setText("Loading Profile....");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 208, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(203, 203, 203))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(477, 477, 477)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(465, 465, 465)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(420, 420, 420)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(83, 83, 83)
.addComponent(jLabel1)
.addGap(74, 74, 74)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 244, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
protected void done() {
try {
if (jProgressBar1.getValue() == 100 )
jProgressBar1.setValue(100); // 100% done
else
System.out.println("ProcessingFailed.");
}
catch (Exception ex) {
System.out.println("Processing Failed.");
}
}
};
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
sw.execute();
/*try {
double lengthPerPercent = 100.0;
long readLength = 0;
FileReader fr=new FileReader("mario.txt");
BufferedReader br=new BufferedReader(fr);
while ((r = br.readLine()) != null) {
readLength += r.length();
jProgressBar1.setValue((int) Math.round(lengthPerPercent * readLength));
}
jProgressBar1.setValue(100);
fr.close();
if (jProgressBar1.getValue() == 100) {
}
}catch(Exception err) {
JOptionPane.showMessageDialog(this, err);
}
}
/**
* #param args the command line arguments
*/
}
public static void main(String args[]) throws Exception{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Log_in().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}

So, you have two basic problems, first, you never call publish, so process will never be called and secondly, you progress calculations are wrong...
double lengthPerPercent = 100.0;
long readLength = 0;
FileReader fr=new FileReader("mario.txt");
BufferedReader br=new BufferedReader(fr);
while((r = br.readLine())!= null){
readLength += r.length();
jProgressBar1.setValue((int)(lengthPerPercent * readLength));
So, if you read 10 characters, you progress value would be 100 * 10 which equals 1000!
SwingWorker already has "progress" support, which you can use a PropertyChangeListener to be notified when it changes, for example
So, your code should look for more like...
File file = new File("mario.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String r = null;
long fileLength = file.length();
long readLength = 0;
while ((r = br.readLine()) != null) {
readLength += r.length();
setProgress((int) (((float) readLength / (float) fileLength) * 100f);
}
}
Then you would attach a PropertyChangeListener to the instance of SwingWorker and update the progress when the progress property changes

Related

Why can't I return true? am I making a mistake in the database query part?

I have tried all kinds of combinations since morning but I can't return any true value. The information I entered is completely correct.
Help me pls why can't I return true? am I making a mistake in the database query part?
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import java.sql.ResultSet;
/*
* 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 seyme
*/
public class para_ekle extends javax.swing.JFrame {
private boolean ahmet;
/**
* Creates new form para_ekle
*/
public para_ekle() {
initComponents();
}
static boolean ekle = false;
public void kontrol() throws SQLException{
Connection connect = null;
dbbaglanti db = new dbbaglanti();
connect = db.getConnection();
Statement oku = ( Statement) connect.createStatement();
String cekilenid = idtext4.getText();
int cevrilenid = Integer.parseInt(cekilenid);
String sifrebilgisi = sifretext4.getText();
String tutarbilgisi = idtext4.getText();
int cevrilentutar = Integer.parseInt(tutarbilgisi);
try {
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Bilgilerde Bir Hata Bulunuyor!");
}
ResultSet rs;
rs = oku.executeQuery("SELECT count(id) as \"giris\" FROM dbkullanici.kullanicilar WHERE id ="+ cevrilenid +" && sifre = '"+sifrebilgisi+"'" +";");
while (rs.next()) {
int id = rs.getInt("giris");
if(id == 1){ boolean ahmet = ekle == true; } else if (id == 0 ){boolean ahmet = ekle == false;}
}
if(ahmet == true){
erortext.setText("verilerdogru");
}else if(ahmet == false){
erortext.setText("Bilgileriniz Veritabanımızda ki veriler ile eşleşmedi");
}
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
idtext4 = new javax.swing.JTextField();
sifretext4 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
tutartext = new javax.swing.JTextField();
erortext = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Segoe UI Black", 1, 36)); // NOI18N
jLabel1.setText("ISSEY FİNANS SİSTEMİ");
jLabel2.setFont(new java.awt.Font("Ink Free", 1, 14)); // NOI18N
jLabel2.setText("ISSEY ile paralarınız daha değerli");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(37, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 428, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(128, 128, 128))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("Hesap Şifreniz: ");
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setText("Hesap İd Numaranızı Yazınız: ");
idtext4.setText("jTextField1");
sifretext4.setText("jTextField2");
jLabel7.setText("İd Numaranızı Bilmiyorsanız Kullanıcı listeleme panelinden görüntüleyebilirsiniz.");
jButton1.setText("Ana Menü'ye Dön");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel3.setText("Eklemek İstediğiniz Tutar");
tutartext.setText("jTextField1");
erortext.setForeground(new java.awt.Color(255, 0, 0));
jButton2.setText("Para Ekle");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel4.setForeground(new java.awt.Color(102, 102, 102));
jLabel4.setText(" Para Eklemi işlemi için tüm bilgileri büyük küçük harf ve boşluk dahil doğru girmelisiniz.");
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(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(erortext, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(idtext4)
.addComponent(sifretext4)
.addComponent(tutartext, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(8, 8, 8)))
.addGap(61, 61, 61))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 408, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(23, 23, 23))))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(idtext4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sifretext4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(tutartext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(erortext, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
kontrol();
} catch (SQLException ex) {
Logger.getLogger(para_ekle.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(para_ekle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(para_ekle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(para_ekle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(para_ekle.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 para_ekle().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel erortext;
private javax.swing.JTextField idtext4;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField sifretext4;
private javax.swing.JTextField tutartext;
// End of variables declaration
}

Strange NullPointerException in Java Client-Server program

I am creating a 2 player game in which clients receive 2 Strings from the server and have to respond with a String of their own. The internal processing is irrelevant here. The main thing is, whenever I send data from server, one of the clients ends up showing a NullPointerException for a setText() function. I am baffled as nobody else at my university knows the reason for that. Please help me solve this issue.
Here is the code (the IDE is NetBeans 7.3.1):
Server
public class TCPServer {
public static void main(String argv[]) throws Exception {
String childWord, childWord2;
Trie1 obj = new Trie1();
obj.loadTrie();
ServerSocket welcomeSocket = new ServerSocket(6759);
ServerSocket welcomeSocket2 = new ServerSocket(6559);
//BufferedReader dd = new BufferedReader(new InputStreamReader(System.in));
String parentWord;
while (true) {
Socket connectionSocket = welcomeSocket.accept();
Socket connectionSocket2 = welcomeSocket2.accept();
//parentWord = dd.readLine();
parentWord = GlobalStuff.word;
System.out.println("word: "+parentWord);
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader inFromClient2 =
new BufferedReader(new InputStreamReader(connectionSocket2.getInputStream()));
DataOutputStream outToClient2 =
new DataOutputStream(connectionSocket2.getOutputStream());
outToClient.writeBytes(parentWord + "\n");
outToClient2.writeBytes(parentWord + "\n");
outToClient.writeBytes(GlobalStuff.sentence + "\n");
outToClient2.writeBytes(GlobalStuff.sentence + "\n");
childWord = inFromClient.readLine();
childWord2 = inFromClient2.readLine();
/*System.out.println(childWord);
System.out.println(childWord2);*/
//System.out.println(clientSentence);
if (childWord.equals(childWord2)) {
System.out.println("The suggestions match!!");
obj.Trie1Main(parentWord, childWord);
} else {
System.out.println("The suggestions DO NOT match...the users entered:");
System.out.println(childWord+" and "+childWord2);
}
}
}
}
Client:
package clientserver;
import markI.*;
import sessionmanager.*;
import java.io.*;
import java.net.*;
public class Player1 extends javax.swing.JFrame {
private static Socket clientSocket;
private static BufferedReader inFromUser;
private static DataOutputStream outToServer;
private static BufferedReader inFromServer;
private static String modifiedSentence;
private static String modifiedWord;
/**
* Creates new form TestFrameOne
*/
public Player1() {
initComponents();
}
//user defined
private void initComponents() {
tlabel = new javax.swing.JLabel();
ilabel = new javax.swing.JLabel();
totalScore = new javax.swing.JLabel();
wordtf = new javax.swing.JTextField();
submit = new javax.swing.JButton();
close = new javax.swing.JButton();
round = new javax.swing.JLabel();
opponent = new javax.swing.JLabel();
hword = new javax.swing.JLabel();
timeLeft = new javax.swing.JLabel();
points = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
sentenceArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tlabel.setFont(new java.awt.Font("Trebuchet MS", 1, 24)); // NOI18N
tlabel.setForeground(new java.awt.Color(51, 0, 255));
tlabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
tlabel.setText("WORD KING");
ilabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
ilabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/markI/crown_low.png"))); // NOI18N
totalScore.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
totalScore.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
totalScore.setText("0");
totalScore.setBorder(javax.swing.BorderFactory.createTitledBorder("Net Score"));
wordtf.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
wordtf.setBorder(javax.swing.BorderFactory.createTitledBorder("Alternate Word"));
submit.setBackground(new java.awt.Color(102, 0, 255));
submit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
submit.setText("Submit");
submit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitActionPerformed(evt);
}
});
close.setText("X");
close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeActionPerformed(evt);
}
});
round.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
round.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
round.setText("0");
round.setBorder(javax.swing.BorderFactory.createTitledBorder("Round"));
opponent.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
opponent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/markI/face_low.jpg"))); // NOI18N
opponent.setBorder(javax.swing.BorderFactory.createTitledBorder("OPPONENT"));
hword.setFont(new java.awt.Font("Trebuchet MS", 1, 18)); // NOI18N
hword.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
hword.setBorder(javax.swing.BorderFactory.createTitledBorder("Highlighted Word"));
timeLeft.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
timeLeft.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
timeLeft.setText("30");
timeLeft.setBorder(javax.swing.BorderFactory.createTitledBorder("Time"));
points.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
points.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
points.setText("0");
points.setBorder(javax.swing.BorderFactory.createTitledBorder("Points"));
jButton1.setBackground(new java.awt.Color(102, 0, 255));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setText("Leave Game");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
sentenceArea.setColumns(20);
sentenceArea.setRows(5);
sentenceArea.setText("The quick brown fox jumps over a lazy dog.");
sentenceArea.setBorder(javax.swing.BorderFactory.createTitledBorder("Sentence"));
jScrollPane1.setViewportView(sentenceArea);
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.TRAILING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(hword, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(wordtf, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(55, 55, 55)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(ilabel)
.addComponent(tlabel))))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(points, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(timeLeft, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(round, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(totalScore, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(opponent)
.addGap(18, 18, 18)
.addComponent(close)))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(opponent))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(close)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(ilabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tlabel)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(hword, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(round)
.addComponent(totalScore))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(points)
.addComponent(timeLeft)
.addComponent(wordtf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>
private void submitActionPerformed(java.awt.event.ActionEvent evt) {
//wordtf.setText(modifiedSentence);
try {
String sentence = wordtf.getText();
System.out.println(sentence);
outToServer.writeBytes(sentence + '\n');
clientSocket.close();
} catch (Exception e) {
System.out.println("Some error through submit button.\n" + e.getMessage());
}
}
private void closeActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(WIDTH); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.setVisible(false);
sessionmanager.WelcomePage.main(null);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws Exception {
/* 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(TestFrameOne.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestFrameOne.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestFrameOne.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestFrameOne.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 Player1().setVisible(true);
}
});
//Start clientserver
inFromUser = new BufferedReader(new InputStreamReader(System.in));
clientSocket = new Socket("172.16.30.183", 6759);
//clientSocket = new Socket("172.16.38.156", 6759);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
modifiedWord = inFromServer.readLine();
System.out.println("FROM SERVER: word " + modifiedWord);
hword.setText(modifiedWord);
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: sentence " + modifiedSentence);
sentenceArea.setText(modifiedSentence);
//End clientserver
}
// Variables declaration - do not modify
private javax.swing.JButton close;
public static javax.swing.JLabel hword;
private javax.swing.JLabel ilabel;
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel opponent;
private javax.swing.JLabel points;
private javax.swing.JLabel round;
public static javax.swing.JTextArea sentenceArea;
private javax.swing.JButton submit;
private javax.swing.JLabel timeLeft;
private javax.swing.JLabel tlabel;
private javax.swing.JLabel totalScore;
public static javax.swing.JTextField wordtf;
// End of variables declaration
}
This is the Exception
This is supposed to be the output if the client runs correctly
Line 272 in the error message is hword.setText(modifiedWord)
So this means that hword is null and you have to ensure it has been initialised before you call this method.
Any update to the GUI should be performed on the GUI thread in any case. I suggest you submit a task to perform the update. This way it should be initialised by the time you use it.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
hword.setText(modifiedWord);
}
});
What you should be doing though, is calling this method on the Player1 instance instead of setting a static field. You really shouldn't be initialising static fields in a constructor.
Player1 player1 = new Player1();
EventQueue.invokeLater(() -> player1.setVisible(true));
EventQueue.invokeLater(() -> player1.setHwordText(modifiedWord));
This way you don't need the static fields.

JTextField resizing after setting text that is longer than its initial size?

This is what the textfield looks like before clicking the check button:
This is what happens after clicking check. This only happens with a string that is longer than the textfield.
This is the code from netbeans:
package filevalidator;
import java.awt.Color;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
/**
*
* #author Kosar
*/
public class Validator extends javax.swing.JFrame {
static String path1 = null;
static String path2 = null;
/**
* Creates new form Validator
*/
public Validator() {
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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
file1path = new javax.swing.JTextField();
select1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
file2path = new javax.swing.JTextField();
select2 = new javax.swing.JButton();
hash1 = new javax.swing.JLabel();
hash2 = new javax.swing.JLabel();
result = new javax.swing.JLabel();
checkBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel1.setText("Original File:");
file1path.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
file1path.setAutoscrolls(false);
select1.setText("Select");
select1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
select1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel2.setText("Second File:");
file2path.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
file2path.setAutoscrolls(false);
file2path.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
select2.setText("Select");
select2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
select2ActionPerformed(evt);
}
});
hash1.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
hash1.setForeground(java.awt.Color.blue);
hash1.setText(" ");
hash2.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
hash2.setForeground(java.awt.Color.blue);
hash2.setText(" ");
result.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
result.setText(" ");
checkBtn.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
checkBtn.setText("Check");
checkBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(32, 32, 32)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(result, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(151, 151, 151)
.addComponent(hash2, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE))
.addComponent(hash1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(30, 30, 30))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(file1path, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(file2path))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(select1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(checkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(331, 331, 331))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(59, 59, 59)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(file1path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select1))
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(file2path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(hash1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hash2)
.addGap(13, 13, 13)
.addComponent(result)
.addGap(5, 5, 5)
.addComponent(checkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
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()
.addGap(27, 27, 27)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void select1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select file");
if (chooser.showOpenDialog(select1) == JFileChooser.APPROVE_OPTION) {
path1 = chooser.getSelectedFile().getAbsolutePath();
}
file1path.setText(path1);
file1path.setBackground(Color.white);
}
private void select2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select file");
if (chooser.showOpenDialog(select2) == JFileChooser.APPROVE_OPTION) {
path2 = chooser.getSelectedFile().getAbsolutePath();
}
file2path.setText(path2);
file2path.setBackground(Color.white);
}
private void checkBtnActionPerformed(java.awt.event.ActionEvent evt) {
try {
HashMD5 hasher = new HashMD5();
try {
hash1.setText(hasher.hash(path1));
hash2.setText(hasher.hash(path2));
} catch (NoSuchAlgorithmException | IOException ex) {
}
if ( hash1.getText().equals(hash2.getText())) {
result.setForeground(Color.GREEN);
result.setText("Hashes are the same. File has not been modified.");
}
else {
result.setForeground(Color.RED);
result.setText("Hashes are not the same. File has been modified.");
}
} catch (NullPointerException e) {
if (file1path.getText() == null) {
file1path.setBackground(Color.red);
}
else if (file2path.getText() == null) {
file2path.setBackground(Color.red);
}
else {
file1path.setBackground(Color.red);
file2path.setBackground(Color.red);
}
}
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JButton checkBtn;
private javax.swing.JTextField file1path;
private javax.swing.JTextField file2path;
private javax.swing.JLabel hash1;
private javax.swing.JLabel hash2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel result;
private javax.swing.JButton select1;
private javax.swing.JButton select2;
// End of variables declaration
}
You can handle it by using TextField and its method to set columns i.e. "setColumns(int numOfCols)"
import java.awt.FlowLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class TextFieldExample extends JFrame {
JFrame frame = new JFrame();
public TextFieldExample()
{
frame = new JFrame("Test");
Container container = frame.getContentPane();
JTextField fld1 = new JTextField("Java C++ C");
JTextField fld2 = new JTextField("");
JTextField fld3 = new JTextField("");
fld1.setColumns(5); //Now, it will not be resized.
fld2.setColumns(7); //Now, it will not be resized.
fld3.setColumns(9); //Now, it will not be resized.
container.setLayout(new FlowLayout());
container.add(fld1);
container.add(fld2);
container.add(fld3);
frame.setVisible(true);
frame.setSize(150,150);
}
public static void main(String[] args) {
TextFieldExample obj = new TextFieldExample();
}
}

Button not working to draw line graph having its coordinate (x1, x2, y1, y2)

I am getting a trouble with displaying the line graph. When I press a button "Plot", nothing happens.
How to solve this problem?
package linecalculate;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
*
* #author HuynhNgocTan
*/
public class main extends javax.swing.JFrame {
boolean temp = false;
/**
* Creates new form main
*/
public main() {
setTitle("HuynhNgocTan - line");
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() {
jLabelX1 = new javax.swing.JLabel();
jLabelY1 = new javax.swing.JLabel();
jLabelX2 = new javax.swing.JLabel();
jLabelY2 = new javax.swing.JLabel();
jLabelSlope = new javax.swing.JLabel();
jLabelDistance = new javax.swing.JLabel();
jLabelAnglerad = new javax.swing.JLabel();
jLabelAngledeg = new javax.swing.JLabel();
jLabelEquation = new javax.swing.JLabel();
jTextFieldSlope = new javax.swing.JTextField();
jTextFieldDistance = new javax.swing.JTextField();
jTextFieldAnglerad = new javax.swing.JTextField();
jTextFieldAngledeg = new javax.swing.JTextField();
jTextFieldEquation = new javax.swing.JTextField();
jButtonCalculate = new javax.swing.JButton();
jButtonPlot = new javax.swing.JButton();
jTextFieldX1 = new javax.swing.JTextField();
jTextFieldY2 = new javax.swing.JTextField();
jTextFieldX2 = new javax.swing.JTextField();
jTextFieldY1 = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jPanelDraw = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabelX1.setText("X1");
jLabelY1.setText("Y1");
jLabelX2.setText("X2");
jLabelY2.setText("Y2");
jLabelSlope.setText("Slope");
jLabelDistance.setText("Distance between points");
jLabelAnglerad.setText("Angle (rad)");
jLabelAngledeg.setText("Angle (deg)");
jLabelEquation.setText("Equation of the line");
jButtonCalculate.setText("Calculate");
jButtonCalculate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCalculateActionPerformed(evt);
}
});
jButtonPlot.setText("Plot");
jButtonPlot.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonPlotActionPerformed(evt);
}
});
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
jLabel10.setForeground(new java.awt.Color(0, 51, 255));
jLabel10.setText("Line Calculation - version 1.0");
javax.swing.GroupLayout jPanelDrawLayout = new javax.swing.GroupLayout(jPanelDraw);
jPanelDraw.setLayout(jPanelDrawLayout);
jPanelDrawLayout.setHorizontalGroup(
jPanelDrawLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 384, Short.MAX_VALUE)
);
jPanelDrawLayout.setVerticalGroup(
jPanelDrawLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelSlope)
.addGap(18, 18, 18)
.addComponent(jTextFieldSlope, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelAnglerad)
.addGap(18, 18, 18)
.addComponent(jTextFieldAnglerad, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelX2)
.addGap(18, 18, 18)
.addComponent(jTextFieldX2, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelX1)
.addGap(18, 18, 18)
.addComponent(jTextFieldX1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelY2)
.addGap(18, 18, 18)
.addComponent(jTextFieldY2, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelY1)
.addGap(18, 18, 18)
.addComponent(jTextFieldY1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelDistance)
.addGap(18, 18, 18)
.addComponent(jTextFieldDistance, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelAngledeg)
.addGap(18, 18, 18)
.addComponent(jTextFieldAngledeg, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 65, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanelDraw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelEquation)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jTextFieldEquation, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(21, 21, 21))))
.addGroup(layout.createSequentialGroup()
.addGap(131, 131, 131)
.addComponent(jButtonCalculate)
.addGap(92, 92, 92)
.addComponent(jButtonPlot)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap(61, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelX1)
.addComponent(jLabelY1)
.addComponent(jTextFieldX1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldY1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelX2)
.addComponent(jLabelY2)
.addComponent(jTextFieldY2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldX2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelSlope)
.addComponent(jLabelDistance)
.addComponent(jTextFieldSlope, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldDistance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelAnglerad)
.addComponent(jLabelAngledeg)
.addComponent(jTextFieldAnglerad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldAngledeg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelEquation)
.addComponent(jTextFieldEquation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonCalculate)
.addComponent(jButtonPlot))
.addGap(18, 18, 18)
.addComponent(jPanelDraw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(46, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public boolean isNumeric(String str)
{
try
{
Double.parseDouble(str);
}
catch(Exception e)
{
return (false);
}
return(true);
}
public double Round(double val, int plc)
{
double pwr = Math.pow(10,plc);
val = val * pwr;
double tmp = (int) val;
if( ((int)(val + .5)) == (int) val)
return (tmp/pwr);
else
return((tmp + 1.0)/pwr);
}
private void jButtonCalculateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here
double x1;
double x2;
double y1;
double y2;
double length_of_x;
double length_of_y;
double slope;
double opposite;
double angle_degrees;
double angle_radians;
double y_intercept;
double distance_between_2_points;
x1 = (double) (Double.parseDouble(jTextFieldX1.getText()));
x2 = (double) (Double.parseDouble(jTextFieldX2.getText()));
y1 = (double) (Double.parseDouble(jTextFieldY1.getText()));
y2 = (double) (Double.parseDouble(jTextFieldY2.getText()));
length_of_x = x2 - x1;
length_of_y = y2 - y1;
slope = length_of_y / length_of_x;
slope = (double) Round(slope,2);
opposite = y2 - y1;
distance_between_2_points = Math.sqrt((length_of_x * length_of_x) + (length_of_y * length_of_y));
distance_between_2_points = (double) Round(distance_between_2_points,2);
angle_radians = opposite / distance_between_2_points;
angle_radians = (double) Round(angle_radians,2);
angle_degrees = angle_radians * (180 / 3.14159);
angle_degrees = (double) Round(angle_degrees,2);
y_intercept = (double) slope*(-x1)+y1;
jTextFieldSlope.setText(slope + "");
jTextFieldDistance.setText(distance_between_2_points + "");
jTextFieldAnglerad.setText(angle_radians + "");
jTextFieldAngledeg.setText(angle_degrees + "");
jTextFieldEquation.setText("Y = " + slope + "" + "X + (" + y_intercept + ")");
}
private void jButtonPlotActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
temp=true;
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
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(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonCalculate;
private javax.swing.JButton jButtonPlot;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabelAngledeg;
private javax.swing.JLabel jLabelAnglerad;
private javax.swing.JLabel jLabelDistance;
private javax.swing.JLabel jLabelEquation;
private javax.swing.JLabel jLabelSlope;
private javax.swing.JLabel jLabelX1;
private javax.swing.JLabel jLabelX2;
private javax.swing.JLabel jLabelY1;
private javax.swing.JLabel jLabelY2;
private javax.swing.JPanel jPanelDraw;
private javax.swing.JTextField jTextFieldAngledeg;
private javax.swing.JTextField jTextFieldAnglerad;
private javax.swing.JTextField jTextFieldDistance;
private javax.swing.JTextField jTextFieldEquation;
private javax.swing.JTextField jTextFieldSlope;
private javax.swing.JTextField jTextFieldX1;
private javax.swing.JTextField jTextFieldX2;
private javax.swing.JTextField jTextFieldY1;
private javax.swing.JTextField jTextFieldY2;
// End of variables declaration
}
It's because you jButtonPlotActionPerformed method just sets the temp variable to true. Nothing else.

How can I set certain text to be read into a textfield in GUI?

I'm working on an assignment using Binary IO and Event Handling. It looks like this, I think I have most of the basic code down, and now its down to the hard stuff. How can I read text from my .bin file into the seperate text fields?
My fields currently are blank, but when read in they should look something like that and I should be able to parse through seperate sets of information with my two buttons on the bottom.
Here is what I have so far.
I have a RecordViewerUI JFrame form, a RecordViewerPanel JFrame panel, and a SalesAgent java class which holds all of my getters and setters/ constructor for my four variables.
Here is my panel. Sorry for the generated code.
Thanks in advance for any help anyone can offer.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RecordViewerPanel extends javax.swing.JPanel {
String filename = "sales.bin";
ArrayList<SalesAgent> customer = new ArrayList<>();
int curIndex = 0;
/**
* Creates new form RecordViewerPanel
*/
public RecordViewerPanel() throws IOException, ClassNotFoundException {
initComponents();
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(filename)));
ArrayList<SalesAgent> salesForce = new ArrayList<SalesAgent>();
String first = in.readUTF();
String last = in.readUTF();
double sales = in.readDouble();
Date date = (Date) (in.readObject());
} catch (FileNotFoundException ex) {
Logger.getLogger(RecordViewerPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void refreshUI() {
SalesAgent sale = (customer.get(curIndex));
firstTextField.setText(sale.getFirst());
lastTextField.setText(sale.getLast());
salesTextField.setText("$" + String.valueOf(sale.getSales()));
dateTextField.setText(String.valueOf(sale.getDate()));
recordPanel.repaint();
}
/**
* 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() {
filePanel = new javax.swing.JPanel();
fileLabel = new javax.swing.JLabel();
fileLabel1 = new javax.swing.JLabel();
recordPanel = new javax.swing.JPanel();
firstTextField = new javax.swing.JTextField();
lastTextField = new javax.swing.JTextField();
salesTextField = new javax.swing.JTextField();
dateTextField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
previousButton = new javax.swing.JButton();
nextButton = new javax.swing.JButton();
filePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
fileLabel.setBackground(new java.awt.Color(204, 204, 204));
fileLabel.setText("sales.bin");
fileLabel1.setBackground(new java.awt.Color(204, 204, 204));
fileLabel1.setText("Current file:");
javax.swing.GroupLayout filePanelLayout = new javax.swing.GroupLayout(filePanel);
filePanel.setLayout(filePanelLayout);
filePanelLayout.setHorizontalGroup(
filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(fileLabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(fileLabel1)
.addContainerGap(562, Short.MAX_VALUE)))
);
filePanelLayout.setVerticalGroup(
filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(fileLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
.addContainerGap())
.addGroup(filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(fileLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
.addContainerGap()))
);
recordPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
firstTextField.setText("jTextField1");
lastTextField.setText("jTextField1");
salesTextField.setText("jTextField1");
dateTextField.setText("jTextField1");
jLabel1.setText("First Last Sales Date");
previousButton.setText("<<");
previousButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousButtonActionPerformed(evt);
}
});
nextButton.setText(">>");
nextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout recordPanelLayout = new javax.swing.GroupLayout(recordPanel);
recordPanel.setLayout(recordPanelLayout);
recordPanelLayout.setHorizontalGroup(
recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(recordPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(recordPanelLayout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 203, Short.MAX_VALUE))
.addGroup(recordPanelLayout.createSequentialGroup()
.addComponent(firstTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(lastTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(salesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(dateTextField)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, recordPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(previousButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31))
);
recordPanelLayout.setVerticalGroup(
recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(recordPanelLayout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(firstTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lastTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(salesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(dateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
.addGroup(recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(previousButton)
.addComponent(nextButton))
.addGap(27, 27, 27))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(filePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(recordPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(filePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(recordPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>
private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (curIndex > 0) {
curIndex--;
} else if (curIndex == 0) {
curIndex = 4;
}
customer.get(curIndex);
}
private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (curIndex < 4) {
curIndex++;
} else if (curIndex == 4) {
curIndex = 0;
}
customer.get(curIndex);
}
// Variables declaration - do not modify
private javax.swing.JTextField dateTextField;
private javax.swing.JLabel fileLabel;
private javax.swing.JLabel fileLabel1;
private javax.swing.JPanel filePanel;
private javax.swing.JTextField firstTextField;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField lastTextField;
private javax.swing.JButton nextButton;
private javax.swing.JButton previousButton;
private javax.swing.JPanel recordPanel;
private javax.swing.JTextField salesTextField;
// End of variables declaration
}
This is rather difficult to answer, as I have no understanding of the file format or the Customer class, but basically, you need to create a new Customer from the values you've read from the file, add it to the customer List and call refreshUI
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(filename)));
String first = in.readUTF();
String last = in.readUTF();
double sales = in.readDouble();
Date date = (Date) (in.readObject());
Customer cust = ...;
customer.add(cust);
} catch (FileNotFoundException ex) {
Logger.getLogger(RecordViewerPanel.class.getName()).log(Level.SEVERE, null, ex);
}
refreshUI();

Categories

Resources