I'm not sure what the problem with this code is but whenever I run it I get a java.lang.StackOverflowError. How would I fix it? This is what is displayed in the output console of netbeans:
run:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222) at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222)
at java.awt.Window.init(Window.java:497)
at java.awt.Window.<init>(Window.java:536)
at java.awt.Frame.<init>(Frame.java:420)
at java.awt.Frame.<init>(Frame.java:385)
at javax.swing.JFrame.<init>(JFrame.java:180)
code
import java.awt.Color;
import java.awt.Font;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Nicholas Ferretti
*/
public class Section2 extends javax.swing.JFrame {
Section2 s2Frame = new Section2();
Section3 s3Frame = new Section3();
ResultSet section2Questions;
DB connection = new DB();
/**
* Creates new form Section2Question1
*/
TimerFrame timerFrame;
int timeRemaining = 60;
int s2QuestionNumber = 1;
public Section2() {
this.timerFrame = new TimerFrame(this);
initComponents();
groupButton();
section2QuestionBox.setEditable(false);
s2QuestionNumberLabel.setText("Question "+s2QuestionNumber+":");
try {
section2Questions=connection.queryTbl("SELECT * FROM tblQuestions WHERE Section = 2");
section2Questions.next();
String firstQuestion = section2Questions.getString("Questions");
System.out.println(firstQuestion);
section2QuestionBox.setText(firstQuestion);
String firstAnswers = section2Questions.getString("AllPossibleAnswers");
Scanner scLine = new Scanner(firstAnswers).useDelimiter(",");
while(scLine.hasNext()){
String answer1 = scLine.next();
S2Answer1.setText(answer1);
System.out.println(answer1);
String answer2 = scLine.next();
S2Answer2.setText(answer2);
System.out.println(answer2);
String answer3 = scLine.next();
S2Answer3.setText(answer3);
System.out.println(answer3);
String answer4 = scLine.next();
S2Answer4.setText(answer4);
System.out.println(answer4);
}
} catch (SQLException ex) {
Logger.getLogger(Section1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error with SQL firstQuestion");
}
/*boolean t = timerFrame.timer(Section2Timer, timeRemaining);
if(t == false){
JOptionPane.showMessageDialog(null, "Time up for section.");
s2Frame.setVisible(false);
//s3Frame.setVisible(true);
}*/
}
private void groupButton() {
ButtonGroup buttons = new ButtonGroup();
buttons.add(S2Answer2);
buttons.add(S2Answer3);
buttons.add(S2Answer1);
buttons.add(S2Answer4);
}
private void timer() {
try {
Score time = new Score();
int timeRemaining = time.getTime();
while(timeRemaining>0){
Section2Timer.setText(timeRemaining+"");
Section2Timer.setFont(new Font("Serif", Font.BOLD, 32));
Section2Timer.setForeground(Color.RED);
Thread.sleep(1000);
timeRemaining--;
if(timeRemaining==0){
time.setTime(60);
}
time.setTime(timeRemaining);
}
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
}
/**
* 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() {
jLabel7 = new javax.swing.JLabel();
s2QuestionNumberLabel = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
section2QuestionBox = new javax.swing.JTextArea();
S2Answer1 = new javax.swing.JRadioButton();
S2Answer2 = new javax.swing.JRadioButton();
S2Answer3 = new javax.swing.JRadioButton();
S2Answer4 = new javax.swing.JRadioButton();
nextS2Question = new javax.swing.JButton();
Section2Timer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel7.setText("SECTION 2:");
s2QuestionNumberLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
s2QuestionNumberLabel.setText("QUESTION 1:");
jLabel9.setText("Answers:");
section2QuestionBox.setColumns(20);
section2QuestionBox.setRows(5);
section2QuestionBox.setText("At a conference, 12 memeber shook hands with each other \nbefore & after the meeting. How many total number of\nhand shakes occurred?");
jScrollPane3.setViewportView(section2QuestionBox);
S2Answer1.setText("Monday");
S2Answer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer1ActionPerformed(evt);
}
});
S2Answer2.setText("Tuesday");
S2Answer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer2ActionPerformed(evt);
}
});
S2Answer3.setText("Wednesday");
S2Answer3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer3ActionPerformed(evt);
}
});
S2Answer4.setText("Friday");
S2Answer4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer4ActionPerformed(evt);
}
});
nextS2Question.setText("Next");
nextS2Question.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextS2QuestionActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(125, 125, 125)
.addComponent(s2QuestionNumberLabel)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(217, 217, 217)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(S2Answer1)
.addGap(53, 53, 53)
.addComponent(S2Answer2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addComponent(S2Answer3)
.addGap(45, 45, 45)
.addComponent(S2Answer4))
.addComponent(nextS2Question, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(139, 139, 139)
.addComponent(Section2Timer, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Section2Timer, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addComponent(s2QuestionNumberLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(S2Answer1)
.addComponent(S2Answer2)
.addComponent(S2Answer3)
.addComponent(S2Answer4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 140, Short.MAX_VALUE)
.addComponent(nextS2Question)
.addGap(125, 125, 125))
);
pack();
}// </editor-fold>
String answer = "";
private void S2Answer1ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer1.getText();
}
private void S2Answer2ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer2.getText();
}
private void S2Answer3ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer3.getText();
}
private void S2Answer4ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer4.getText();
}
private void nextS2QuestionActionPerformed(java.awt.event.ActionEvent evt) {
Score score = new Score();
try {
String actualAnswer = section2Questions.getString("Answer");
int currentScore = score.getS2Score();
if(answer.equalsIgnoreCase(actualAnswer)){
currentScore+=5;
score.setS2Score(currentScore);
}
} catch (SQLException ex) {
Logger.getLogger(Section1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error in Next Question method");
}
if(s2QuestionNumber ==4){
int timeLeft = score.getTime();
int currentBonusPoints = score.getBonusPoints();
score.setBonusPoints(timeLeft+currentBonusPoints);
s2Frame.setVisible(false);
s3Frame.setVisible(true);
}
try {
section2Questions.next();
String nextQuestion = section2Questions.getString("Questions");
section2QuestionBox.setText(nextQuestion);
s2QuestionNumber++;
s2QuestionNumberLabel.setText("Question "+s2QuestionNumber+":");
} catch (SQLException ex) {
Logger.getLogger(Section1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error in Next Question method");
}
}
/**
* #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(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Section2().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JRadioButton S2Answer1;
private javax.swing.JRadioButton S2Answer2;
private javax.swing.JRadioButton S2Answer3;
private javax.swing.JRadioButton S2Answer4;
private javax.swing.JLabel Section2Timer;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton nextS2Question;
private javax.swing.JLabel s2QuestionNumberLabel;
private javax.swing.JTextArea section2QuestionBox;
// End of variables declaration
}
The very first line in your class Section2 would cause the problem.
You have, Section2 s2Frame = new Section2();, which means, every time an object is created for Section2 you want to create another object of Section2 (which will create another object... and sooooooooo on...)
Hence the stackoverflow exception...
Related
I trying to read file in java. When click next button, how can I show second question when next button is clicked?
My .txt file content is like this
1. What is his name
A.John
B.David
2. How old is him?
A.24
B.27
So far I am able to display the first question in JTextField.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.FileReader;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() throws IOException {
initComponents();
setLocationRelativeTo(null);
pack();
File file = new File("/home/xxx/Desktop/englishQuestion.txt");
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
if (line.equals("")) {
break;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
String result = sb.toString();
jTextArea1.setText(result);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
textField1 = new java.awt.TextField();
label1 = new java.awt.Label();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Next");
textField1.setName("\"\""); // NOI18N
textField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textField1ActionPerformed(evt);
}
});
label1.setText("Answer:");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap())
);
label1.getAccessibleContext().setAccessibleName("Answer: ");
pack();
}// </editor-fold>
private void textField1ActionPerformed(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(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() {
try {
new NewJFrame().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private java.awt.Label label1;
private java.awt.TextField textField1;
// End of variables declaration
}
I refactored the file lines to be like this:
q1 = What is his name? | John | David
q2 = How old is him? | 24 | 27
This way, each question information is in a single line and is easier to parse. You just have to load it as a property file and the q1 and q2 would be the keys, and what is after = would be the values. After that, split it by | or whatever you decide to use.
I refactored your code to look like this:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewJFrame extends javax.swing.JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private Properties props = new Properties();
private List<Question> questionList = new ArrayList<>();
private int currentQuestionIndex = -1;
private class Question {
private String question;
private String answer1;
private String answer2;
#Override
public String toString() {
return "Question [question=" + question + ", answer1=" + answer1 + ", answer2=" + answer2 + "]";
}
public Question(String question, String answer1, String answer2) {
this.question = question;
this.answer1 = answer1;
this.answer2 = answer2;
}
public String getQuestion() {
return question;
}
public String getAnswer1() {
return answer1;
}
public String getAnswer2() {
return answer2;
}
}
public void showNextQuestion() {
currentQuestionIndex++;
if (currentQuestionIndex >= questionList.size()) {
jTextArea1.setText("No more questions available.");
return;
}
jTextArea1.setText("");
Question currentQuestion = questionList.get(currentQuestionIndex);
String newLine = "\n";
jTextArea1.append(currentQuestion.getQuestion() + newLine);
jTextArea1.append("A. " + currentQuestion.getAnswer1() + newLine);
jTextArea1.append("B. " + currentQuestion.getAnswer2());
}
public NewJFrame() throws IOException {
initComponents();
setLocationRelativeTo(null);
pack();
Path path = Paths.get("/home/xxx/Desktop/englishQuestion.txt");
props.load(Files.newInputStream(path));
props.forEach((key, value) -> {
String v = (String) value;
System.out.println(v);
String[] token = v.split("\\|");
String question = token[0];
String answer1 = token[1];
String answer2 = token[2];
Question q = new Question(question, answer1, answer2);
questionList.add(q);
});
showNextQuestion();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
textField1 = new java.awt.TextField();
label1 = new java.awt.Label();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Next");
jButton1.addActionListener(e -> {
showNextQuestion();
});
textField1.setName("\"\""); // NOI18N
textField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textField1ActionPerformed(evt);
}
});
label1.setText("Answer:");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 53,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 421,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap()));
label1.getAccessibleContext().setAccessibleName("Answer: ");
pack();
}// </editor-fold>
private void textField1ActionPerformed(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(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() {
try {
new NewJFrame().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private java.awt.Label label1;
private java.awt.TextField textField1;
// End of variables declaration
}
Notice that I used a Properties object to load all the keys, and then for each of those lines, I parsed it and created a Question object and add it to a questionList. Also, notice the jButton1.addActionListener(e -> { showNextQuestion(); });. Call showNextQuestion(); method everytime you want the next question, in this case, every time to click the Next button.
I'm not sure what you want to acomplish with this application, is not clear yet, but I simply answered your question on how to show the next question.
First of all, your questions in the file should be in uniform format, I mean we should be able to distinguish between different question and it's options.
Secondly, then you read each question and it's options and store it in an Java Object. Let's say Question object.
Question object might be something like below:-
class Question {
String questionString;
String[] options;
}
Then, after you read each question/options and form an Object, you store these objects in a DoublyLinkedList, so you can easily navigate back and forth when user clicks Previous button or Next button.
I Am having trouble saving the state of a Form application and loading its state. I created a simple Swing Application in Java using netbeans. The purpose of the program is a spit out a unique 4 digit number and had a note if necessary. The trouble came up with I tried to serialize the data so that when the application was opened again I would be able to load the data from where I left off.
Here is the code for the Swing Portion:
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Map;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author marcsantiago
*/
public class MainForm extends javax.swing.JFrame {
/**
* Creates new form MainForm
*/
public MainForm() {
//jTextField2.setVisible(false);
this.rndn = new RandomNumber();
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jCheckBox1 = new javax.swing.JCheckBox();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField3 = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Generate Number");
jButton1.setToolTipText("");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setToolTipText("");
jCheckBox1.setText("Add Notes");
jButton2.setText("Save Note and Number");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("View Notes");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton4.setText("Save All Data");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("Load Data");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(112, 112, 112)
.addComponent(jButton3)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jCheckBox1)))
.addGap(0, 82, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(111, 111, 111))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBox1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public RandomNumber rndn;
//View Randomly Generated Number buttom
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText(rndn.getNumber());
}
//save number button
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(jCheckBox1.isSelected()){
String text = jTextField3.getText();
rndn.removeNumber(text);
}else{
rndn.removeNumber("");
}
}
//view notes
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
StringBuilder sb = new StringBuilder();
for (Map.Entry<String,String> entry : rndn.getSaveState().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append("ID: ").append(key).append("\t");
sb.append("Note: ").append(value).append("\n");
}
jTextArea1.setText(sb.toString());
}
//save data
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedReader txtReader = rndn.getTxtReader();
ArrayList<String> numbers = rndn.getNumbers();
ArrayList<String> usedNumbers = rndn.getUsedNumbers();
String currentNumber = rndn.getCurrentNumber();
Map<String, String> saveState = rndn.getSaveState();
try
{
FileOutputStream fileOut = new FileOutputStream("/tmp/data.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(rndn);
out.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
}
//load data
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// try
// {
// FileInputStream fileIn = new FileInputStream("/tmp/data.ser");
// ObjectInputStream in = new ObjectInputStream(fileIn);
// rndn = (RandomNumber) in.readObject();
// in.close();
// fileIn.close();
// }catch(IOException i)
// {
// i.printStackTrace();
// return;
// }catch(ClassNotFoundException c)
// {
// System.out.println("Employee class not found");
// c.printStackTrace();
// return;
// }
// System.out.println(rndn.getSaveState());
}
/**
* #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(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.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 MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField3;
// End of variables declaration
}
near the end I've comment the two methods as //save and //load
That those methods I can't figure out. When I try and serialize the rndn object I get this error: java.io.NotSerializableException: java.io.BufferedReader
The class that contains the data is serrate from the Form Class:
Here is the RandomNumber class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author marcsantiago
*/
public class RandomNumber implements java.io.Serializable{
private BufferedReader txtReader;
private ArrayList<String> numbers;
private ArrayList<String> usedNumbers = new ArrayList<>();
private Random rnd = new Random();
private String currentNumber;
private Map<String, String> saveState = new HashMap<>();
RandomNumber(){
this.txtReader = new BufferedReader(new InputStreamReader(RandomNumber.class.getResourceAsStream("/resources/unique_nums")));
try{
numbers = new ArrayList(Arrays.asList(txtReader.readLine().split(",")));
}catch(IOException e){
}
}
public String getNumber(){
int item = rnd.nextInt(numbers.size());
currentNumber = numbers.get(item);
while(usedNumbers.contains(currentNumber)){
item = rnd.nextInt(numbers.size());
currentNumber = numbers.get(item);
}
return currentNumber;
}
public void removeNumber(String note){
usedNumbers.add(currentNumber);
saveState.put(currentNumber, note);
numbers.remove(currentNumber);
}
public ArrayList<String> getUsedNumbers() {
return usedNumbers;
}
public String getCurrentNumber() {
return currentNumber;
}
public Map<String, String> getSaveState() {
return saveState;
}
public void setTxtReader(BufferedReader txtReader) {
this.txtReader = txtReader;
}
public BufferedReader getTxtReader() {
return txtReader;
}
public ArrayList<String> getNumbers() {
return numbers;
}
public Random getRnd() {
return rnd;
}
public void setNumbers(ArrayList<String> numbers) {
this.numbers = numbers;
}
public void setUsedNumbers(ArrayList<String> usedNumbers) {
this.usedNumbers = usedNumbers;
}
public void setRnd(Random rnd) {
this.rnd = rnd;
}
public void setCurrentNumber(String currentNumber) {
this.currentNumber = currentNumber;
}
public void setSaveState(Map<String, String> saveState) {
this.saveState = saveState;
}
}
Sorry if it's a bit messy, I haven't cleaned up the code yet because I haven't gotten it to work the way I want to to. Any help in completing this application is much appreciated.
The BufferedReader in your class is not seriablizeable and that should be causing the issue. Make it transient and it should work.
I'm trying to do a log in I've gotten the username to work but the password is failing hard, I've tried multiple techniques and different ways and all of them have failed, my last effort seems to do nothing at all no error messages either where my previous stuff displayed error.
Can you please help me fix this + show me how to navigate to another page if the access is verified and password and username is right?
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Arrays;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class MainMenu extends javax.swing.JFrame {
private JLabel username;
private JLabel passwordlbl;
private JLabel Welco;
private JPasswordField Passwordfld;
private JButton Cancelbtn;
private JButton OKbtn;
private JTextField Usernametxt;
private String Password = "pass";
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
//PASSWORD field to store new password inside
//Passwordfld.setEchoChar('*');
//Passwordfld.addActionListener(new AL());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainMenu inst = new MainMenu();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public MainMenu() {
super();
initGUI();
}
private static boolean isPasswordCorrect(char[] input) {
boolean isCorrect = true;
char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals (input, correctPassword);
}
//Zero out the password.
Arrays.fill(correctPassword,'0');
return isCorrect;
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
username = new JLabel();
getContentPane().add(username);
username.setText("User Name:");
username.setBounds(63, 113, 80, 16);
passwordlbl = new JLabel();
getContentPane().add(passwordlbl);
passwordlbl.setText("Password:");
passwordlbl.setBounds(63, 160, 72, 16);
Usernametxt = new JTextField();
getContentPane().add(Usernametxt);
Usernametxt.setBounds(198, 110, 79, 23);
OKbtn = new JButton();
getContentPane().add(OKbtn);
OKbtn.setText("OK");
OKbtn.setBounds(102, 217, 59, 23);
OKbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(Usernametxt.getText().equals("Admin")){} /*&&
(Passwordfld.getText().equals("Admin2"))*/
String cmd = evt.getActionCommand();
if (OKbtn.equals(cmd)) { //Process the password.
char[] input = Passwordfld.getPassword();
if (isPasswordCorrect(input)) {
System.out.println("Password Accepted");
} else {
System.out.println("Password Rejected");
}
//Zero out the possible password, for security.
Arrays.fill(input, '0');
Passwordfld.selectAll();
/*else{
System.out.println("permition Rejected");
}*/
//else{}
/* if (Passwordfld = Password)= true) {
System.out.println("permition granted");}*/
}
}
}
);
Cancelbtn = new JButton();
getContentPane().add(Cancelbtn);
Cancelbtn.setText("Exit");
Cancelbtn.setBounds(198, 217, 61, 23);
Cancelbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setDefaultCloseOperation(WindowConstants.setVisible(false);
//System.out.println("Cancelbtn.actionPerformed, event="+evt);
//TODO add your code for Cancelbtn.actionPerformed
}
});
Welco = new JLabel();
getContentPane().add(Welco);
Welco.setText("Welcome to Jstore please log in using your staff acount");
Welco.setBounds(51, 19, 291, 16);
JPasswordField Passwordfld = new JPasswordField();
//Passwordfld.setText("Secret");
getContentPane().add(Passwordfld);
Passwordfld.setBounds(198, 157, 79, 23);
Passwordfld.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//System.out.println("Passwordfld.actionPerformed, event="+evt);
//TODO add your code for Passwordfld.actionPerformed
}
});
pack();
setSize(400, 300);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
//static class AL implements ActionListener{
//JPasswordField input = new JPasswordField();
/* char [] passy = input.getPassword();
String p = new String (passy);{
if (p.equals (Password)){
JOptionPane.showMessageDialog(null, "Correct"); }
else
{ JOptionPane.showMessageDialog(null, "InCorrect");
}
*/
}
Alternatively you can use this....
package javaapplication7;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
/**
*
* #author akash
*/
public class detail extends javax.swing.JFrame implements ActionListener{
private final String username ="admin";
private final String password = "pass";
public detail() {
initComponents();
jButton1.addActionListener(this);
}
/**
* 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();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Username");
jLabel2.setText("Password");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jButton1.setText("Submit");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(63, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14))
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(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(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(detail.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 detail().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()== jButton1)
{
if("admin".equals(jTextField1.getText()) && "pass".equals(jTextField2.getText()))
{
java.awt.EventQueue.invokeLater(() -> {
new LoggedIn().setVisible(true);
});
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use admin and pass");
}
}
}
}
The above one will be your first class and the next will be....
class LoggedIn extends javax.swing.JFrame {
/**
* Creates new form LoggedIn
*/
public LoggedIn() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Welcome 2 Store");
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(91, 91, 91)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(101, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(163, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #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(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Hoping it helped....
Your password field is not inited, it's still null when you try to take char[] from it. You can try with:
final JPasswordField Passwordfld = new JPasswordField();
// Passwordfld.setText("Secret");
getContentPane().add(Passwordfld);
Passwordfld.setBounds(198, 157, 79, 23);
Passwordfld.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.out.println("Passwordfld.actionPerformed, event="+evt);
// TODO add your code for Passwordfld.actionPerformed
}
});
OKbtn = new JButton();
getContentPane().add(OKbtn);
OKbtn.setText("OK");
OKbtn.setBounds(102, 217, 59, 23);
OKbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String passText = new String(Passwordfld.getPassword());
if (Usernametxt.getText().equals("Admin")) {
String cmd = evt.getActionCommand();
if (OKbtn.getActionCommand().equals(cmd)) { // Process the password.
if (isPasswordCorrect(passText.toCharArray())) {
System.out.println("Password Accepted");
} else {
System.out.println("Password Rejected: " + passText);
}
// Zero out the possible password, for security.
Arrays.fill(passText.toCharArray(), '0');
Passwordfld.selectAll();
/*
* else{ System.out.println("permition Rejected"); }
*/
// else{}
/*
* if (Passwordfld = Password)= true) {
* System.out.println("permition granted");}
*/
}
}
}
});
I have write a code to find a word in JTextPane. Problem here is when I enter a search word and click on search button it was highlight the all the occurrence of the given search word. I want to Highlight the first occurrence of the word then click on search button shows second occurrence of the way like that. Another one is it was not unHighlight the after search complete when click on text pane.
My code:
public class FindAWord extends javax.swing.JFrame {
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(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MarkAll().setVisible(true);
}
});
}
Highlighter.HighlightPainter myHighLightPainter = new FindAWord.MyHighightPainter(
Color.LIGHT_GRAY);
// Variables declaration - do not modify
private javax.swing.JScrollPane scrollPane;
private javax.swing.JTextField searchText;
private javax.swing.JTextPane textPane;
private javax.swing.JButton search;
public FindAWord() {
initComponents();
}
public void removeHighLights(JTextComponent component) {
Highlighter hilet = component.getHighlighter();
Highlighter.Highlight[] highLites = hilet.getHighlights();
for (int i = 0; i < highLites.length; i++) {
if (highLites[i].getPainter() instanceof MarkAll.MyHighightPainter) {
hilet.removeHighlight(highLites[i]);
}
}
}
public void highLight(JTextComponent component, String patteren) {
try {
removeHighLights(component);
Highlighter hLite = component.getHighlighter();
Document doc = component.getDocument();
String text = component.getText(0, doc.getLength());
int pos = 0;
while ((pos = text.toUpperCase().indexOf(patteren.toUpperCase(),
pos)) >= 0) {
hLite.addHighlight(pos, pos + patteren.length(),
myHighLightPainter);
pos += patteren.length();
}
} catch (Exception e) {
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
search = new javax.swing.JButton();
searchText = new javax.swing.JTextField();
scrollPane = new javax.swing.JScrollPane();
textPane = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
search.setText("Search");
search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchActionPerformed(evt);
}
});
scrollPane.setViewportView(textPane);
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(36, 36, 36)
.addComponent(search,
javax.swing.GroupLayout.PREFERRED_SIZE,
91,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(searchText,
javax.swing.GroupLayout.PREFERRED_SIZE,
120,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114, Short.MAX_VALUE))
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addComponent(scrollPane)
.addContainerGap()));
layout.setVerticalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(search)
.addComponent(
searchText,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPane,
javax.swing.GroupLayout.DEFAULT_SIZE,
235, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void searchActionPerformed(java.awt.event.ActionEvent evt) {
if (searchText.getText().length() == 0) {
removeHighLights(textPane);
} else
highLight(textPane, searchText.getText());
}
class MyHighightPainter extends DefaultHighlighter.DefaultHighlightPainter {
MyHighightPainter(Color color) {
super(color);
}
}
}
If you need just to highlight one word you don't need all the addHighlight() and removeHighlight() calls.
Just figure out the word's offset (and length) and use setSelectionStart()/setSelectionEnd() method of the JTextPane passing the word start and start + length
UPDATE as requested the working code
import javax.swing.text.*;
import java.awt.*;
public class FindAWord extends javax.swing.JFrame {
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 (Exception ex) {
ex.printStackTrace();
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new FindAWord().setVisible(true);
}
});
}
Highlighter.HighlightPainter myHighLightPainter=new FindAWord.MyHighightPainter(Color.LIGHT_GRAY);
// Variables declaration - do not modify
private javax.swing.JScrollPane scrollPane;
private javax.swing.JTextField searchText;
private javax.swing.JTextPane textPane;
private javax.swing.JButton search;
public FindAWord() {
initComponents();
}
public void highLight(JTextComponent component,String patteren){
try {
Document doc=component.getDocument();
String text=component.getText(0,doc.getLength());
int pos=component.getCaretPosition();
if (pos==doc.getLength()) {
pos=0;
}
int index=text.toUpperCase().indexOf(patteren.toUpperCase(),pos);
if (index>=0) {
component.setSelectionStart(index);
component.setSelectionEnd(index+patteren.length());
component.getCaret().setSelectionVisible(true);
}
}
catch(Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
search = new javax.swing.JButton();
searchText = new javax.swing.JTextField();
scrollPane = new javax.swing.JScrollPane();
textPane = new javax.swing.JTextPane();
searchText.setText("test");
textPane.setText("test qweqw test asdasdas test");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
search.setText("Search");
search.setFocusable(false);
search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchActionPerformed(evt);
}
});
scrollPane.setViewportView(textPane);
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(36, 36, 36)
.addComponent(search, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(scrollPane)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(search)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void searchActionPerformed(java.awt.event.ActionEvent evt) {
highLight(textPane, searchText.getText());
}
class MyHighightPainter extends DefaultHighlighter.DefaultHighlightPainter{
MyHighightPainter(Color color){
super(color);
}
}
}
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()
}
}
});