Swing JFrame GUI window is empty when run - java

I've built a Higher/Lower game, using the Swing library. When I run the code I don't get any errors or warnings. The problem appears when I try running the code, the window is empty, not the way it should be.
I use NetBeans to program.There are 2 different files in my project, here is the code...
HiLoGUI.java:
import java.awt.Dimension;
import javax.swing.*;
public class HiLoGUI extends JFrame {
private JTextField txtGuess;
private JLabel outputLabel;
private int theNumber;
public void newGame() {
theNumber = (int)(Math.random() * 100 + 1);
}
public void checkGuess() {
String guessText = txtGuess.getText();
String message = "";
int guess = Integer.parseInt(guessText);
if (guess < theNumber) {
message = guess + " is too low. Try again.";
}
else if (guess > theNumber) {
message = guess + " is too high. Try again.";
}
else {
message = guess + " is correct. You win!";
}
outputLabel.setText(message);
}
public static void main(String[] args) {
HiLoGUI theGame = new HiLoGUI();
theGame.newGame();
theGame.setSize(new Dimension(450,300));
theGame.setVisible(true);
}
}
The window should look like this:
NetBeans screenshot
EDIT:
The other files code:
public class HiLoJFrame extends javax.swing.JFrame {
/**
* Creates new form HiLoJFrame
*/
public HiLoJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
titleLabel = new javax.swing.JLabel();
chooseLabel = new javax.swing.JLabel();
txtGuess = new javax.swing.JTextField();
guessButton = new javax.swing.JButton();
outputLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setName("HiLoGame"); // NOI18N
titleLabel.setFont(new java.awt.Font("SansSerif", 1, 24)); // NOI18N
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
titleLabel.setText("High/Lower Game");
titleLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
chooseLabel.setFont(new java.awt.Font("SansSerif", 0, 15)); // NOI18N
chooseLabel.setText("Guess a name between 1 to 100");
txtGuess.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtGuessActionPerformed(evt);
}
});
guessButton.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
guessButton.setText("Guess");
guessButton.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR));
guessButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
guessButtonActionPerformed(evt);
}
});
outputLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
outputLabel.setText("Enter a number and press Guess");
outputLabel.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(50, Short.MAX_VALUE)
.addComponent(chooseLabel)
.addGap(18, 18, 18)
.addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(136, 136, 136)
.addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(78, 78, 78)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(titleLabel)
.addComponent(outputLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(75, 75, 75)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chooseLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(53, 53, 53)
.addComponent(outputLabel)
.addGap(35, 35, 35))
);
titleLabel.getAccessibleContext().setAccessibleDescription("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 422, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 346, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
getAccessibleContext().setAccessibleName("HiLoGame");
pack();
}// </editor-fold>
private void txtGuessActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
HiLoGUI hilogui = new HiLoGUI();
hilogui.checkGuess();
}
/**
* #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(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new HiLoJFrame().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JLabel chooseLabel;
private javax.swing.JButton guessButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel outputLabel;
private javax.swing.JLabel titleLabel;
private javax.swing.JTextField txtGuess;
// End of variables declaration
}
EDIT2:
I've changed the main class of HiLoGUI.java
I was creating a wrong object.
New main:
public static void main(String[] args) {
HiLoJFrame theGame = new HiLoJFrame();
theGame.newGame();
theGame.setSize(new Dimension(450,300));
theGame.setVisible(true);
}
Now it claims that I need to create that method (newGame) in the JFrame file.

You are calling a method from the wrong class, according to the Swing docs, it is not needed to create a new JFrame object, so setting its visibility is enough. Check this out: How To Call JFrame from another Java class

Related

Cannot hide a JFrame using setVisible(boolean true/false);

Im using the Netbeans Swing Gui builder.
I create a simple menu that I want to appear/disappear when i press a hotkey.
Here is the code for the menu:
package overlay;
import java.util.Properties;
import javax.swing.JOptionPane;
import static overlay.Overlay.flags;
public class Menu extends javax.swing.JFrame {
static boolean isVisible = true;
/**
* Creates new form Menu
*/
public Menu() {
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() {
jSeparator4 = new javax.swing.JSeparator();
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
jSeparator3 = new javax.swing.JSeparator();
jSeparator5 = new javax.swing.JSeparator();
jCheckBox1 = new javax.swing.JCheckBox();
jCheckBox2 = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
setOpacity(0.9F);
setResizable(false);
setType(java.awt.Window.Type.POPUP);
jLabel3.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel3.setText("Foo");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 11, Short.MAX_VALUE)
.addComponent(jLabel3))
);
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jLabel1.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel1.setText("Foo");
jLabel2.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel2.setText("Foo");
jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL);
jCheckBox1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
jCheckBox1.setText("Foo");
jCheckBox1.setActionCommand("JFoo");
jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox1ActionPerformed(evt);
}
});
jCheckBox2.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
jCheckBox2.setText("Foo");
jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCheckBox2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 280, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jSeparator3, 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.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCheckBox1))
.addGap(261, 261, 261))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jSeparator2)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jSeparator5)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBox1)
.addComponent(jCheckBox2))
.addGap(0, 104, Short.MAX_VALUE))
.addComponent(jSeparator1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jCheckBox1.getAccessibleContext().setAccessibleName("JFooB");
pack();
}// </editor-fold>
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here: Foo
Overlay.Foo = !Overlay.Foo;
}
private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here: //Foo1
Overlay.Foo1 = !Overlay.Foo1;
}
/**
* #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 {
Properties props = new Properties();
props.put("windowDecoration", "off");
props.put("textAntiAliasing", "on");
props.put("backgroundPattern", "off");
props.put("backgroundColor", "60 63 65");
props.put("windowBorderColor", "255 255 255");
// props.put("selectionForegroundColor", "255 255 255");
// props.put("selectedTexture", "255 255 255");
props.put("focusColor", "60 63 65");
com.jtattoo.plaf.hifi.HiFiLookAndFeel.setCurrentTheme(props);
javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel");
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu.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 Menu().setVisible(true);
}
});
}
public void toggleMenu() {
isVisible = !isVisible;
if (isVisible) {
setVisible(true);
//JOptionPane.showMessageDialog(null, String.valueOf(isVisible), String.valueOf(isVisible), JOptionPane.INFORMATION_MESSAGE);
} else {
//JOptionPane.showMessageDialog(null, String.valueOf(isVisible), String.valueOf(isVisible), JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
dispose();
}
}
// Variables declaration - do not modify
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JCheckBox jCheckBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
// End of variables declaration
}
What I'm doing is calling the toggleMenu() method from my Main class(named Overlay) upon a key press, and it flips the isVisible boolean. Thing is, when I press the button, it doesnt do anything. Then when I press it again, it creates a new Window with a different look and feel(not the one i specified initially).
I also tried to use the hide(); and show(); methods, but without success.
So what am I doing wrong? I am not really familiar with how Netbeans handles gui creation, although i think this should work.
Fixed, in the run method, change this:
public void run() {
new Menu().setVisible(true);
}
to this:
public void run() {
m = new Menu();
m.setVisible(true);
}
(Create a static Menu object called m, and then in the toggleMenu() method, use
m.setVisible(true);
or false. Closed.

There is no output in my GroceryList program

I rewrote my first application after getting the advice not to use static as much as I did and I misused inherentance. But now my application is not working anymore.
And I can't figure out why not. I think I instanciate the wrong things but can't see which things. I read about instanciation on stackoverflow and other sites but I still don't fully understand it.
I am new to java and don't code for that long. I build a layout in Netbeans. Everytime u click the "Add" button a grocery item should be displayed in the textarea. My old code (with everything being static) worked fine.
I now and then get an "Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.awt.Color" error. But its not coming up all the time. And if I don'get the error and I click the "Add" button there is just noting happening.
Could anyone tell me what I am doing wrong?
Any suggestion on what I'm doing wrong or on how I can debug this would be much appreciated.
GroceryList2ActionListener.java
package javaclasses;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import grocerylist2jframe.GroceryList2JFrame;
// this is the ActionListener for adding a grocery item
public class GroceryList2ActionListener {
public void getButtonActionAddGroceryItem() {
GroceryList2JFrame jFrameAdd = new GroceryList2JFrame();
jFrameAdd.buttonAddGroceryItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String groceryItem = jFrameAdd.jTextField1GroceryItem.getText();
String quantity = jFrameAdd.jTextField2Quantity.getText();
String unit = jFrameAdd.jComboBox1Unit.getSelectedItem().toString();
jFrameAdd.jTextArea1.append(groceryItem + " " + quantity + " " + unit + "\n" );
}
});
}
// this is the ActionListener for removing a grocery item
public void getButtonActionRemoveGroceryItem() {
GroceryList2JFrame jFrameRemove = new GroceryList2JFrame();
jFrameRemove.buttonRemoveGroceryItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jFrameRemove.jTextArea1.setText(jFrameRemove.jTextArea1.getText().replaceAll(jFrameRemove.jTextArea1.getSelectedText(),""));
}
});
}
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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GroceryList2JFrame.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() {
#Override
public void run() {
new GroceryList2JFrame().setVisible(true);
}
});
GroceryList2ActionListener action = new GroceryList2ActionListener();
action.getButtonActionAddGroceryItem(); // I think I call here the "addItem" and "removeItem" on button click.
action.getButtonActionRemoveGroceryItem();
}
}
This is the ActionListener I wrote. And next is my layout for the application I made in Netbeans. I didn't wrote it myself I used a JForm for this.
GroceryList2JFrame.java
package grocerylist2jframe;
public class GroceryList2JFrame extends javax.swing.JFrame {
/**
* Creates new form GroceryList2JFrame
*/
public GroceryList2JFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jComboBox1Unit = new javax.swing.JComboBox();
jTextField2Quantity = new javax.swing.JTextField();
jTextField1GroceryItem = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setSize(new java.awt.Dimension(0, 0));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grocerylist2", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Georgia", 3, 18))); // NOI18N
jPanel1.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grocerylist Input", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Georgia", 3, 14))); // NOI18N
jLabel2.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jLabel2.setText("Choose a Quantity");
jLabel1.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jLabel1.setText("Add a Grocery Item");
jLabel3.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jLabel3.setText("Choose A Unit");
jComboBox1Unit.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jComboBox1Unit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Kilogram", "Gram", "Liter", "Millilitre", "Piece(s)" }));
jComboBox1Unit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1UnitActionPerformed(evt);
}
});
jTextField2Quantity.setFont(new java.awt.Font("Georgia", 0, 9)); // NOI18N
jTextField2Quantity.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2QuantityActionPerformed(evt);
}
});
jTextField1GroceryItem.setFont(new java.awt.Font("Georgia", 0, 9)); // NOI18N
jTextField1GroceryItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1GroceryItemActionPerformed(evt);
}
});
buttonAddGroceryItem.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
buttonAddGroceryItem.setText("Add Grocery Item To Grocerylist");
buttonAddGroceryItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonAddGroceryItemActionPerformed(evt);
}
});
buttonRemoveGroceryItem.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
buttonRemoveGroceryItem.setText("Remove Grocery Item From Gocerylist");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)
.addComponent(jLabel2, 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(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1GroceryItem)
.addComponent(jTextField2Quantity)
.addComponent(jComboBox1Unit, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(buttonAddGroceryItem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonRemoveGroceryItem, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1GroceryItem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2Quantity, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox1Unit, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(86, 86, 86)
.addComponent(buttonAddGroceryItem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(buttonRemoveGroceryItem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(217, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grocerylist2 View", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Georgia", 1, 14))); // NOI18N
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void buttonAddGroceryItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField1GroceryItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField2QuantityActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jComboBox1UnitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
public final javax.swing.JButton buttonAddGroceryItem = new javax.swing.JButton();
public final javax.swing.JButton buttonRemoveGroceryItem = new javax.swing.JButton();
public javax.swing.JComboBox jComboBox1Unit;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
public javax.swing.JTextArea jTextArea1;
public javax.swing.JTextField jTextField1GroceryItem;
public javax.swing.JTextField jTextField2Quantity;
// End of variables declaration
}
I think you have over-complicated this program. Other SO users are correct that you should avoid using static for methods and variables unless absolutely justified. You should read up some on Java Swing event handling and specifically on how to use ActionListener.
In your case, you did not need a separate class (GroceryList2ActionListener), since NetBeans is creating the event handling methods for your (typically). The GroceryList2JFrame already had a method to handle adding a grocery item. For some reason, when you added the remove button, you did not select to add the action listener when building the form.
Additionally, it makes sense to have a 'driver' class with a main to instantiate the frame, set the look-n-feel, etc.
1) You can remove/delete the GroceryList2ActionListener class - it's no longer needed.
2) Add this class to the same package as your GroceryList2JFrame class. This is the driver class that now has the main() method.
package grocerylist2jframe;
public class GroceryList {
public static void main(String args[]) {
System.out.println("Running the GroceryList program...");
/* 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GroceryList2JFrame.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() {
#Override
public void run() {
GroceryList2JFrame frame = new GroceryList2JFrame();
frame.setVisible(true);
}
});
}
}
3) When building the form using NetBeans, it already added an event handler method and registered it for the add button, but it was omitted for the remove button. If you look around line 70 of the GroceryList2JFrame class you will see the method call buttonAddGroceryItem.addActionListener()... I have added a similar block to register a new method for the buttonRemoveGroceryItem. Place this block of code below the `buttonAddGroceryItem.addActionListener() code:
buttonRemoveGroceryItem.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
buttonRemoveGroceryItem.setText("Remove Grocery Item From Gocerylist");
buttonRemoveGroceryItem.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
buttonRemoveGroceryItemActionPerformed(evt);
}
});
Finally, you will find the existing method GroceryList2JFrame.buttonAddGroceryItemActionPerformed(), which was created by NetBeans. I have filled in the method, copying the contents from GroceryList2ActionLIstener and also added a method for the buttonRemoveGroceryItemActionPerformed(), both of which are shown below:
private void buttonAddGroceryItemActionPerformed(java.awt.event.ActionEvent evt) {
String groceryItem = jTextField1GroceryItem.getText();
String quantity = jTextField2Quantity.getText();
String unit = jComboBox1Unit.getSelectedItem().toString();
jTextArea1.append(groceryItem + " " + quantity + " " + unit + "\n" );
}
private void buttonRemoveGroceryItemActionPerformed(java.awt.event.ActionEvent evt){
String choice = jTextArea1.getSelectedText();
try {
jTextArea1.setText(jTextArea1.getText().replaceAll(choice, ""));
}
catch(Exception ex){
JOptionPane.showMessageDialog(this, "Please select a valid item from the grocery list before clicking to remove.",
"Invalid Item selected for removal", JOptionPane.ERROR_MESSAGE);
}
}
Once you have made these minor changes, your program should work as expected.
Good Luck!

Having trouble converting textfield to integer and more

a little information on my assignment:
Based on the Person class previously defined, design your own Java application that displays a form for a user to enter their name, year_of_birth and employment status. The provided data will be used to instantiate a Person object. The form should also include a JButton and a JTextField. When the user clicks on the JButton the application should display “Welcome [name]! You are [age] old. Time has been kind to you.”, where [name] and [age] are the current values of the name and age attributes of the Person object.
I am a little new to creating GUI's. I have used the jFrame design that allows me to create the design of the GUI. I am having trouble using that form to display the results. Specifically, having the button display the results, having there name stored in a variable once they type it in, and brining up a dialog box once the button is clicked with the message.
package my.userFormUI;
/**
*
* #author Randy
*/
public class userFormUI extends javax.swing.JFrame {
/**
* Creates new form userFormUI
*/
public userFormUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
int age;
int year;
public int getAge(int year_of_birth){//get year method
age = 2014 - year_of_birth;
return age;
}//end method
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jDialog1 = new javax.swing.JDialog();
jDialog2 = new javax.swing.JDialog();
jDialog3 = new javax.swing.JDialog();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
name = new javax.swing.JTextField();
year_of_birth = new javax.swing.JTextField();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jButton1 = new javax.swing.JButton();
javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
jDialog1.getContentPane().setLayout(jDialog1Layout);
jDialog1Layout.setHorizontalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog1Layout.setVerticalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane());
jDialog2.getContentPane().setLayout(jDialog2Layout);
jDialog2Layout.setHorizontalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog2Layout.setVerticalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jDialog3Layout = new javax.swing.GroupLayout(jDialog3.getContentPane());
jDialog3.getContentPane().setLayout(jDialog3Layout);
jDialog3Layout.setHorizontalGroup(
jDialog3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog3Layout.setVerticalGroup(
jDialog3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "User Information", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 12), new java.awt.Color(0, 0, 0))); // NOI18N
jLabel1.setText("NAME:");
jLabel2.setText("YEAR BORN:");
jLabel3.setText("EMPLOYMENT STATUS:");
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
year_of_birth.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
year_of_birthActionPerformed(evt);
}
});
jRadioButton1.setText("Employed");
jRadioButton2.setText("Unemployed");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButton2)
.addComponent(jRadioButton1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(year_of_birth, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(year_of_birth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jRadioButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jButton1.setText("SUBMIT");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(14, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(104, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
This is where my coding needs to begin.
private void year_of_birthActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int year = Integer.parseInt(year_of_birth.getText());
getAge(year);
}//attempted to convert a string to an integer here
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here
System.out.println("Welcome" + name + " ! You are " + getAge(year) + " old. Time has been kind to you.");
}//Code for button here
private void nameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}//name text field
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(userFormUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(userFormUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(userFormUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(userFormUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new userFormUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JDialog jDialog1;
private javax.swing.JDialog jDialog2;
private javax.swing.JDialog jDialog3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JTextField name;
private javax.swing.JTextField year_of_birth;
// End of variables declaration
}
Any help would be greatly appreciated. I am already past the due date and very confused on how coding for GUI's go.
There is whole lot of unnecessary code you have. you need to clean it up for example you have 3 dialog instances. you do not need them. coming to your question you need to write implementation like:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// This will display message
JOptionPane.showMessageDialog(this, "Welcome" + name.getText() + " ! You are " + getAge(Integer.parseInt(year_of_berth.getText())) + " old. Time has been kind to you.");
// here you need to write code to populate your Person Object.
}
Hope this helps
You don't need a event for every textField. This:
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
year_of_birth.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
year_of_birthActionPerformed(evt);
}
});
I wipe this fragment of code.
You only need an event when the user click the button, therefore this event what you'll need.
Instead of the methods nameActionPerformed() and year_of_birthActionPerformed(), I would create a getName() and getYearOfBirth() methods.
private String getName(){
return name.getText();
}
private int getYearOfBirth(){
return Integer.parseInt(year_of_birth.getText());
}
Then, in the method of button event:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String name = getName();
int year = getYearOfBirth();
System.out.println("Welcome" + name + " ! You are " + getAge(year) + " old. Time has been kind to you.");
}

