i wanted to choose a file from harddisk which contain a matrix.....and i want to save it in an 2d array..but whenever i choose the file,my app hangs and i cant abble to press any other buttons
Here is my sample:
public class Flood extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public static int[][] multi;
public Flood() {
initComponents();
browseB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
JFileChooser fc = new JFileChooser();
switch (fc.showOpenDialog(null)) {
case JFileChooser.APPROVE_OPTION:
File file = fc.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(Flood.class.getName()).log(Level.SEVERE, null, ex);
}
int row = 0;
int col = 0;
while (input.hasNextLine()) {
++row;
Scanner colReader = new Scanner(input.nextLine());
while (colReader.hasNextInt()) {
++col;
}
}
multi = new int[row][col];
input.close();
{
try {
input = new Scanner(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(Flood.class.getName()).log(Level.SEVERE, null, ex);
}
}
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (input.hasNextInt()) {
multi[i][j] = input.nextInt();
}
}
}
break;
}
}
});
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
for(int i=0;i<multi.length;i++)
{
for(int j=0;j<multi[0].length;j++)
{
System.out.println(""+multi[i][j]);
}
}
}
});
}
/**
* 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();
browseTF = new javax.swing.JTextField();
browseB = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
browseB.setText("Browse");
browseB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseBActionPerformed(evt);
}
});
jLabel1.setText("number of 0 :-");
jLabel2.setText("0");
jLabel3.setText("number of 1 :-");
jLabel4.setText("0");
jButton1.setText("go");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(browseTF, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(browseB))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(159, 159, 159)
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(browseTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(browseB))
.addGap(7, 7, 7)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addContainerGap(176, 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()
.addGap(24, 24, 24)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, 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)
.addContainerGap(18, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void browseBActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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(Flood.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Flood.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Flood.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Flood.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 Flood().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton browseB;
private javax.swing.JTextField browseTF;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
Thanks in Advance
You have an infinite loop here:
while (colReader.hasNextInt()) {
++col;
}
You are not advancing the colReader Scanner at all, so it is forever looking at the first int value on the line.
You can fix it by moving past each int value as you encounter it:
while (colReader.hasNextInt()) {
colReader.nextInt();
++col;
}
In the future, you can solve a problem like this on your own by using a debugger to check where your program is stuck, or, if you’re running on the command line, by forcing Java to print a stack trace for each active thread using Ctrl-Break on Windows or Ctrl-\ (SIGQUIT) on Linux and OS X.
Related
eg. I input 1 into combobox and 50 into jTextField1 and the correct answer won't come out. It is going to be code that runs an application to convert chosen temperature ie. celcius, fairenheit or kelvin into the desired choice. For now I'm just trying out with this format of the choices between 1 and 4. I will change it later. Jbutton1 is the button to convert and when clicked should enact all the code within it. but for some reason it does not want to enact on the case that I defined earlier on. It should take the inputted temperature and add 273 to it.
public class Conversion extends javax.swing.JFrame {
int calculation = 0;
String temphold;
double input_temp;
/**
* Creates new form Conversion
*/
public Conversion() {
initComponents();
}
public void cases() {
switch (calculation) {
case 1:
input_temp = input_temp + 273.5;
break;
}
}
/**
* 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();
jComboBox1 = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("jTextField1");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4" }));
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(126, 126, 126)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(207, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(113, 113, 113))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(67, 67, 67))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(50, 50, 50))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
temphold = (String) jComboBox1.getSelectedItem();
String hold = jTextField1.getText();
input_temp = Double.parseDouble(hold);
if (temphold == "1") {
calculation = 1;
System.out.println("monkey");
System.out.println(input_temp);
}
}
/**
* #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(Conversion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Conversion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Conversion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Conversion.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 Conversion().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
I am learning java and i am pretty new for it. I am trying to create a static profile window using swing. Also, the avatar picture should change depending on user and user information should be read from a text file. This code doesnt give a error but its because of avatarPath. I think the program thinks its non-static.
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* #author B_Ali
*/
public class ProfilePanel extends javax.swing.JFrame {
public static String avatarPath;
public static int x;
public static class UsersInfo{
public int userID;
public String userName;
public String userSurname;
public String userGender;
UsersInfo(String name, String surname, String gender){
userID = x;
userName = name;
userSurname = surname;
userGender = gender;
}
}
static UsersInfo permitedUser[];
public static void InfoReader()throws IOException{
#SuppressWarnings("UnusedAssignment")
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader("C:\\Users\\B_Ali\\Documents\\NetBeansProjects\\JavaApplication20\\UserInformation.txt"));
String s, s2 = new String();
while((s = in.readLine())!= null)
s2 += s + "\n";
#SuppressWarnings("UnusedAssignment")
String[] s1 = new String[100];
s1 = s2.split("\\s+");
in.close();
permitedUser[0] = new UsersInfo( s1[0] , s1[1], s1[2] );
permitedUser[1] = new UsersInfo ( s1[3], s1[4], s1[5] );
permitedUser[2] = new UsersInfo ( s1[6], s1[7], s1[8] );
} catch (FileNotFoundException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
public static void ProfilePanel() {
initComponents();
}
public static String AvatarPic(){
if( x == 0 ){
avatarPath = "\"/Users/hei_cosplay_darker_than_black_by_seras0victoria.jpg\"";
}
else if( x == 1 ){
avatarPath = "\"/Users/lyralei_the_windrunner_by_trungth-d5zhmc1.jpg\"";
}
else if( x == 2 ){
avatarPath = "\"/Users/shingeki_no_kyojin_by_asuka10-d6k762k.jpg\"";
}
return avatarPath;}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jFrame2 = new javax.swing.JFrame();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
jFrame2.getContentPane().setLayout(jFrame2Layout);
jFrame2Layout.setHorizontalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame2Layout.setVerticalGroup(
jFrame2Layout.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, "Avatar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(ProfilePanel.AvatarPic())));
jLabel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 2, true));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jScrollPane2.setName(""); // NOI18N
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
try {
ProfilePanel.InfoReader(); // TODO add your handling code here:
} catch (IOException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
}
jTextArea1.setText("Name: " +permitedUser[x].userName+ "\r\nSurname :"+permitedUser[x].userSurname+"\r\nGender :"+permitedUser[x].userGender);
jTextArea1.setDragEnabled(true);
jTextArea1.setMaximumSize(new java.awt.Dimension(2147483647, 120));
jTextArea1.setMinimumSize(new java.awt.Dimension(92, 120));
jTextArea1.setPreferredSize(new java.awt.Dimension(164, 120));
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
);
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(50, 50, 50)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(120, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
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
*/
Scanner in = new Scanner(System.in);
x = in.nextInt();
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(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.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 ProfilePanel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JFrame jFrame1;
private javax.swing.JFrame jFrame2;
public javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
public javax.swing.JScrollPane jScrollPane2;
public javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
Edit: I changed code a bit and it gives error.
Edit2: what I am trying to do is creating users and their profiles. Profile will contain avatar image and 3 variable which are name, surname and gender. I want to display them with respect to users.
I am living problems with this codes;
static void AvatarPic(){
if( x == 0 ){
avatarPath = "\"/Users/hei_cosplay_darker_than_black_by_seras0victoria.jpg\"";
}
else if( x == 1 ){
avatarPath = "\"/Users/lyralei_the_windrunner_by_trungth-d5zhmc1.jpg\"";
}
else if( x == 2 ){
avatarPath = "\"/Users/shingeki_no_kyojin_by_asuka10-d6k762k.jpg\"";
}
}
and
ProfilePanel.AvatarPic();
jLabel1.setIcon(new
javax.swing.ImageIcon(getClass().getResource(ProfilePanel.avatarPath)));
There are many problems in your code.
The initComponents() is not a static function .I guess in your static conversion you just replaced every function with public static .And the below is a constructor [I'm sure because it is a Netbeans generated one] and you have modified it also.No need to do that
public static void ProfilePanel() {
initComponents();
}
You can change it back to the way it was
public ProfilePanel() {
initComponents();
}
You'll get a java.lang.NullPointerException at
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(ProfilePanel.AvatarPic())));
because if you are using getResource you just have to specify the filename relative to the package.If you'll be loading from other location,then you have to change it like
jLabel1.setIcon(new javax.swing.ImageIcon(ProfilePanel.AvatarPic()));//file location
Also you have to give the absolute path
avatarPath = "D://hei_cosplay_darker_than_black_by_seras0victoria.jpg";
You'll again get a java.lang.NullPointerException at
permitedUser[0] = new UsersInfo(s1[0], s1[1], s1[2]);
because you haven't initialized the permitedUser anywhere.So you have to do it like
static UsersInfo permitedUser[]=new UsersInfo[3];
After making those changes and if you run it with 0 then BK201[Code Name Hei] will be on your screen
And Your Edited FullCode[Make change to ImageLocations]
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author B_Ali
*/
public class ProfilePanel extends javax.swing.JFrame {
public static String avatarPath;
public static int x;
public static class UsersInfo {
public int userID;
public String userName;
public String userSurname;
public String userGender;
UsersInfo(String name, String surname, String gender) {
userID = x;
userName = name;
userSurname = surname;
userGender = gender;
}
}
static UsersInfo permitedUser[] = new UsersInfo[3];//change 3
public static void InfoReader() throws IOException {
#SuppressWarnings("UnusedAssignment")
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader("C:\\Users\\B_Ali\\Documents\\NetBeansProjects\\JavaApplication20\\UserInformation.txt"));
String s, s2 = new String();
while ((s = in.readLine()) != null) {
s2 += s + "\n";
}
#SuppressWarnings("UnusedAssignment")
String[] s1 = new String[100];
s1 = s2.split("\\s+");
in.close();
permitedUser[0] = new UsersInfo(s1[0], s1[1], s1[2]);
permitedUser[1] = new UsersInfo(s1[3], s1[4], s1[5]);
permitedUser[2] = new UsersInfo(s1[6], s1[7], s1[8]);
} catch (FileNotFoundException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
//Change 1
public ProfilePanel() {
initComponents();
}
public static String AvatarPic() {
//change 2
if (x == 0) {
avatarPath = "D://hei_cosplay_darker_than_black_by_seras0victoria.jpg";
} else if (x == 1) {
avatarPath = "D://lyralei_the_windrunner_by_trungth-d5zhmc1.jpg";
} else if (x == 2) {
avatarPath = "D://shingeki_no_kyojin_by_asuka10-d6k762k.jpg";
}
return avatarPath;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jFrame2 = new javax.swing.JFrame();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
jFrame2.getContentPane().setLayout(jFrame2Layout);
jFrame2Layout.setHorizontalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame2Layout.setVerticalGroup(
jFrame2Layout.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, "Avatar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
//Change 2
jLabel1.setIcon(new javax.swing.ImageIcon(ProfilePanel.AvatarPic()));
jLabel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 2, true));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jScrollPane2.setName(""); // NOI18N
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
try {
ProfilePanel.InfoReader(); // TODO add your handling code here:
} catch (IOException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
}
jTextArea1.setText("Name: " + permitedUser[x].userName + "\r\nSurname :" + permitedUser[x].userSurname + "\r\nGender :" + permitedUser[x].userGender);
jTextArea1.setDragEnabled(true);
jTextArea1.setMaximumSize(new java.awt.Dimension(2147483647, 120));
jTextArea1.setMinimumSize(new java.awt.Dimension(92, 120));
jTextArea1.setPreferredSize(new java.awt.Dimension(164, 120));
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
);
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(50, 50, 50)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(120, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
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
*/
Scanner in = new Scanner(System.in);
x = in.nextInt();
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(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.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 ProfilePanel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JFrame jFrame1;
private javax.swing.JFrame jFrame2;
public javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
public javax.swing.JScrollPane jScrollPane2;
public javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
I want this code work with update JProgressBar and JTextArea while scanner is working, but I don't know how implement Threading. Is it possible?
This is my code:
UPDATED: It's a working version now, with "Stop" function. I added a "breakPoint" variable to break out from the for loop.
package main;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
public class PortScanner extends javax.swing.JFrame {
private doSomeStuff taskPortScanner;
private boolean breakPoint;
public PortScanner() {
initComponents();
}
private void portScan() {
int currentPort = 1;
try {
String hostname = hostNameTextField.getText();
int timeOut = (Integer) timeOutSpinner.getValue();
int minPort = Integer.parseInt(portMinTextField.getText());
int maxPort = Integer.parseInt(portMaxTextField.getText());
//set min and max value of progress bar
jProgressBar1.setMinimum(minPort);
jProgressBar1.setMaximum(maxPort);
//print out the address
InetAddress theAddress = InetAddress.getByName(hostname);
resultTextArea.append("IP adress: " + theAddress + "\n\n");
//check if port is open
for (currentPort = minPort; currentPort <= maxPort; currentPort++) {
//stop for loop
if (breakPoint == true) {
System.out.println("Portscanning stopped.");
break;
}
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(hostname, currentPort), timeOut);
//update textarea
resultTextArea.append("Service running on port " + currentPort + "\n");
socket.close();
} catch (Exception ex) {
System.out.println(currentPort);
}
//update progressbar
jProgressBar1.setValue(currentPort);
jProgressBar1.repaint();
}
} catch (UnknownHostException ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Unknown hostname: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Invalid format. " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
private class doSomeStuff extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() throws Exception {
portScan();
return null;
}
#Override
public void done() {
//if thread is done enable start and clear buttons
clearButton.setEnabled(true);
startButton.setEnabled(true);
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
hostNameTextField = new javax.swing.JTextField();
portMinTextField = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
resultTextArea = new javax.swing.JTextArea();
startButton = new javax.swing.JButton();
clearButton = new javax.swing.JButton();
portMaxTextField = new javax.swing.JTextField();
jProgressBar1 = new javax.swing.JProgressBar();
timeOutSpinner = new javax.swing.JSpinner();
jLabel4 = new javax.swing.JLabel();
stopButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Simple port scanner");
setResizable(false);
jLabel1.setText("Hostname");
jLabel2.setText("Timeout");
jLabel3.setText("Port range");
hostNameTextField.setToolTipText("Type a hostname like www.google.com");
portMinTextField.setText("1");
resultTextArea.setColumns(20);
resultTextArea.setRows(5);
jScrollPane1.setViewportView(resultTextArea);
startButton.setText("Scan");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
clearButton.setText("Clear");
clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearButtonActionPerformed(evt);
}
});
portMaxTextField.setText("1000");
jProgressBar1.setStringPainted(true);
timeOutSpinner.setModel(new javax.swing.SpinnerNumberModel(15, 0, 999999, 1));
jLabel4.setText("-");
stopButton.setText("Stop");
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(hostNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(timeOutSpinner)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(portMinTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addGap(12, 12, 12)
.addComponent(portMaxTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(startButton)
.addGap(18, 18, 18)
.addComponent(stopButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
.addComponent(clearButton)
.addGap(32, 32, 32))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(hostNameTextField, 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(jLabel2)
.addComponent(timeOutSpinner, 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(jLabel3)
.addComponent(portMinTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(portMaxTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startButton)
.addComponent(clearButton)
.addComponent(stopButton))
.addContainerGap())
);
pack();
}// </editor-fold>
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
breakPoint = false;
taskPortScanner = new doSomeStuff();
taskPortScanner.execute();
startButton.setEnabled(false);
clearButton.setEnabled(false);
System.out.println("Starting portscanner...");
}
private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
resultTextArea.setText(null);
jProgressBar1.setValue(0);
System.out.println("Clearing results...");
}
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
breakPoint = true;
startButton.setEnabled(true);
clearButton.setEnabled(true);
}
/**
* #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(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PortScanner.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 PortScanner().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton clearButton;
private javax.swing.JTextField hostNameTextField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField portMaxTextField;
private javax.swing.JTextField portMinTextField;
private javax.swing.JTextArea resultTextArea;
private javax.swing.JButton startButton;
private javax.swing.JButton stopButton;
private javax.swing.JSpinner timeOutSpinner;
// End of variables declaration
}
You need to look at moving the long running scan task out of the Event dispatching thread to keep the UI responsive. Look at using a Swing Worker to achieve this.
http://en.wikipedia.org/wiki/SwingWorker#The_event_dispatching_thread_problem
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
I am doing a project where I have to convert a fraction into its lowest terms. I am experiencing errors with .getText from a JTextField. I printed their input and the input is being received as the properties rather than as a string. I am having problems with this code:
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
this give the variable a value of
javax.swing.JTextField[,12,93,166x36,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#c112a58,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]
I was wondering if any problems could be caused by me using a GUI form or a key released listener.
Here is the full code separated into two classes:
package reducefraction;
public class ReduceFraction {
public static void main(String[] args) {
NewJFrame form = new NewJFrame();
form.setVisible(true);
form.setLocationRelativeTo(null);
}
}
Here is the second class
package reducefraction;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
userDenominatorInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
userDenominatorInputKeyReleased(evt);
}
});
userNumeratorInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
userNumeratorInputKeyReleased(evt);
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
userDenominatorInput = new javax.swing.JTextField();
jSeparator2 = new javax.swing.JSeparator();
numeratorOutput = new javax.swing.JTextField();
denominatorOutput = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
userNumeratorInput = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Reduce Fractions");
jLabel2.setText("This program will reduce a fraction to its lowest terms");
userDenominatorInput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
userDenominatorInput.setForeground(new java.awt.Color(255, 102, 51));
numeratorOutput.setEditable(false);
numeratorOutput.setColumns(10);
numeratorOutput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
numeratorOutput.setForeground(new java.awt.Color(255, 102, 51));
denominatorOutput.setEditable(false);
denominatorOutput.setColumns(10);
denominatorOutput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
denominatorOutput.setForeground(new java.awt.Color(255, 102, 51));
jLabel3.setFont(new java.awt.Font("Tempus Sans ITC", 1, 36)); // NOI18N
jLabel3.setText("=");
userNumeratorInput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
userNumeratorInput.setForeground(new java.awt.Color(255, 102, 51));
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(155, 155, 155)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jLabel2)))
.addGap(0, 82, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator1)
.addComponent(userDenominatorInput, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
.addComponent(userNumeratorInput))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator2)
.addComponent(denominatorOutput, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(numeratorOutput, javax.swing.GroupLayout.Alignment.TRAILING, 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(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(userNumeratorInput, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(userDenominatorInput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(denominatorOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(numeratorOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)))
.addGap(22, 22, 22))
);
pack();
}// </editor-fold>
**public void userDenominatorInputKeyReleased(java.awt.event.KeyEvent evt) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
public void userNumeratorInputKeyReleased(java.awt.event.KeyEvent evt) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
public void calculate(double userNumerator, double userDenominator) {
System.out.println(userNumeratorInput);
double a = userDenominator;
double b = userNumerator % userDenominator;
double c;
do {
c = a % b;
a = b;
b = c;
} while (a != 0);
int greatestCommonDenominator = (int) c;
double numeratorAnswer = userNumerator / greatestCommonDenominator;
double denominatorAnswer = userDenominator / greatestCommonDenominator;
numeratorOutput.setText(Double.toString(numeratorAnswer));
denominatorOutput.setText(Double.toString(denominatorAnswer));
}**
/**
* #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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField denominatorOutput;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTextField numeratorOutput;
public javax.swing.JTextField userDenominatorInput;
private javax.swing.JTextField userNumeratorInput;
// End of variables declaration
}
The "probable" cause is the use of KeyListener on the text fields.
The main problem is you are not taking into account what should occur if one of the fields is empty, "" is not a valid number.
Don't use KeyListeners on text fields, if you want to perform real time updates on fields, you should be using a DocumentListener instead. KeyListener won't be notified if the the user pastes content into the field...
You should also consider using a JSpinner or a JFormattedField or even a DocumentFilter to restrict what the user can actually type into the fields
Something like...
if (!userDenominatorInput.getText().isEmpty() && !userNumeratorInput.getText().isEmpty()) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
Should help...
MadProgrammer gave me the answer I needed that was causing the output of properties rather than a string. This Problem is solved by doing the .getText method as described here:
Don't use System.out.println(userNumeratorInput), it's calling userNumeratorInput.toString()which prints the properties of the text field, use ystem.out.println(userNumeratorInput.getText()) to print the text content of the field – MadProgrammer
Here is the correct code from my form class
package reducefraction;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class NewJFrame extends javax.swing.JFrame {
double userDenominator, userNumerator;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
// userDenominatorInput.addActionListener(new MyTextActionListener());
userDenominatorInput.getDocument().addDocumentListener(new MyDocumentListener());
userDenominatorInput.getDocument().putProperty("name", "Text Field");
/* userDenominatorInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
userDenominatorInputKeyReleased(evt);
}
});
*/
// userNumeratorInput.addActionListener(new MyTextActionListener());
userNumeratorInput.getDocument().addDocumentListener(new MyDocumentListener());
userNumeratorInput.getDocument().putProperty("name", "Text Field");
/*
userNumeratorInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
userNumeratorInputKeyReleased(evt);
}
});
*/
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
userDenominatorInput = new javax.swing.JTextField();
jSeparator2 = new javax.swing.JSeparator();
numeratorOutput = new javax.swing.JTextField();
denominatorOutput = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
userNumeratorInput = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Reduce Fractions");
jLabel2.setText("This program will reduce a fraction to its lowest terms");
userDenominatorInput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
userDenominatorInput.setForeground(new java.awt.Color(255, 102, 51));
numeratorOutput.setEditable(false);
numeratorOutput.setColumns(10);
numeratorOutput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
numeratorOutput.setForeground(new java.awt.Color(255, 102, 51));
denominatorOutput.setEditable(false);
denominatorOutput.setColumns(10);
denominatorOutput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
denominatorOutput.setForeground(new java.awt.Color(255, 102, 51));
jLabel3.setFont(new java.awt.Font("Tempus Sans ITC", 1, 36)); // NOI18N
jLabel3.setText("=");
userNumeratorInput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
userNumeratorInput.setForeground(new java.awt.Color(255, 102, 51));
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(155, 155, 155)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jLabel2)))
.addGap(0, 82, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator1)
.addComponent(userDenominatorInput, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
.addComponent(userNumeratorInput))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator2)
.addComponent(denominatorOutput, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(numeratorOutput, javax.swing.GroupLayout.Alignment.TRAILING, 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(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(userNumeratorInput, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(userDenominatorInput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(denominatorOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(numeratorOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)))
.addGap(22, 22, 22))
);
pack();
}// </editor-fold>
/* public void userDenominatorInputKeyReleased(java.awt.event.KeyEvent evt) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
*/
/* public void userNumeratorInputKeyReleased(java.awt.event.KeyEvent evt) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
*/
public void update() {
if (!userDenominatorInput.getText().isEmpty() && !userNumeratorInput.getText().isEmpty()) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
}
public void calculate(double userNumerator, double userDenominator) {
if (Double.toString(userNumerator).contains(".")) {
int decimalLocationuserNumerator = Double.toString(userNumerator).lastIndexOf(".");
String decimalsuserNumerator = Double.toString(userNumerator).substring(decimalLocationuserNumerator + 1, Double.toString(userNumerator).length());
int magnitudeUserNumerator = decimalsuserNumerator.length();
userNumerator = userNumerator * Math.pow(10, magnitudeUserNumerator);
userDenominator = userDenominator * Math.pow(10, magnitudeUserNumerator);
}
if (Double.toString(userDenominator).contains(".")) {
int decimalLocationUserDenominator = Double.toString(userDenominator).lastIndexOf(".");
String decimalsUserDenominator = Double.toString(userDenominator).substring(decimalLocationUserDenominator + 1, Double.toString(userDenominator).length());
int magnitudeUserDenominator = decimalsUserDenominator.length();
userDenominator = userDenominator * Math.pow(10, magnitudeUserDenominator);
userNumerator = userNumerator * Math.pow(10, magnitudeUserDenominator);
}
double a = userNumerator;
double b = userDenominator;
double c = a % b;
while (c > 1) {
c = a % b;
a = b;
b = c;
}
int greatestCommonDenominator = (int) a;
int numeratorAnswer = (int) userNumerator / greatestCommonDenominator;
int denominatorAnswer = (int) userDenominator / greatestCommonDenominator;
numeratorOutput.setText(Integer.toString(numeratorAnswer));
denominatorOutput.setText(Integer.toString(denominatorAnswer));
}
/**
* #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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField denominatorOutput;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTextField numeratorOutput;
public javax.swing.JTextField userDenominatorInput;
private javax.swing.JTextField userNumeratorInput;
// End of variables declaration
private class MyDocumentListener implements DocumentListener {
public MyDocumentListener() {
}
#Override
public void insertUpdate(DocumentEvent de) {
update();
}
#Override
public void removeUpdate(DocumentEvent de) {
update();
}
#Override
public void changedUpdate(DocumentEvent de) {
update();
}
}
}
In the following code I don't know how to find the average using the Calculate Button. I have managed to read the text in through Text fields for the values but i don't know how to make the program calculate the average and print it in the textfield once the Calculate Button has been clicked.
import java.util.Scanner;
public class KdrCalGui extends javax.swing.JFrame {
/**
* Creates new form KdrCalGui
*/
public KdrCalGui() {
initComponents();
double kills;
double deaths;
double subtotal;
double roundnumber;
}
/**
* 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() {
KillsValue = new javax.swing.JTextField();
KillsLabel = new javax.swing.JLabel();
DeathsValue = new javax.swing.JLabel();
DeathsLabel = new javax.swing.JTextField();
CalculateButton = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
Display = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
KillsValue.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
KillsValueActionPerformed(evt);
}
});
KillsLabel.setText("Kills");
DeathsValue.setText("Deaths");
DeathsLabel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DeathsLabelActionPerformed(evt);
}
});
CalculateButton.setText("Calculate");
CalculateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CalculateButtonActionPerformed(evt);
}
});
jLabel3.setText("Your KDR");
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(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(CalculateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DeathsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DeathsValue)
.addComponent(KillsValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KillsLabel))
.addGap(113, 113, 113)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(Display, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addContainerGap(31, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {DeathsLabel, KillsValue});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(KillsLabel)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(KillsValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(DeathsValue)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DeathsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Display)))
.addGap(36, 36, 36)
.addComponent(CalculateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(50, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void DeathsLabelActionPerformed(java.awt.event.ActionEvent evt) {
DeathsLabel.setText(DeathsLabel.getText());
double deaths;
Scanner sc= new Scanner(System.in);
deaths=sc.nextInt();
}
private void KillsValueActionPerformed(java.awt.event.ActionEvent evt) {
KillsLabel.setText(KillsLabel.getText());
double kills;
Scanner sc=new Scanner(System.in);
kills=sc.nextInt();
}
THIS IS THE CALCULATE BUTTON.
private void CalculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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(KdrCalGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(KdrCalGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(KdrCalGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(KdrCalGui.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 KdrCalGui().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton CalculateButton;
private javax.swing.JTextField DeathsLabel;
private javax.swing.JLabel DeathsValue;
private javax.swing.JTextField Display;
private javax.swing.JLabel KillsLabel;
private javax.swing.JTextField KillsValue;
private javax.swing.JLabel jLabel3;
// End of variables declaration
}
CalculateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == CalculateButton) {
// not sure what exactly you're trying to average
// but if it's the kills and deaths value, then...
int k = Integer.parseInt(KillsValue.getText());
int d = Integer.parseInt(DeathsValue.getText());
Display.setText((k+d)/2);
// think about adding exception handling in case they enter a noninteger
// also you switched the names of the TextField and Label in the initComponents()
}
}
});