I have 3 java files.
DBConn - This Class conencts to the database and execute query.
UserLogin - This jFrame will take username and password and compare with "users" table
if it matches it will display "Login Successfull" in LibSysMain java file
LibSysMain - This is the main file which shows the menu.
This is the jFrame which is displayed first when application is run.
The problem is I am not able to set the "Login Successful" message in LibSysMain.
My Database is MS Access. Table name is "users". Field is "username" and "password". Both of them are of string type.
A help would be highly apprecited.
I am new in Java. I am using NetBeans 6.9.1.
Here is the list:
DBConn:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package LibSystem;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class DBConn {
Connection con;
Statement stmt;
ResultSet rs;
public void DoConnect(String querydb)
{
String SQL;
SQL=querydb;
try
{
// CONNECT TO THE DATABASE
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Database\\libsys\\libsys.mdb";
con = DriverManager.getConnection(url);
System.out.println("\nConnected to the database");
//QUERY THE DATABASE
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
//String SQL ="Select * from Members";
rs=stmt.executeQuery(SQL);
//MOVE CURSOR AT FIRST RECORD AND FETCH DATA
rs.next();
}
catch(ClassNotFoundException e)
{
System.out.println("\nClass not found. Check Path");
e.printStackTrace();
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(null, err.getMessage());
}
}
}
UserLogin:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* UserLogin.java
*
* Created on Apr 23, 2011, 8:46:59 PM
*/
package LibSystem;
import java.sql.*;
import javax.swing.JOptionPane;
import java.lang.*;
/**
*
* #author Administrator
*/
public class UserLogin extends javax.swing.JFrame {
private String user;
private String password;
private String status;
/** Creates new form UserLogin */
public UserLogin() {
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() {
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
btnClose = new javax.swing.JButton();
btnLogin = new javax.swing.JButton();
lbUserName = new javax.swing.JLabel();
lbPassword = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnClose.setText("Close");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
btnLogin.setText("Login");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
lbUserName.setText("User Name");
lbPassword.setText("Password");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbPassword)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbUserName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnClose)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE)
.addComponent(btnLogin))
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE))))
.addGap(35, 35, 35))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(lbUserName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbPassword)
.addGap(5, 5, 5)
.addComponent(txtPassword, 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(btnClose)
.addComponent(btnLogin))
.addContainerGap(39, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//CREATE AN INSTANCE OF DBCONN CLASS TO CONNECT TO THE DATABASE
//WE TAKE THE USERNAME FROM THE LOGIN WINDOW AND SEARCH THE USER
//BASED ON THAT USER. IF FOUND, COMPARE IT WITH THE LOGIN WINDOW.
//IF NOT FOUND DISPLAY ERROR MESSAGE.
DBConn dbc = new DBConn();
String qry = "Select * from users where username=" + "'" + txtUserName.getText() + "'";
dbc.DoConnect(qry);
try
{
setUsername(dbc.rs.getString("username"));
setPassword(dbc.rs.getString("password"));
//TEST PRINTOUT OF USERNAME AND PASSWORD FOR DEBUGGING
System.out.println(getUsername());
System.out.println(getPassword());
if (user.equals(txtUserName.getText()) && password.equals(txtPassword.getText()))
{
JOptionPane.showMessageDialog(UserLogin.this, "Login Successfull");
this.setStatus("pass");
dispose();
}
else
{
JOptionPane.showMessageDialog(UserLogin.this, "Login unsuccessful");
setStatus("fail");
}
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(UserLogin.this, err.getMessage());
}
}
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.dispose();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UserLogin().setVisible(true);
}
});
}
public void setUsername(String u)
{
user = u;
}
public void setPassword(String p)
{
password = p;
}
public String getUsername()
{
return user;
}
public String getPassword()
{
return password;
}
public void setStatus(String stat)
{
status = stat;
}
public String getStatus()
{
return status;
}
// Variables declaration - do not modify
private javax.swing.JButton btnClose;
private javax.swing.JButton btnLogin;
private javax.swing.JLabel lbPassword;
private javax.swing.JLabel lbUserName;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
// End of variables declaration
}
LibSysMain:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* LibsysMain.java
*
* Created on Apr 23, 2011, 6:48:18 PM
*/
package LibSystem;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class LibsysMain extends javax.swing.JFrame {
String q;
/** Creates new form LibsysMain */
public LibsysMain()
{
initComponents();
//DBConn dbc = new DBConn();
//q="Select * from users";
//dbc.DoConnect(q);
}
// LibsysMain frame1 = new LibsysMain();
// UserLogin frame2 = new UserLogin(frame1);
/** 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() {
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jMenuBar1 = new javax.swing.JMenuBar();
miLogin = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 539, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 328, Short.MAX_VALUE)
);
jLabel1.setText("Status");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addContainerGap(518, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
);
jSeparator1.setAlignmentX(0.0F);
jSeparator1.setMinimumSize(new java.awt.Dimension(10, 10));
miLogin.setText("Connect");
miLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miLoginActionPerformed(evt);
}
});
jMenuItem1.setText("Login");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
miLogin.add(jMenuItem1);
jMenuItem2.setText("Exit");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
miLogin.add(jMenuItem2);
jMenuBar1.add(miLogin);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
private void miLoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
UserLogin ul = new UserLogin();
ul.setVisible(true);
//SET THE STATUS IF LOGIN IS SUCCESSFULL
if (ul.getStatus() == "pass")
{
jLabel1.setText("Logged In");
}
else
{
jLabel1.setText("Cannot Log in");
}
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void formWindowActivated(java.awt.event.WindowEvent 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 LibsysMain().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JMenu miLogin;
// End of variables declaration
}
I have a couple of suggestions:
For one, don't compare Strings with == as you do here if (ul.getStatus() == "pass") as this checks to see if two variables refer to the same String object (which you don't care about) but rather use either the equals or the equalsIgnoreCase method which checks to see if the two Strings contain the same String data (which you do care about). e.g., if (ul.getStatus().equalsIgnoreCase("pass"))
Be sure to do all of your database queries and whatnot in a thread background to the GUI's thread, the EDT such as can be achieved by using a SwingWorker object. This article will tell you what I said but will give you the details: Concurrency in Swing.
Consider using a single JFrame and modal dialogs to act as dialog windows to the main app. This can be achieved by using JOptionPanes or modal JDialogs, in particular for your UserLogin window.
For this reason, I like to gear my GUI's towards creating JPanels rather than top level windows such as JFrames. This way I can place my GUI/JPanel into any type of window I desire depending on the situation be it a JFrame, a JApplet, a JDialog, a JOptionPane, or even nested into another JPanel. This gives you an amazing amount of flexibilty.
Related
I just want to ask if I can change the text in radio button.
For example:
here in the picture if I put a number, it will show the number factors at the radio button. ( the factor 1 will just show in Jlabel and the rest of the factor will show at the Radio button) the problem part at the private void checkbtnActionPerformed(java.awt.event.ActionEvent evt) I already tried to use .setText() but I think this will not work for radio button or button group. Is there another way to do that
public class primefactor extends javax.swing.JFrame {
/**
* Creates new form primefactor
*/
public primefactor() {
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() {
numfactorgr = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
checkbtn = new javax.swing.JButton();
cleatbtn = new javax.swing.JButton();
inspectbtn = new javax.swing.JButton();
num1 = new javax.swing.JLabel();
numdis = new javax.swing.JLabel();
numtxt = new javax.swing.JTextField();
primeyn = new javax.swing.JLabel();
numfactors1 = new javax.swing.JRadioButton();
numfactors2 = new javax.swing.JRadioButton();
numfactors3 = new javax.swing.JRadioButton();
numfactors4 = new javax.swing.JRadioButton();
numfactors = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("NUMBER::");
jLabel2.setText("FACTORS::");
jLabel3.setText("PRIME:");
checkbtn.setText("CHECK");
checkbtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkbtnActionPerformed(evt);
}
});
cleatbtn.setText("CLEAR");
cleatbtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cleatbtnActionPerformed(evt);
}
});
inspectbtn.setText("INSPECT");
inspectbtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
inspectbtnActionPerformed(evt);
}
});
numdis.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
numtxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
numtxtActionPerformed(evt);
}
});
numfactorgr.add(numfactors1);
numfactorgr.add(numfactors2);
numfactorgr.add(numfactors3);
numfactorgr.add(numfactors4);
numfactors.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
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()
.addComponent(checkbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 138, Short.MAX_VALUE)
.addComponent(cleatbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(num1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(numdis, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(numfactors, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(inspectbtn))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(primeyn)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numtxt))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(numfactors1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numfactors2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numfactors3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numfactors4)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(numtxt, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(numdis)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(inspectbtn)
.addComponent(num1)
.addComponent(numfactors)))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(primeyn))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 3, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(numfactors1)
.addComponent(numfactors2)
.addComponent(numfactors3)
.addComponent(numfactors4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(checkbtn)
.addComponent(cleatbtn))
.addContainerGap())
);
pack();
}// </editor-fold>
private void numtxtActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void checkbtnActionPerformed(java.awt.event.ActionEvent evt) {
String str = numtxt.getText();
int num = Integer.parseInt(str);
int flag = 0;
numdis.setText(str);
num1.setText("1");
for (int i=2;i<num;i++){
if (num%i ==0){
flag =1;
num1.setText("1");
numfactors.setText( numfactors.getText()+i+" "); // at this part it will display the radio button with the number factors. (but I use first the jlabel numfactors to show the number factors)
}
}
if (flag == 0){
primeyn.setText("Yes");
}
else{
primeyn.setText(primeyn.getText()+"No");
}
}
private void cleatbtnActionPerformed(java.awt.event.ActionEvent evt) {
numtxt.setText("");
num1.setText("");
numdis.setText("");
numfactors.setText("");
primeyn.setText("");
}
private void inspectbtnActionPerformed(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(primefactor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(primefactor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(primefactor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(primefactor.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 primefactor().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton checkbtn;
private javax.swing.JButton cleatbtn;
private javax.swing.JButton inspectbtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel num1;
private javax.swing.JLabel numdis;
private javax.swing.ButtonGroup numfactorgr;
private javax.swing.JLabel numfactors;
private javax.swing.JRadioButton numfactors1;
private javax.swing.JRadioButton numfactors2;
private javax.swing.JRadioButton numfactors3;
private javax.swing.JRadioButton numfactors4;
private javax.swing.JTextField numtxt;
private javax.swing.JLabel primeyn;
// End of variables declaration
}
I am building a product database and when I'm using the update database function my program crashes.
The issue is one string the program itself throws in.
I retrieve the data from the database text file and because I'm using numberformat.getCurrencyInstance and it throws in a dollar sign. So I threw in an exception String price = updatePriceTextField.getText().substring(1); so it would bypass the dollar sign in the beginning of the text field and send the information back to the textfile and save.
Now it brought up my current problem which is: when I enter a number bigger than 999 and I get to thousands, it brings in a comma: example: $3000.00 is now $3,000.00 and when i try to send that information back to the database it throws in an error and crashes.
Now I know I could just simply add in another substring to avoid, and solve the problem like that, but what if the price of the object lets say is: $300000000.00 the the program throws in 2 commas $300,000,000.00 and would crash again. So what sort of exception or command should I throw in to bypass these commas except substring.
Sorry for the long post, but I tried to explain the issue as well as I could.
import java.util.ArrayList;
/**
*
* #author 0103425014
*/
public class EditProduct extends javax.swing.JFrame {
ProductTextFile txtfile = new ProductTextFile();
ArrayList<Product> products = txtfile.getProducts();
/**
* Creates new form UpdateProduct
*/
public EditProduct() {
initComponents();
for (Product p : products)
updateComboBox.addItem(p.getCode() + " " + p.getDescription());
}
/**
* 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() {
updateComboBox = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
updateCodeTextField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
updateDesTextField = new javax.swing.JTextField();
updatePriceTextField = new javax.swing.JTextField();
buttonUpdate = new javax.swing.JButton();
buttonExit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
updateComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateComboBoxActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Select Product to edit:");
jLabel2.setText("Product Code:");
jLabel3.setText("Product Description:");
jLabel4.setText("Product Price:");
buttonUpdate.setText("UPDATE");
buttonUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonUpdateActionPerformed(evt);
}
});
buttonExit.setText("EXIT");
buttonExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonExitActionPerformed(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()
.addGap(76, 76, 76)
.addComponent(buttonUpdate)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonExit)
.addGap(104, 104, 104))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(updateCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(updateDesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(updatePriceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(updateComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jLabel1)))
.addGap(0, 126, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel1)
.addGap(33, 33, 33)
.addComponent(updateComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(updateCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(updateDesTextField, 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(updatePriceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(60, 60, 60)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonUpdate)
.addComponent(buttonExit))
.addContainerGap(73, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void buttonExitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void buttonUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Product p = new Product();
p.setCode(updateCodeTextField.getText());
p.setDescription(updateDesTextField.getText());
String price = updatePriceTextField.getText().substring(1);
p.setPrice(Double.parseDouble(price));
txtfile.updateProduct(p);
UpdatedConfirm confirmed = new UpdatedConfirm();
confirmed.setVisible(true);
this.setVisible(false);
// txtfile.updateProduct();
}
private void updateComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int si = updateComboBox.getSelectedIndex();
Product sp = products.get(si);
updateCodeTextField.setText(sp.getCode());
updateDesTextField.setText(sp.getDescription());
updatePriceTextField.setText(sp.getFormattedPrice());
}
/**
* #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(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EditProduct.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 EditProduct().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonExit;
private javax.swing.JButton buttonUpdate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField updateCodeTextField;
private javax.swing.JComboBox updateComboBox;
private javax.swing.JTextField updateDesTextField;
private javax.swing.JTextField updatePriceTextField;
// End of variables declaration
}
Use a JFormattedTextField instead, this way you just use getValue and it will return you the unformatted value for the field.
See How to Use Formatted Text Fields for more details
a little information on my assignment:
Based on the Person class previously defined, design your own Java application that displays a form for a user to enter their name, year_of_birth and employment status. The provided data will be used to instantiate a Person object. The form should also include a JButton and a JTextField. When the user clicks on the JButton the application should display “Welcome [name]! You are [age] old. Time has been kind to you.”, where [name] and [age] are the current values of the name and age attributes of the Person object.
I am a little new to creating GUI's. I have used the jFrame design that allows me to create the design of the GUI. I am having trouble using that form to display the results. Specifically, having the button display the results, having there name stored in a variable once they type it in, and brining up a dialog box once the button is clicked with the message.
package my.userFormUI;
/**
*
* #author Randy
*/
public class userFormUI extends javax.swing.JFrame {
/**
* Creates new form userFormUI
*/
public userFormUI() {
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")
int age;
int year;
public int getAge(int year_of_birth){//get year method
age = 2014 - year_of_birth;
return age;
}//end method
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jDialog1 = new javax.swing.JDialog();
jDialog2 = new javax.swing.JDialog();
jDialog3 = new javax.swing.JDialog();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
name = new javax.swing.JTextField();
year_of_birth = new javax.swing.JTextField();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jButton1 = new javax.swing.JButton();
javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
jDialog1.getContentPane().setLayout(jDialog1Layout);
jDialog1Layout.setHorizontalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog1Layout.setVerticalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane());
jDialog2.getContentPane().setLayout(jDialog2Layout);
jDialog2Layout.setHorizontalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog2Layout.setVerticalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jDialog3Layout = new javax.swing.GroupLayout(jDialog3.getContentPane());
jDialog3.getContentPane().setLayout(jDialog3Layout);
jDialog3Layout.setHorizontalGroup(
jDialog3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog3Layout.setVerticalGroup(
jDialog3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "User Information", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 12), new java.awt.Color(0, 0, 0))); // NOI18N
jLabel1.setText("NAME:");
jLabel2.setText("YEAR BORN:");
jLabel3.setText("EMPLOYMENT STATUS:");
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
year_of_birth.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
year_of_birthActionPerformed(evt);
}
});
jRadioButton1.setText("Employed");
jRadioButton2.setText("Unemployed");
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)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButton2)
.addComponent(jRadioButton1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(year_of_birth, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(year_of_birth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jRadioButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jButton1.setText("SUBMIT");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(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()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(14, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(104, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
This is where my coding needs to begin.
private void year_of_birthActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int year = Integer.parseInt(year_of_birth.getText());
getAge(year);
}//attempted to convert a string to an integer here
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here
System.out.println("Welcome" + name + " ! You are " + getAge(year) + " old. Time has been kind to you.");
}//Code for button here
private void nameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}//name text field
/**
* #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(userFormUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(userFormUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(userFormUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(userFormUI.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 userFormUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JDialog jDialog1;
private javax.swing.JDialog jDialog2;
private javax.swing.JDialog jDialog3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JTextField name;
private javax.swing.JTextField year_of_birth;
// End of variables declaration
}
Any help would be greatly appreciated. I am already past the due date and very confused on how coding for GUI's go.
There is whole lot of unnecessary code you have. you need to clean it up for example you have 3 dialog instances. you do not need them. coming to your question you need to write implementation like:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// This will display message
JOptionPane.showMessageDialog(this, "Welcome" + name.getText() + " ! You are " + getAge(Integer.parseInt(year_of_berth.getText())) + " old. Time has been kind to you.");
// here you need to write code to populate your Person Object.
}
Hope this helps
You don't need a event for every textField. This:
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
year_of_birth.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
year_of_birthActionPerformed(evt);
}
});
I wipe this fragment of code.
You only need an event when the user click the button, therefore this event what you'll need.
Instead of the methods nameActionPerformed() and year_of_birthActionPerformed(), I would create a getName() and getYearOfBirth() methods.
private String getName(){
return name.getText();
}
private int getYearOfBirth(){
return Integer.parseInt(year_of_birth.getText());
}
Then, in the method of button event:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String name = getName();
int year = getYearOfBirth();
System.out.println("Welcome" + name + " ! You are " + getAge(year) + " old. Time has been kind to you.");
}
I'm using jEditorPane to act kinda as some editor, the one who asked for this of me, also needed a find replace search... so I wanted to let him select in find and then do replace on need.
so I provide this simple code:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
int start = (jEditorPane1.getSelectionStart()>jEditorPane1.getSelectionEnd())?jEditorPane1.getSelectionEnd():jEditorPane1.getSelectionStart();
int max = (start>jEditorPane1.getSelectionStart())?start:jEditorPane1.getSelectionStart();
String searchWord = jTextField3.getText();
int searchIndex = jEditorPane1.getText().indexOf(searchWord, max);
if(searchIndex != -1){
jEditorPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jEditorPane1.setSelectionStart(-1);
jEditorPane1.setSelectionEnd(-1);
}
}
fortunatelly the application return good indexes, but unfortunatelly on view windows I see no selection.
I'm also new to java, please help
PS. buttons action are provided by netbeans itself
THe sample you requested
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* test.java
*
* Created on Jun 12, 2013, 8:23:19 PM
*/
package wordchecker;
/**
*
* #author Hassan
*/
public class test extends javax.swing.JFrame {
/** 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(jTextPane1);
jTextField1.setText("jTextField1");
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(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()
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int startFrom = jTextPane1.getSelectionStart();
if(jTextPane1.getSelectionStart() == jTextPane1.getSelectionEnd()){
startFrom = -1;
}
String searchWord = jTextField1.getText();
int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);
if(searchIndex != -1){
jTextPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jTextPane1.setSelectionStart(0);
jTextPane1.setSelectionEnd(0);
}
}
/**
* #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.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
}
The selection of a text component is only displayed when the text component has focus. When you click on the button it gains focus so you don't see the text selection. You could make the button non-focusable or you can add the following to the bottom of your actionPerformed() method:
jTextPane1.requestFocusInWindow();
Also, don't use the getText() method. This will cause problems with offsets.
int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);
See Text and New Lines for more information and a solution. The basics of this link is to use:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
The above will only return "\n" as the EOL string so the offsets will match when you do a search and then select the text.
Edit:
I generally use code like the following:
int startFrom = jTextPane1.getCaretPosition();
I want to display string in textbox of vpsfame class below my code, but I am unable to dispaly it. Can you give me suggestion this string in new8 class show in code and serial class gives me string from gps continue. It also displays it at run time via System.out.println, but does not display it through the textbox of vpsfame class
package vpspro;
import javax.comm.*;
import java.util.*;
import java.io.*;
public class Serial
{
public void com() throws UnsupportedCommOperationException, IOException, TooManyListenersException
{
int c=1;
String wantedPortName="COM6";
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId = null;
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);
}
port.setSerialPortParams(
4800,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
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;
}
String pt=null;
while(true)
{
String st = is.readLine();
System.out.print("(" + c + ")");
c++;
new8 obj1 = new new8();
obj1.decode(st);
System.out.println(st);
st = st.replace(st, "");
}
if (is != null) is.close();
/*if (os != null) os.close();*/
if (port != null) port.close();
}
}
this code for start communication with serial class
package vpspro;
import java.io.IOException;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.UnsupportedCommOperationException;
public class getcon extends javax.swing.JFrame {
public getcon() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
sc = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
br = new javax.swing.JComboBox();
help = new javax.swing.JButton();
ok = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("select comport");
sc.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM10", "COM11", "COM12" }));
sc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
scActionPerformed(evt);
}
});
sc.addInputMethodListener(new java.awt.event.InputMethodListener() {
public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
}
public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
scInputMethodTextChanged(evt);
}
});
jLabel2.setText("select buad rate");
br.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "4800", "1900", "150000" }));
br.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
brActionPerformed(evt);
}
});
help.setText("help");
ok.setText("ok");
ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okActionPerformed(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, false)
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(sc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(105, 105, 105))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(171, Short.MAX_VALUE)
.addComponent(ok)
.addGap(28, 28, 28)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(help)
.addComponent(br, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(80, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(br, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(57, 57, 57)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(help)
.addComponent(ok))
.addContainerGap(118, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void brActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==br)
br.addItem("4800");
br.addItem("9600");
}
private void scActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==sc)
sc.addItem("COM6");
sc.addItem("COM7");
}
private void scInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==sc)
sc.addItem("COM6");
sc.addItem("COM7");
}
private void okActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==ok)
{
try {
new Serial().com();
} catch (UnsupportedCommOperationException ex) {
Logger.getLogger(getcon.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getcon.class.getName()).log(Level.SEVERE, null, ex);
} catch (TooManyListenersException ex) {
Logger.getLogger(getcon.class.getName()).log(Level.SEVERE, null, ex);
}
new new8();
}
}
public void getcom() {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new getcon().setVisible(true);
}
});
}
private javax.swing.JComboBox br;
private javax.swing.JButton help;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
public javax.swing.JButton ok;
private javax.swing.JComboBox sc;
}
this code decoding my gps string and dispaly and hear problem created i can not dispaly below string in textbox when i rum program textbox are empty.
package vpa.io.*;
import vpspro.vpsfame;
public class new8
{
static String[] a2;
static String a1[];
static String c;
public static String[] t;
public void decode(String st)
{
if(st.isEmpty())
{
System.out.println("System has proble");
vpsfame obj=new vpsfame();
obj.ab.setText("ok");
}
else
{
a1=st.split("\\$",0);
a2=a1[1].split("\\*",0);
checksum();
if(a2[1].equalsIgnoreCase(c))
{
t=st.split(",",0);
switch (t[0].charAt(0))
{
case '$':
String s=t[0].substring(3,6);
String s3="RMC";
if (s.compareTo(s3)==0)
{
System.out.println(" NMEA 0183 Details.....");
System.out.println("System identity: "+t[0].substring(1,3));
System.out.println("NMEA Formate: "+t[0].substring(3,6));
System.out.println("(UTC)Time: "+t[1].substring(1,2));
new vpsfame().ac.setText(t[1].substring(1,2));
System.out.println("Lattitude: "+t[3]);
System.out.println("Direction of Lattitude: "+t[4]);
new vpsfame().ab.setText(t[3].concat(t[4]));
System.out.println("Longitude: "+t[5]);
System.out.println("Direction of Longitude: "+t[6]);
new vpsfame().bc.setText(t[5].concat(t[6]));
System.out.println("Speed over Ground: "+t[7]);
new vpsfame().cd.setText(t[7]);
/*System.out.println("Track mode: "+t[8]);
System.out.println(st.isEmpty());
System.out.println("DATE: "+t[9]);
System.out.println("adjustment declination "+t[10]);
System.out.println("Direction of Magnetic variation: "+t[11].charAt(0));*/
}
}
else
System.out.println(" Invalid Formate...");
break;
default:
System.out.println(" Invalid DATA....");
}
}
else
System.out.println(" no match checksum");
}
}
public static void checksum()
{
int l=a2[0].length();
char[] a=a2[0].toCharArray();
int b=0;
for(int i=0;i<l;i++)
{
b=b^a[i];
}
c=Integer.toHexString(b);
}
}
and this is my main class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* vpsfame.java
*
* Created on Jan 26, 2013, 11:02:32 PM
*/
package vpspro;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Image;
import java.awt.TextField;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.UnsupportedCommOperationException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
/**
*
* #author DHARMA
*/
public class vpsfame extends javax.swing.JFrame {
public vpsfame()
{
initComponents();
}
/** Creates new form vpsfame */
/** 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() {
jComboBox1 = new javax.swing.JComboBox();
ab = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
bc = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
ac = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
cd = new javax.swing.JTextField();
jPanel1 = new javax.swing.JPanel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
gc = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
lm = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
jMenuItem6 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem7 = new javax.swing.JMenuItem();
jMenuItem8 = new javax.swing.JMenuItem();
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
ab.setEditable(false);
ab.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
abActionPerformed(evt);
}
});
jLabel1.setText("latitude");
jLabel2.setText("longitude");
bc.setText(" ");
bc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bcActionPerformed(evt);
}
});
jLabel4.setText("UTC");
ac.setText(" ");
ac.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
acActionPerformed(evt);
}
});
jLabel5.setText("Speed of vessel");
cd.setText(" ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 621, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 368, Short.MAX_VALUE)
);
jMenu1.setText("File");
gc.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
gc.setIcon(new javax.swing.ImageIcon("C:\\Users\\DHARMA\\Desktop\\png\\20x20\\55.png")); // NOI18N
gc.setText("get connection");
gc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
gcActionPerformed(evt);
}
});
jMenu1.add(gc);
jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem2.setText("track");
jMenu1.add(jMenuItem2);
lm.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.ALT_MASK));
lm.setText("load map");
lm.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lmActionPerformed(evt);
}
});
jMenu1.add(lm);
jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem4.setText("data save");
jMenu1.add(jMenuItem4);
jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.META_MASK));
jMenuItem5.setText("set time zone");
jMenu1.add(jMenuItem5);
jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem6.setText("quit");
jMenu1.add(jMenuItem6);
jMenuBar1.add(jMenu1);
jMenu2.setText("view");
jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK));
jMenuItem7.setText("saved data");
jMenu2.add(jMenuItem7);
jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK));
jMenuItem8.setText("about us");
jMenu2.add(jMenuItem8);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(19, 19, 19))
.addGroup(layout.createSequentialGroup()
.addComponent(cd, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))
.addComponent(ab, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
.addComponent(jLabel3)
.addComponent(ac, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
.addComponent(jLabel4)
.addComponent(bc, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ab, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(43, 43, 43)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addGap(16, 16, 16)
.addComponent(bc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(ac, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(cd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
pack();
}// </editor-fold>
private void gcActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==gc)
{
getcon obj3=new getcon();
obj3.setVisible(true);
}
}
private void lmActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void abActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void acActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void bcActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws UnsupportedCommOperationException, IOException, TooManyListenersException {
/*public vpsfame()
{
initComponents();*/
new new8();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
/*URL url=getClass().getResource("C:\\Users\\DHARMA\\Documents\\NetBeansProjects\\vpspro\\src");*/
vpsfame obj4=new vpsfame();
new vpsfame().setBackground(Color.yellow);
obj4.setSize(1000,
500);
ImageIcon image1=new ImageIcon("C:\\Users\\DHARMA\\Documents\\NetBeansProjects\\vpspro\\src");
System.out.println("jjdfhj");
obj4.setIconImage(image1.getImage());
obj4.setTitle("VPS");
obj4.setVisible(true);
new new8();
}
});
}
/*public vpsfame()
{
fm=new JFrame("VPS");
fm.setSize(1000, 1000);
fm.setVisible(true);
fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}*/
// Variables declaration - do not modify
public static javax.swing.JTextField ab;
public javax.swing.JTextField ac;
public static javax.swing.JTextField bc;
public javax.swing.JTextField cd;
private javax.swing.JMenuItem gc;
private javax.swing.JComboBox jComboBox1;
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.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JMenuItem jMenuItem8;
private javax.swing.JPanel jPanel1;
private javax.swing.JMenuItem lm;
// End of variables declaration
}
I would seriously advise you to take a time out, and refactor all of your code. Igonoring that in the class new8, in method decode replace this code:
new vpsfame().ac.setText(t[1].substring(1,2));
System.out.println("Lattitude: "+t[3]);
System.out.println("Direction of Lattitude: "+t[4]);
new vpsfame().ab.setText(t[3].concat(t[4]));
System.out.println("Longitude: "+t[5]);
System.out.println("Direction of Longitude: "+t[6]);
new vpsfame().bc.setText(t[5].concat(t[6]));
System.out.println("Speed over Ground: "+t[7]);
new vpsfame().cd.setText(t[7]);
With this:
//use one object, dont just create new frames
vpsfame myFrame = new vpsfame();
myFrame.ac.setText(t[1].substring(1,2));
System.out.println("Lattitude: "+t[3]);
System.out.println("Direction of Lattitude: "+t[4]);
myFrame.ab.setText(t[3].concat(t[4]));
System.out.println("Longitude: "+t[5]);
System.out.println("Direction of Longitude: "+t[6]);
myFrame.bc.setText(t[5].concat(t[6]));
System.out.println("Speed over Ground: "+t[7]);
myFrame.cd.setText(t[7]);
//Also set the frame to visible, so it can be displayed once you've done all this work.
myFrame.setVisible(true);
The problem is that:
Firstly, you are creating multiple vpsframe objects where you should only have one. It makes no sense to create 5 frames where each will have 4 empty fields. Create one object and initialise all it's fields rather than using 5 diffrent objects.
You are not tracking the objects you are creating, the garbage collector will just get rid of the, so create one object, assign it to a variable and use that.
Set the vpsfame object to visible, otherwise you will never see it.
Your code also needs refactoring, you should be using the camelCase naming convention, and classes should always begin with Capital letters.