action when component state changed

I have a series of radio buttons generated as an array and displayed in a jPanel.
I want a series of checkboxes in a second panel to be enbled when the radio buttons are in output state but not in the input (input or output are the radio choices).
I want to call the checking state method whenever any of the radiobuttons states change but don't know how to do this as they are created in an array.
Currently the method is called only when the radio button panel is actually clicked.
package my.ArduinoGUI;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
public class ArduinoGUI extends javax.swing.JFrame {
public ArduinoGUI() {
initCustomComponents();
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() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
digitalPinPanel = new javax.swing.JPanel(new GridLayout(0, 3));
jPanel3 = new javax.swing.JPanel(new GridLayout(0, 1));
jPanel2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Outputs"));
jPanel1.setName("Outputs"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 209, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 106, Short.MAX_VALUE)
);
digitalPinPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Digital Pin State"));
digitalPinPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
digitalPinPanelMouseReleased(evt);
}
});
digitalPinLabelArray = new javax.swing.JLabel[digitalPinTotal];
digitalPinRadioButtonArray = new javax.swing.JRadioButton[digitalPinTotal][2];
digitalPinGroupArray = new javax.swing.ButtonGroup[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinGroupArray[x] = new javax.swing.ButtonGroup(); // populate button group
digitalPinLabelArray[x] = new javax.swing.JLabel(); // populate label array
digitalPinLabelArray[x].setText("Pin " + (x +2));
digitalPinPanel.add(digitalPinLabelArray[x]); // add label to panel
for(int y = 0; y < 2; y++){
digitalPinRadioButtonArray[x][y] = new javax.swing.JRadioButton(); // populate radio button array
if (y == 0) {digitalPinRadioButtonArray[x][y].setText("Input");}
if (y == 1) {digitalPinRadioButtonArray[x][y].setText("Output"); digitalPinRadioButtonArray[x][y].setSelected(true);
}
digitalPinGroupArray[x].add(digitalPinRadioButtonArray[x][y]); // assign radio buttons to group
digitalPinPanel.add(digitalPinRadioButtonArray[x][y]); // add buttons to panel
}
}
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Generated Boxes"));
digitalPinOutputArray = new javax.swing.JCheckBox[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinOutputArray[x] = new javax.swing.JCheckBox();
digitalPinOutputArray[x].setText("Output Pin " + (x+2));
jPanel3.add(digitalPinOutputArray[x]);
}
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Analog Pin State"));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 126, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, 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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
digitalPinPanel.getAccessibleContext().setAccessibleName("DigitalPins");
pack();
}// </editor-fold>
private void digitalPinPanelMouseReleased(java.awt.event.MouseEvent evt) {
// if output selected enable checkbox otherwise disable it
for (int x = 0; x < digitalPinTotal; x++) {
if (digitalPinRadioButtonArray[x][0].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(false);
}
if (digitalPinRadioButtonArray[x][1].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(true);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.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 ArduinoGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel digitalPinPanel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration
private int digitalPinTotal = 12;
private int analogPinTotal = 8;
private javax.swing.JCheckBox[] digitalPinOutputArray;
private javax.swing.JRadioButton[][] digitalPinRadioButtonArray;
private javax.swing.ButtonGroup[] digitalPinGroupArray;
private javax.swing.JLabel[] digitalPinLabelArray;
private void initCustomComponents() {
//throw new UnsupportedOperationException("Not yet implemented");
// create checkbox array
}
}
digitalPinRadioButtonArray[x][y].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Output"))
{
digitalPinOutputArray[2].setSelected(true);
}
}
});
try this

