An Exam Maker in JFrame, after you finish answering the questions a JOptionPane will pop-up and ask if you want to retake it, I click no and the program is still running.
package quizmaker;
import javax.swing.JOptionPane;
public class QuizMaker extends javax.swing.JFrame {
private static QuestionBuilder Questions = new QuestionBuilder();
private static String[] Question = new String[5];
private static String[] Answer = new String[5];
private static String[] Bogus1 = new String[5];
private static String[] Bogus2 = new String[5];
private static String[] Bogus3 = new String[5];
private static int[] QuestionsIndex = {0, 1, 2, 3, 4};
private static int Index=0, Score=0, QuestionNumber=0;
public QuizMaker() {
initComponents();
goToNext();
}
#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();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setResizable(false);
jLabel1.setText("jLabel1");
jLabel2.setText("jLabel2");
jTextField1.setEditable(false);
jTextField1.setText("jTextField1");
jButton1.setText("jButton1");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jButton2.setText("jButton2");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton2MouseClicked(evt);
}
});
jButton3.setText("jButton3");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton3MouseClicked(evt);
}
});
jButton4.setText("jButton4");
jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton4MouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
.addComponent(jButton1, 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(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.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)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String YourAnswer = jButton1.getText();
checkAnswer(YourAnswer);
goToNext();
}
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String YourAnswer = jButton2.getText();
checkAnswer(YourAnswer);
goToNext();
}
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String YourAnswer = jButton3.getText();
checkAnswer(YourAnswer);
goToNext();
}
private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String YourAnswer = jButton4.getText();
checkAnswer(YourAnswer);
goToNext();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(QuizMaker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(QuizMaker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(QuizMaker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(QuizMaker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
for (int x=0; x<=4; x++) {
QuestionNumber = x + 1;
Question[x] = JOptionPane.showInputDialog(null, "Enter Question # " + QuestionNumber, "Question # " + QuestionNumber);
Answer[x] = JOptionPane.showInputDialog(null, "Enter Answer in Question # " + QuestionNumber, "Answer in Question # " + QuestionNumber);
Bogus1[x] = JOptionPane.showInputDialog(null, "Enter Bogus 1 in Question # " + QuestionNumber, "Bogus 1 in Question # " + QuestionNumber);
Bogus2[x] = JOptionPane.showInputDialog(null, "Enter Bogus 2 in Question # " + QuestionNumber, "Bogus 2 in Question # " + QuestionNumber);
Bogus3[x] = JOptionPane.showInputDialog(null, "Enter Bogus 3 in Question # " + QuestionNumber, "Bogus 3 in Question # " + QuestionNumber);
}
QuestionNumber=1;
for (int x=4; x>=0; x--) {
int y=x+1;
int w=(int)(Math.random()*y);
int Container = QuestionsIndex[w];
QuestionsIndex[w] = QuestionsIndex[x];
QuestionsIndex[x] = Container;
}
Message("Let's start the quiz.");
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new QuizMaker().setVisible(true);
}
});
}
public static void goToNext() {
if (QuestionNumber > 5) {
Message("Your score is " + Score + " out of 5.");
int ConfirmButton = JOptionPane.YES_NO_CANCEL_OPTION;
JOptionPane.showConfirmDialog(null, "Do yo want to retake?", null, ConfirmButton);
if (ConfirmButton == JOptionPane.YES_OPTION) {
Score=0;
QuestionNumber=1;
for (int x=4; x>=0; x--) {
int y=x+1;
int w=(int)(Math.random()*y);
int Container = QuestionsIndex[w];
QuestionsIndex[w] = QuestionsIndex[x];
QuestionsIndex[x] = Container;
}
goToNext();
}
else {
System.exit(0);
}
}
else if (QuestionNumber <= 5) {
jLabel1.setText("Question " + QuestionNumber + " of 5");
jLabel2.setText("Score: " + Score);
Questions.setQuestion(Question[QuestionsIndex[QuestionNumber-1]]);
Questions.setAnswer(Answer[QuestionsIndex[QuestionNumber-1]]);
Questions.setBogus1(Bogus1[QuestionsIndex[QuestionNumber-1]]);
Questions.setBogus2(Bogus2[QuestionsIndex[QuestionNumber-1]]);
Questions.setBogus3(Bogus3[QuestionsIndex[QuestionNumber-1]]);
String[] Choices = new String[4];
Choices[0] = Questions.getAnswer();
Choices[1] = Questions.getBogus1();
Choices[2] = Questions.getBogus2();
Choices[3] = Questions.getBogus3();
for (int x=3; x>=0; x--) {
int y=x+1;
int w=(int)(Math.random()*y);
String Container = Choices[w];
Choices[w] = Choices[x];
Choices[x] = Container;
}
jTextField1.setText(Questions.getQuestion());
jButton1.setText(Choices[0]);
jButton2.setText(Choices[1]);
jButton3.setText(Choices[2]);
jButton4.setText(Choices[3]);
QuestionNumber++;
}
}
public static void checkAnswer(String YourAnswer) {
if (YourAnswer.equals(Questions.getAnswer())) {
Message("Correct!");
Score++;
}
else {
Message("Wrong!");
}
}
public static void Message(Object Message) {
JOptionPane.showMessageDialog(null, Message);
}
// Variables declaration - do not modify
private static javax.swing.JButton jButton1;
private static javax.swing.JButton jButton2;
private static javax.swing.JButton jButton3;
private static javax.swing.JButton jButton4;
private static javax.swing.JLabel jLabel1;
private static javax.swing.JLabel jLabel2;
private static javax.swing.JTextField jTextField1;
// End of variables declaration
}
The option selected by the user is the return value of the showConfirmDialog(...) method. You will have to do something like this:
int selected = JOptionPane.showConfirmDialog(null, "Do yo want to retake?", null, JOptionPane.YES_NO_CANCEL_OPTION);
if(selected == JOptionPane.YES_OPTION){
...
}
Related
I'm struggling here... I'm building a small calorie calculator application with Java swing using an MVC design pattern.
For some reason, the actionPerformed methods for my secondary view(SettingsView.java) don't do anything, yet for my main view(UserDetailsView.java) they work fine.
Here's my Controller class. (Simplified the code in the methods)
import com.willemdebruyn.macronutrientcalculator.model.Model;
import com.willemdebruyn.macronutrientcalculator.view.SettingsView;
import com.willemdebruyn.macronutrientcalculator.view.UserDetailsView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller
{
private UserDetailsView userDetailsView;
private SettingsView settingsView;
private Model model;
private double requiredCalories;
public Controller(UserDetailsView userDetailsView, SettingsView settingsView, Model model)
{
this.userDetailsView = userDetailsView;
this.settingsView = settingsView;
this.model = model;
this.userDetailsView.addCalorieCalculationListener(new CalorieCalculationListener()); // Here I add the listeners for my main view, they work just fine
this.userDetailsView.addMacroCalculationListener(new MacroCalculationListener());
this.settingsView.addApplySettingsListener(new ApplySettingsListener()); // This is the one that doesn't work
}
class CalorieCalculationListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("This prints...");
}
}
class MacroCalculationListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("This prints as well...");
}
}
class ApplySettingsListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("This never prints...");
}
}
}
Here's the methods that add the ActionListener in my UserDetailsView, which work as expected
public void addCalorieCalculationListener(ActionListener listenForCalorieButton)
{
caloriesButton.addActionListener(listenForCalorieButton);
}
public void addMacroCalculationListener(ActionListener listenForMacroButton)
{
macrosButton.addActionListener(listenForMacroButton);
}
Here is the code from my SettingsView to add the ActionListener (The one that doesn't work)
public void addApplySettingsListener(ActionListener listenForApplyButton)
{
applyButton.addActionListener(listenForApplyButton);
}
Am I missing something?
Edit:
As requested the SettingsView code
import java.awt.event.ActionListener;
public class SettingsView extends javax.swing.JFrame
{
/**
* Creates new form SettingsView
*/
public SettingsView()
{
initComponents();
myInit();
}
/**
* 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()
{
jLabel3 = new javax.swing.JLabel();
jInternalFrame1 = new javax.swing.JInternalFrame();
jInternalFrame2 = new javax.swing.JInternalFrame();
jLabel2 = new javax.swing.JLabel();
metricRadioButton = new javax.swing.JRadioButton();
imperialRadioButton = new javax.swing.JRadioButton();
jInternalFrame3 = new javax.swing.JInternalFrame();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox<>();
carbsTextField = new javax.swing.JTextField();
proteinsTextField = new javax.swing.JTextField();
fatsTextField = new javax.swing.JTextField();
applyButton = new javax.swing.JButton();
jLabel3.setText("jLabel3");
jInternalFrame1.setVisible(true);
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame2.setVisible(true);
jLabel2.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel2.setText("Measuring System:");
metricRadioButton.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
metricRadioButton.setText("Metric (cm/kg)");
metricRadioButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
metricRadioButtonActionPerformed(evt);
}
});
imperialRadioButton.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
imperialRadioButton.setText("Imperial (in/lbs)");
imperialRadioButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
imperialRadioButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jInternalFrame2Layout = new javax.swing.GroupLayout(jInternalFrame2.getContentPane());
jInternalFrame2.getContentPane().setLayout(jInternalFrame2Layout);
jInternalFrame2Layout.setHorizontalGroup(
jInternalFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame2Layout.createSequentialGroup()
.addGap(113, 113, 113)
.addGroup(jInternalFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imperialRadioButton)
.addComponent(metricRadioButton)
.addComponent(jLabel2))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jInternalFrame2Layout.setVerticalGroup(
jInternalFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(metricRadioButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(imperialRadioButton)
.addGap(0, 16, Short.MAX_VALUE))
);
jInternalFrame3.setVisible(true);
jLabel4.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel4.setText("Carbs:");
jLabel5.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel5.setText("Proteins:");
jLabel6.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel6.setText("Fats:");
jLabel7.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel7.setText("Custom Macros:");
jLabel1.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel1.setText("Macro Nutrients Split:");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "<Carbs/Proteins/Fats>", "50/30/20", "80/10/10", "Custom" }));
javax.swing.GroupLayout jInternalFrame3Layout = new javax.swing.GroupLayout(jInternalFrame3.getContentPane());
jInternalFrame3.getContentPane().setLayout(jInternalFrame3Layout);
jInternalFrame3Layout.setHorizontalGroup(
jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame3Layout.createSequentialGroup()
.addGap(110, 110, 110)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame3Layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame3Layout.createSequentialGroup()
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(fatsTextField)
.addComponent(proteinsTextField)
.addComponent(carbsTextField))))
.addComponent(jLabel1)))
.addContainerGap(111, Short.MAX_VALUE))
);
jInternalFrame3Layout.setVerticalGroup(
jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame3Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(carbsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(proteinsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(fatsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 38, Short.MAX_VALUE))
);
applyButton.setText("Apply");
applyButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
applyButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame2)
.addComponent(jInternalFrame3)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(applyButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jInternalFrame2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jInternalFrame3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(applyButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void myInit()
{
// Metric radio button should be selected on default
metricRadioButton.setSelected(true);
// Disable textFields on startup
carbsTextField.setEditable(false);
proteinsTextField.setEditable(false);
fatsTextField.setEditable(false);
}
private void metricRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// When metric radio button is selected, deselect the imperial radio button
imperialRadioButton.setSelected(false);
}
private void imperialRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// When imperial radio button is selected, deselect the metric radio button
metricRadioButton.setSelected(false);
}
private void applyButtonActionPerformed(java.awt.event.ActionEvent evt)
{
System.out.println("Apply button clicked");
}
public void addApplySettingsListener(ActionListener listenForApplyButton)
{
applyButton.addActionListener(listenForApplyButton);
}
public String getMeasuringSystem()
{
if (metricRadioButton.isSelected() && !imperialRadioButton.isSelected())
return "Metric";
else if (imperialRadioButton.isSelected() && !metricRadioButton.isSelected())
return "Imperial";
return "No Selection made";
}
// Variables declaration - do not modify
private javax.swing.JButton applyButton;
private javax.swing.JTextField carbsTextField;
private javax.swing.JTextField fatsTextField;
private javax.swing.JRadioButton imperialRadioButton;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JInternalFrame jInternalFrame2;
private javax.swing.JInternalFrame jInternalFrame3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JRadioButton metricRadioButton;
private javax.swing.JTextField proteinsTextField;
// End of variables declaration
}
Edit 2: Here's my class containing the main method
import com.willemdebruyn.macronutrientcalculator.controller.Controller;
import com.willemdebruyn.macronutrientcalculator.model.Model;
import com.willemdebruyn.macronutrientcalculator.view.SettingsView;
import com.willemdebruyn.macronutrientcalculator.view.UserDetailsView;
public class App
{
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(UserDetailsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UserDetailsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UserDetailsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UserDetailsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
UserDetailsView userDetailsView = new UserDetailsView();
SettingsView settingsView = new SettingsView();
Model model = new Model();
Controller controller = new Controller(userDetailsView, settingsView, model);
userDetailsView.setVisible(true); // SettingsView gets openend from this view
}
}
Edit 3: UserDetailsView.java
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class UserDetailsView extends JFrame
{
private boolean calorieCalculationPerformed;
public UserDetailsView()
{
initComponents();
myInit();
}
/**
* 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()
{
// I removed the generated code, apparently my post exeeded the allowed limit
}
private void myInit()
{
// Disable macros button on startup, will enable again after caloric needs have been calculated
macrosButton.setEnabled(false);
}
private void maleRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// When male button is selected, deselect the female radio button
femaleRadioButton.setSelected(false);
}
private void femaleRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// When female button is selected, deselect the male radio button
maleRadioButton.setSelected(false);
}
private void caloriesButtonActionPerformed(java.awt.event.ActionEvent evt)
{
calorieCalculationPerformed = true;
System.out.println("Calories button gets clicked");
if (heightField.getText().isEmpty() || weightField.getText().isEmpty() || ageField.getText().isEmpty())
{
JOptionPane.showMessageDialog(this, "Please fill in all the fields before performing the calculation.");
calorieCalculationPerformed = false;
}
else if ((!maleRadioButton.isSelected() && !femaleRadioButton.isSelected()))
{
JOptionPane.showMessageDialog(this, "Please select your gender.");
calorieCalculationPerformed = false;
}
else if (activityComboBox.getSelectedItem().toString() == "<Select>")
{
JOptionPane.showMessageDialog(this, "Please select your activity level.");
calorieCalculationPerformed = false;
}
else if (goalComboBox.getSelectedItem().toString() == "<Select>")
{
JOptionPane.showMessageDialog(this, "Please select your fitness goal.");
calorieCalculationPerformed = false;
}
// Only when caloric requirements have been calculated will the user be able to calculate macronutrient requirements
if (calorieCalculationPerformed)
macrosButton.setEnabled(true);
else
macrosButton.setEnabled(false);
}
private void macrosButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if (heightField.getText().isEmpty() || weightField.getText().isEmpty() || ageField.getText().isEmpty())
{
JOptionPane.showMessageDialog(this, "Please fill in all the fields before performing the calculation.");
}
else if ((!maleRadioButton.isSelected() && !femaleRadioButton.isSelected()))
{
JOptionPane.showMessageDialog(this, "Please select your gender.");
}
else if (activityComboBox.getSelectedItem().toString() == "<Select>")
{
JOptionPane.showMessageDialog(this, "Please select your activity level.");
calorieCalculationPerformed = false;
}
else if (goalComboBox.getSelectedItem().toString() == "<Select>")
{
JOptionPane.showMessageDialog(this, "Please select your fitness goal.");
}
}
private void settingsButtonActionPerformed(java.awt.event.ActionEvent evt)
{
SettingsView settingsView = new SettingsView();
settingsView.setVisible(true);
}
public void addCalorieCalculationListener(ActionListener listenForCalorieButton)
{
caloriesButton.addActionListener(listenForCalorieButton);
}
public void addMacroCalculationListener(ActionListener listenForMacroButton)
{
macrosButton.addActionListener(listenForMacroButton);
}
public double getUserHeight()
{
if (!heightField.getText().isEmpty())
return Double.parseDouble(heightField.getText());
return 0.0;
}
public double getUserWeight()
{
if (!weightField.getText().isEmpty())
return Double.parseDouble(weightField.getText());
return 0.0;
}
public int getUserAge()
{
if (!ageField.getText().isEmpty())
return Integer.parseInt(ageField.getText());
return 0;
}
public String getUserGender()
{
if (femaleRadioButton.isSelected() && !maleRadioButton.isSelected())
{
return "female";
}
else if(maleRadioButton.isSelected() && !femaleRadioButton.isSelected())
{
return "male";
}
else return "No selection made";
}
public String getUserActivityLevel()
{
return (String) activityComboBox.getSelectedItem();
}
public String getUserGoal()
{
return (String) goalComboBox.getSelectedItem();
}
public void displayNutritionalInfo(String message)
{
JOptionPane.showMessageDialog(this, message);
}
public void displayErrorMessage(String errorMessage)
{
JOptionPane.showMessageDialog(this, errorMessage);
}
// Variables declaration - do not modify
private javax.swing.JComboBox<String> activityComboBox;
private javax.swing.JTextField ageField;
private javax.swing.JButton caloriesButton;
private javax.swing.JRadioButton femaleRadioButton;
private javax.swing.JComboBox<String> goalComboBox;
private javax.swing.JTextField heightField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JButton macrosButton;
private javax.swing.JRadioButton maleRadioButton;
private javax.swing.JButton settingsButton;
private javax.swing.JTextField weightField;
// End of variables declaration
}
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...
I have created a search tool in java that reads doc and docx files. First, the user have to select a folder that contain the word documents. The program works fine however when I select desktop as the folder it gives the following error: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
Here is my code:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Main.java
*
* Created on Jul 4, 2014, 8:19:21 AM
*/
/**
*
* #author Yağız
*/
public class search extends javax.swing.JFrame {
Boolean check = true;
File[] filelist;
/** Creates new form Main */
public search() {
initComponents();
setIcon();
}
/** 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() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
jFrame1 = new javax.swing.JFrame();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
label1 = new java.awt.Label();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
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)
);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jFrame1, org.jdesktop.beansbinding.ELProperty.create("CV Search"), this, org.jdesktop.beansbinding.BeanProperty.create("title"));
bindingGroup.addBinding(binding);
label1.setText("Keyword:");
jButton1.setText("Find");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Select Folder");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(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(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addComponent(label1, 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(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(29, 29, 29))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.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(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1))
.addGap(37, 37, 37))
);
bindingGroup.bind();
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-278)/2, (screenSize.height-158)/2, 278, 158);
jFrame1.getRootPane().setDefaultButton(jButton1);
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//Select Folder Button
try{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(null);
if(fc.getSelectedFile()==null){
check = false;
}
else
{
File folder = new File(fc.getSelectedFile().getPath());
filelist = folder.listFiles();
if( filelist.length == 0 ){
// dialog: folder is empty
check = false;
}
else
{
check = true;
}
}
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error");
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//Find button for finding the word in word documents in the selected folder
String keyword = jTextField1.getText();
int count=0;
while (! check ) {
JOptionPane.showMessageDialog(null, "Select a Folder!");
return;
}
if(keyword.equals("")){
JOptionPane.showMessageDialog(null, "No keyword found!");
return;
}
ArrayList result = new ArrayList();
try
{
for( int i=0; i < filelist.length; i++){
// maybe also .doc?
if( filelist[i].getName().endsWith( ".docx" ) ){
count++;
XWPFDocument input = new XWPFDocument(new FileInputStream(filelist[i]));
XWPFWordExtractor extract = new XWPFWordExtractor(input);
Scanner scan = new Scanner(extract.getText());
while(scan.hasNext())
{
String word = scan.next();
if( keyword.equalsIgnoreCase(word) ) {
result.add(filelist[i].getName().replace(".docx",""));
break;
}
}
}
else if(filelist[i].getName().endsWith( ".doc" )){
HWPFDocument inputdoc = new HWPFDocument(new FileInputStream(filelist[i]));
WordExtractor extract = new WordExtractor(inputdoc);
Scanner scan = new Scanner(extract.getText());
while(scan.hasNext())
{
String word = scan.next();
if( keyword.equalsIgnoreCase(word) ) {
result.add(filelist[i].getName().replace(".doc",""));
break;
}
}
}
else
continue;
}
if( count == 0 ){
JOptionPane.showMessageDialog(null,"Selected folder must contain word documents");
return;
}
//...
if(result.isEmpty()){
JOptionPane.showMessageDialog(null,"No match found!");
return;
}
else {
StringBuilder sb = new StringBuilder();
for( int j = 0; j < result.size(); j++){
sb.append( result.get(j) ).append( "\n" );
}
JOptionPane.showMessageDialog( null, sb.toString(), "Results", JOptionPane.INFORMATION_MESSAGE );
}
} catch (Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error!");
}
}
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
if( evt.getKeyCode() == KeyEvent.VK_ENTER ){
jButton1.doClick();
}
}
/**
* #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(search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(search.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 search().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JFrame jFrame1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTextField jTextField1;
private java.awt.Label label1;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration
private void setIcon(){
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("icon.png")));
}
}
What does this error mean and when does it occur? Can anyone help with my situation? Thanks
I've made an application in java using NetBeans IDE and I'm having a problem. It doesn't read the array elements. Here's the code:
private void buton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] toppings = new String[20];
toppings[0] = "";
toppings[1] = "";
toppings[2] = "";
toppings[3] = "";
int size = toppings.length;
for (int i=0; i<size; i++){
toppings[i]=textbox.getText();
label1.setText(toppings[0]);
label2.setText(toppings[1]);
label3.setText(toppings[2]);
label4.setText(toppings[3]);
}
}
I want to put then each element of the array on the labels(label1,label2,label3,label4) each time I press the button and add a new value for a new element in the vector.
At this time, when I type the value of the first element it sets the value to all labels.
Does anybody have an idea please?
You should create array of JLabel and then fill up the text on them in for loop:
private javax.swing.JLabel label[];
//write these lines within constructor or wherever you are creating your GUI
label = new javax.swing.JLabel[4];//
for (int i = 0 ; i < label.length ;i++)
label[i] = new javax.swing.jLabel();
Then change the buton1ActionPerformed
private void buton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] toppings = new String[20];
toppings[0] = "";
toppings[1] = "";
toppings[2] = "";
toppings[3] = "";
int size = toppings.length;
for (int i=0; i<size; i++){
toppings[i]=textbox.getText();
if (i < 4)
label[i].setText(toppings[i]);
}
}
EDIT
Here I have put the updated version of your code. Just run it and tell me if it fulfills what you looking for:
public class fereastra extends javax.swing.JFrame {
/**
* Creates new form fereastra
*/
public fereastra() {
initComponents();
buttonGroup1.add(singleplayer);
buttonGroup1.add(twoplayers);
buttonGroup1.add(threeplayers);
buttonGroup1.add(fourplayers);
casutatext.setVisible(true);
panel.setVisible(true);
text.setText("Wellcome! Please choose the number of players!");
}
/**
* 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() {
label = new javax.swing.JLabel[4];//
for (int i = 0 ; i < label.length ;i++)
{label[i] = new javax.swing.JLabel();}
buttonGroup1 = new javax.swing.ButtonGroup();
casutatext = new javax.swing.JTextField();
text = new javax.swing.JLabel();
buton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
panel = new javax.swing.JPanel();
fourplayers = new javax.swing.JRadioButton();
twoplayers = new javax.swing.JRadioButton();
threeplayers = new javax.swing.JRadioButton();
singleplayer = new javax.swing.JRadioButton();
test = new javax.swing.JLabel();
test2 = new javax.swing.JLabel();
test3 = new javax.swing.JLabel();
test4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
casutatext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
casutatextActionPerformed(evt);
}
});
text.setText("Text");
buton1.setText("OK");
buton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buton1ActionPerformed(evt);
}
});
jButton3.setText("Cancel");
fourplayers.setText("4 players");
fourplayers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fourplayersActionPerformed(evt);
}
});
twoplayers.setText("2 players");
twoplayers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
twoplayersActionPerformed(evt);
}
});
threeplayers.setText("3 players");
threeplayers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
threeplayersActionPerformed(evt);
}
});
singleplayer.setText("Single player");
singleplayer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
singleplayerActionPerformed(evt);
}
});
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(singleplayer)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(twoplayers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(threeplayers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(fourplayers)
.addContainerGap())
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(singleplayer)
.addComponent(twoplayers)
.addComponent(threeplayers)
.addComponent(fourplayers))
.addContainerGap())
);
test.setText("test");
test2.setText("jLabel1");
test3.setText("jLabel2");
test4.setText("jLabel3");
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(127, 127, 127)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(casutatext, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(text, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(label[0])
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(buton1)
.addGap(35, 35, 35)
.addComponent(jButton3))
.addGroup(layout.createSequentialGroup()
.addComponent(label[1])
.addGap(32, 32, 32)
.addComponent(label[2])
.addGap(31, 31, 31)
.addComponent(label[3])))))
.addGap(93, 93, 93))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(text)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(casutatext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buton1)
.addComponent(jButton3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(label[0])
.addComponent(label[1])
.addComponent(label[2])
.addComponent(label[3]))
.addGap(51, 51, 51))
);
pack();
}// </editor-fold>
private void casutatextActionPerformed(java.awt.event.ActionEvent evt) {
}
private void buton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] toppings = new String[20];
toppings[0] = "";
toppings[1] = "";
toppings[2] = "";
toppings[3] = "";
int size = toppings.length;
for (int i=0; i<size; i++){
toppings[i]=casutatext.getText();
if (i < 4)
{label[i].setText(toppings[i]);
}
}
}
private void singleplayerActionPerformed(java.awt.event.ActionEvent evt) {
numarjucatori=1;
}
private void twoplayersActionPerformed(java.awt.event.ActionEvent evt) {
numarjucatori=2;
}
private void threeplayersActionPerformed(java.awt.event.ActionEvent evt) {
numarjucatori=3;
}
private void fourplayersActionPerformed(java.awt.event.ActionEvent evt) {
numarjucatori=4;
}
/**
* #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(fereastra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(fereastra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(fereastra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(fereastra.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 fereastra().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buton1;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JTextField casutatext;
private javax.swing.JRadioButton fourplayers;
private javax.swing.JButton jButton3;
private javax.swing.JPanel panel;
private javax.swing.JRadioButton singleplayer;
private javax.swing.JLabel test;
private javax.swing.JLabel test2;
private javax.swing.JLabel test3;
private javax.swing.JLabel test4;
private javax.swing.JLabel text;
private javax.swing.JRadioButton threeplayers;
private javax.swing.JRadioButton twoplayers;
// End of variables declaration
public int numarjucatori;
public String p1="", p2="", p3="", p4="";
private javax.swing.JLabel label[];
}
The first issue I see is that you're trying to set the label text inside of the for loop where you should really be doing it outside:
for(int i = 0; i < toppings.length; i++){
toppings[i] = textbox.getText();
}
label1.setText(toppings[0]);
// etc.
i want to get the value from the txt field val1 and val2 and store it in the variables n1 and n2. then n1 and n2 will be parsed to get the value for the calculator. here is the code:
public class CalcUI extends javax.swing.JFrame {
String n1 = val1.getText();
String n2 = val2.getText();
double num1 = Double.parseDouble(n1);
double num2 = Double.parseDouble(n2);
/**
* Creates new form CalcUI
*/
public CalcUI() {
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() {
val1 = new javax.swing.JTextField();
val2 = new javax.swing.JTextField();
plus = new javax.swing.JButton();
multiply = new javax.swing.JButton();
clr = new javax.swing.JButton();
exit = new javax.swing.JButton();
minus = new javax.swing.JButton();
divide = new javax.swing.JButton();
ans = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
plus.setText("+");
plus.setMaximumSize(new java.awt.Dimension(41, 41));
plus.setMinimumSize(new java.awt.Dimension(41, 41));
plus.setPreferredSize(new java.awt.Dimension(41, 41));
plus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
plusActionPerformed(evt);
}
});
multiply.setText("*");
multiply.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
multiplyActionPerformed(evt);
}
});
clr.setText("Clear");
clr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clrActionPerformed(evt);
}
});
exit.setText("Exit");
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
minus.setText("-");
minus.setMaximumSize(new java.awt.Dimension(41, 41));
minus.setMinimumSize(new java.awt.Dimension(41, 41));
minus.setPreferredSize(new java.awt.Dimension(41, 41));
minus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
minusActionPerformed(evt);
}
});
divide.setText("/");
divide.setMaximumSize(new java.awt.Dimension(41, 41));
divide.setMinimumSize(new java.awt.Dimension(41, 41));
divide.setPreferredSize(new java.awt.Dimension(41, 41));
divide.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
divideActionPerformed(evt);
}
});
ans.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(val1)
.addComponent(val2)
.addGroup(layout.createSequentialGroup()
.addComponent(clr)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(exit)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(134, 134, 134)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(multiply, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(plus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(77, 77, 77)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(minus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(divide, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(143, 143, 143))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(ans, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(val1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(val2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ans, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(plus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(minus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(multiply, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(clr)
.addComponent(exit))
.addContainerGap())
);
pack();
}// </editor-fold>
private void plusActionPerformed(java.awt.event.ActionEvent evt) {
double add = num1 + num2;
ans.setText(Double.toString(add));
// TODO add your handling code here:
}
private void minusActionPerformed(java.awt.event.ActionEvent evt) {
double min = num1 - num2;
ans.setText(Double.toString(min));
// TODO add your handling code here:
}
private void divideActionPerformed(java.awt.event.ActionEvent evt) {
double div = num1 / num2;
ans.setText(Double.toString(div));
// TODO add your handling code here:
}
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
// TODO add your handling code here:
}
private void clrActionPerformed(java.awt.event.ActionEvent evt) {
val1.setText("");
val2.setText("");
ans.setText("");
// TODO add your handling code here:
}
private void multiplyActionPerformed(java.awt.event.ActionEvent evt) {
double mult = num1 * num2;
ans.setText(Double.toString(mult));
// 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(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CalcUI.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 CalcUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel ans;
private javax.swing.JButton clr;
private javax.swing.JButton divide;
private javax.swing.JButton exit;
private javax.swing.JButton minus;
private javax.swing.JButton multiply;
private javax.swing.JButton plus;
private javax.swing.JTextField val1;
private javax.swing.JTextField val2;
// End of variables declaration
}
the problem is that in the declaration
String n1 = val1.getText();
String n2 = val2.getText();
i get an error whioch says illegal forward reference. how do i fix this?
this was fixed.
now when i use the following code:
public class CalcUI extends javax.swing.JFrame {
Double num1 ;
Double num2 ;
/**
* Creates new form CalcUI
*/
public CalcUI(){
val1 = new javax.swing.JTextField();
val2 = new javax.swing.JTextField();
num1 = Double.parseDouble(val1.getText());
num2 = Double.parseDouble(val2.getText());
initComponents();
}
i get a build error which says:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at CalcUI.<init>(CalcUI.java:24)
at CalcUI$7.run(CalcUI.java:227)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:671)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
how do i fix this? what is wrong with the code?
I imagine your JTextField components will not have been initialised by the time you are calling:
String n1 = val1.getText();
String n2 = val2.getText();
If you use this code you will see what your input is.
private void yourActionButtonActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null,yourTextField.getText());
}
So, this should store your data to n1.
private void yourActionButtonActionPerformed(java.awt.event.ActionEvent evt) {
String n1;
n1 = yourTextField.getText();
}
You're missing the "equals" button that will do the computation. Add a listener to that button, and in the listener's actionPerformed() you getText() and then compute the calculation. Also, I guess there's no need to have n1 and n2 as class-level variables.