implementing a class in class

I am trying to implement a class in a class in JAVA, like this
package test;
import java.awt.event.*;
import javax.swing.*;
/**
*
* #author jackandjill
*/
public class Summingup extends JFrame {
/**
* Creates new form Summingup
*/
public Summingup() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
input1_tb = new javax.swing.JTextField();
calculate_btn = new javax.swing.JButton();
result_lbl = new javax.swing.JLabel();
input2_tb = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Input 1");
jLabel2.setText("Input 2");
calculate_btn.setText("SUM");
result_lbl.setText("RESULT DISPLAYED HERE!");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(input1_tb))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(result_lbl))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(input2_tb)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(calculate_btn)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(calculate_btn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(input1_tb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(input2_tb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
.addComponent(result_lbl)
.addContainerGap())
);
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()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, 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(Summingup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Summingup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Summingup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Summingup.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 Summingup().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton calculate_btn;
private javax.swing.JTextField input1_tb;
private javax.swing.JTextField input2_tb;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel result_lbl;
// End of variables declaration
}
class InvalidValueException implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
try
{
if(ae.getSource() ==calculate_btn)
{
String input_1 = input1_tb.getText();
String input_2 = input2_tb.getText();
checkBlanklnput(input_1,input_2);
validateInput(Integer.parseInt(input_1),Integer.parseInt(input_2));
result_lbl.setText(calculate(Integer.parseInt(input_1),Integer.parseInt(input_2)));
}
}
catch (NumberFormatException excep)
{
result_lbl.setText("Invalid number");
}
catch (InvalidInputException excep)
{
result_lbl.setText(excep.getMessage());
}
catch (BlankInputException excep)
{
result_lbl.setText(excep.getMessage());
}
}
public void checkBlanklnput(String input1,String input2) throws BlanklnputException
{
if (input1.length() == 0 ||input2.length() == 0) throw new BlanklnputException();
}
public void validateInput(int input1 , int input2) throws InvalidInputException
{
if (input1 + input2 > 100 )
throw new InvalidInputException();
}
public String calculate(int input1, int input2)
{
String res = "";
while (true)
{
res = Integer.toString(input1 + input2);
break;
}
return res;
}
}
class InvalidInputException extends Exception {
public InvalidInputException() {
super("Invalid number");
}
}
class BlankInputException extends Exception {
public BlankInputException() {
super("Input cannot be blank");
}
}
So this class is also throwing lot of exceptions and catching them. But the only problem is the JForm controls are not being recognised in the InvalidValueException class.
Not sure how to open those controls to this class.
Another issue that I am facing is my validateInput is checking for maximum sum but I want to check for IF any alphabets other than numbers are entered in the textboxes.
This is what my GUI looks like
You might compare your implementation to the working example shown here. It uses JFormattedTextField to enforce numeric input, as well as a PropertyChangeListener & FocusListener to update the sum.
As an aside, you should study layouts before relying too much on a GUI editor. See also Nested Classes.
Addendum: BlankInputException was misspelled, and your (oddly named) ActionListener was unused. You should be able to initialize it using a custom code property.
calculate_btn.addActionListener(new InvalidValueException());

Categories

Resources