GUI construction error - java

I'm still fairly new to Java, and am not sure why I am getting an error when I compile (no errors show prior to that). The error is:
Exception in thread "main" java.lang.NullPointerException
at Lab10.<init>(Lab10.java:21)
at Lab10.main(Lab10.java:55)
I was assuming that is indicating that the array is null? I tried moving it before the constructor, and it came out with errors in whatever I did. There were hundreds of errors before I initialized it with just a space before I actually used the user input as the array. All I am trying to make is a simple GUI where if you click on the button "Add Course" it will prompt you to type in a course, and that will add to the JList. I would appreciate any input! Thank you!
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Lab10 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
int count = 0;
String subject;
private JList list;
private JButton button;
private JButton button2;
Scanner input = new Scanner(System.in);
String [] Courses;
#SuppressWarnings("unchecked")
public Lab10() {
JPanel p1 = new JPanel();
for (int j = 0 ; j < 100 ; j++) {
Courses[j] = " ";
}
p1.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
button = new JButton("Add Course");
button2 = new JButton("Close");
button.addActionListener(this);
button2.addActionListener(this);
add(button);
add(button2);
setLayout(new BorderLayout(10, 10));
list = new JList(Courses);
add(list, BorderLayout.CENTER);
add(p1, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Add Course")) {
System.out.println("Enter your new subject: ");
subject = input.next();
count++;
for (int i = 0 ; i <= count ; i++) {
if (Courses[i].equals(" ")) {
Courses[i] = subject;
}
}
}
else if (e.getActionCommand().equals("Close")) {
System.exit(0);
}
}
public static void main(String [] args) {
Lab10 frame = new Lab10();
frame.setTitle("Java");
frame.setSize(500, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Add this to the top of your constructor:
this.Courses = new String[100];
Even better, you should actually move that 100, and the 100 in your for loop condition, to something like:
private static final int ARRAY_SIZE = 100;
Then change the other instances of 100 to ARRAY_SIZE.
Also, note that the NullPointerException isn't happening when you compile; it's happening when you run the program.

Basically, you've declared an array called Courses but you've never initialised it...
String[] Courses;
#SuppressWarnings("unchecked")
public Lab10() {
JPanel p1 = new JPanel();
for(int j = 0; j < 100; j++){
Courses[j] = " ";
}
Make sure you allocate the required number of elements to the array before you try and use it, for example...
String[] Courses;
#SuppressWarnings("unchecked")
public Lab10() {
JPanel p1 = new JPanel();
Courses = new String[100];
for(int j = 0; j < Courses.length; j++){
Courses[j] = " ";
}
You may also wish to take a read through Code Conventions for the Java Programming Language, as it will make you code eaiser for others to read

Related

Create Text in JText Field that user can not edit in java

I am creating a game similar to the star wars game sabacc. I am trying to create a Jtextfield that has three card suites already on the screen. The user will press a button and depending on the button they press the card suit will change to a different suit. If they get three of the same suites they win. I am having trouble getting text onto the screen though. As of right now I keep getting an error saying non static method can not be referenced by a static content.
Here is my code for the main application :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CardApp extends JFrame implements ActionListener {
private JButton oneButton,
twoButton,
threeButton;
private int width = 25;
private int height = 15;
public CardApp() {
//JPanel boardPanel = new JPanel(new GridLayout(height,width));
JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
JTextField TextField = new JTextField(30);
Hand settingTheText = new Hand();
TextField.setText(settingTheText.ListOfCards());
oneButton = new JButton("1");
twoButton = new JButton("2");
threeButton = new JButton("3");
// Listen for events on each button
oneButton.addActionListener(this);
twoButton.addActionListener(this);
threeButton.addActionListener(this);
// Add each to the panel of buttons
buttonPanel.add(oneButton);
buttonPanel.add(twoButton);
buttonPanel.add(threeButton);
// Add everything to a main panel attached to the content pane
JPanel mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel);
mainPanel.add(TextField, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setTitle("Sabacc Example by Angela Rucci");
setSize(375, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
int pressed = 0;
if (e.getSource() == oneButton){
pressed = 1;}
if (e.getSource() == twoButton){
pressed = 2;}
if (e.getSource() == threeButton){
pressed = 3;}
Hand handObject = new Hand();
///This IS WHERE IM GETTING MY ERROR!//
String screenText = handObject.ListOfCards();
TextField.setText(screenText);
}
public static void main(String[] args) {
CardApp c = new CardApp();
}
}
This is the other file where i am getting my list of suits
package cardapp;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Hand {
String [] Suits = {"C", "H", "S", "D"};
String [] probability = {"C","H","R","D"};
Random randomInt = new Random ();
String RandomSuit;
String RandomShuffle;
String ThreeSuits;
String LeftSuit;
String MiddleSuit;
String RightSuit;
int pressed = 0;
public int Discards(int pressedNumber){
return pressed;
}
public void Randomizer (){
int RandomSuitNumber = randomInt.nextInt(4);//this is generator a random number
//------------------Decide what hand to randomize --------------------------//
if (pressed==1){
LeftSuit= Suits[RandomSuitNumber];
}
if (pressed==2){
MiddleSuit=Suits[RandomSuitNumber];
}
if (pressed==3){
RightSuit=Suits[RandomSuitNumber];
}
//----------------20% chance of new random set------------------------------------//
int ProabilityRandomNum = randomInt.nextInt(5);//this will create a random number for probability array
RandomShuffle= probability[ProabilityRandomNum];//this will pick a random letter in proability array
//------------If proability array equals R then change all of the suits----------//
if (RandomShuffle.equals("R")){
JOptionPane.showMessageDialog(null, "Randomized Hand!");
int leftNumber = randomInt.nextInt(4);
int middleNumber = randomInt.nextInt(4);
int rightNumber = randomInt.nextInt(4);
LeftSuit= Suits[leftNumber];
MiddleSuit= Suits[middleNumber];
RightSuit= Suits[rightNumber];}
ThreeSuits = (LeftSuit + MiddleSuit + RightSuit);
}
public String ListOfCards (){
return ThreeSuits;
}
public void GameOver(){
if (LeftSuit == MiddleSuit && MiddleSuit == RightSuit &&
RightSuit== LeftSuit){
JOptionPane.showMessageDialog(null, "WINNER!!");
}
}
}
The variables are local to the method. the JTextField TextField is visible to the CardApp() only. if you want it to be available to the whole class, put it as a private class member :
public class CardApp extends JFrame implements ActionListener {
private JButton oneButton,
twoButton,
threeButton;
private int width = 25;
private private int height = 15;
// available to all methods
// better naming convention was JTextfield tf = new JTextField(30);
// even stackoverflow thinks its a class name :)
// see the color highlighting
private JTextField TextField = new JTextField(30);
public CardApp() {
//JPanel boardPanel = new JPanel(new GridLayout(height,width));
JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
//JTextField TextField = new JTextField(30);
Hand settingTheText = new Hand();
TextField.setText(settingTheText.ListOfCards());
}
//
// code continues here ...
//
}

Taking values from JTextField created during runtime

I set up a small program that can create rows and columns at run time, its for a math class implementing sets, I already got the program to create the rows and columns but what I wanna do next is be able to get the values inside and then load another form of the same structure and get that forms values then add them and show them on a final form. Fairly new to the whole java thing, so if anyone could help it'd mean the world. Here's what I have so far..
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Matrice extends JFrame {
protected static final int PREF_W = 200;
protected static final int PREF_H = 200;
JPanel mainPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
};
public JComponent getMainComponent() {
return mainPanel;
}
public Matrice(){
int rows, columns, end;
String RI, CI;
RI = JOptionPane.showInputDialog(null, "How many rows: ");
rows = Integer.parseInt(RI);
CI = JOptionPane.showInputDialog(null, "How many columns: ");
columns = Integer.parseInt(CI);
end = rows * columns;
JPanel holder = new JPanel(new GridLayout(rows, columns));
holder.setVisible(true);
for(int i = 0; i < end; i ++){
holder.add(new JTextField("output"));
}
JPanel set = new JPanel(new GridLayout(1, 0));
JTextField r = new JTextField("rows");
JTextField c = new JTextField("columns");
set.add(r);
set.add(c);
set.add(new JButton("Set"));
mainPanel.add(set, BorderLayout.SOUTH);
mainPanel.add(holder, BorderLayout.NORTH);
}
private static void createAndShowGui() {
Matrice test = new Matrice();
JFrame frame = new JFrame("Matrice");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(test.getMainComponent());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
never mind the buttons and the pre-set TextField
Simple answer to your question is that you need to define a array of TextField after getting the size:
TextField[][] inputFields = new TextField[rows][columns];
now add the TextFields
getContentPane().setLayout(new GridLayout(rows, columns));
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
inputFields[i][j] = new TextField("output");
holder.add(inputFields[i][j]);
}
}
There might be syntax errors above as I am directly typing it here.
To get the text out of a JTextField call .getText() on the object. so r.getText();
An elegant way to get a number out of the field is to use Integer.parseInt(String)
so your call would be Integer.parseInt(r.getText()) Note that this may throw
NumberFormatException so you will have to catch the exception and maybe reprompt the user to enter a valid number.

simple GUI not showing up?

Ok so, when I run it, it works all fine but it just doesn't pop up with the answer.
What did I do wrong?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class AF implements ActionListener{
double length;
double width;
double answer;
JTextField twidth;
JTextField tlength;
void AFWindow() {
JFrame AFwindow = new JFrame();
JPanel pan2 = new JPanel(new GridBagLayout());
AFwindow.setVisible(true);
AFwindow.setSize(250, 150);
AFwindow.setResizable(false);
GridBagConstraints c = new GridBagConstraints();
AFwindow.add(pan2);
pan2.setBackground(Color.LIGHT_GRAY);
c.gridx = 0;
c.gridy = 5;
tlength = new JTextField();
tlength.setText(" Length ");
pan2.add(tlength, c);
c.gridx = 0;
c.gridy = 0;
twidth = new JTextField();
twidth.setText(" Width ");
pan2.add(twidth, c);
JButton Find = new JButton("Ok");
c.gridx = 0;
c.gridy = -5;
pan2.add(Find);
Find.addActionListener(this);
Find.setActionCommand("ok");
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("ok")){
try {
this.length = Double.parseDouble(tlength.getText());
this.width = Double.parseDouble(twidth.getText());
}
catch(NumberFormatException ex){
System.out.println("There was an issue!");
}
}
}
int area = (int) (length * width);
public void answer(){
JFrame answer = new JFrame();
answer.setVisible(true);
answer.setBackground(Color.yellow);
JPanel pan2 = new JPanel();
JLabel howanswer = new JLabel("Your answer is" + area + "We got this by multiplying the length and width");
pan2.add(howanswer);
}
}
That code has multiple issues. Forgot to document them, but look at this code for the beginnings of the fixes.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class AF implements ActionListener{
double length;
double width;
JTextField twidth;
JTextField tlength;
JFrame AFwindow;
void AFWindow() {
AFwindow = new JFrame();
JPanel pan2 = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
AFwindow.add(pan2);
pan2.setBackground(Color.LIGHT_GRAY);
pan2.setBorder(new EmptyBorder(100,100,100,100));
c.gridx = 0;
c.gridy = 5;
tlength = new JTextField();
tlength.setText(" Length ");
pan2.add(tlength, c);
c.gridx = 0;
c.gridy = 0;
twidth = new JTextField();
twidth.setText(" Width ");
pan2.add(twidth, c);
JButton Find = new JButton("Ok");
c.gridx = 0;
c.gridy = -5;
pan2.add(Find);
Find.addActionListener(this);
Find.setActionCommand("ok");
AFwindow.pack();
AFwindow.setLocationByPlatform(true);
AFwindow.setVisible(true);
}
int area;
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("ok")){
try {
this.length = Double.parseDouble(tlength.getText());
this.width = Double.parseDouble(twidth.getText());
area = (int) (length * width);
answer();
}
catch(NumberFormatException ex){
ex.printStackTrace();
// System.out.println("There was an issue!");
// Can you vague that up for me?!?!
JOptionPane.showMessageDialog(AFwindow, ex);
}
}
}
public void answer(){
JPanel pan2 = new JPanel();
JLabel howanswer = new JLabel("Your answer is " + area + " We got this by multiplying the length and width");
pan2.add(howanswer);
JOptionPane.showMessageDialog(AFwindow, pan2);
}
public static void main(String[] args) {
System.out.println("Hi!");
new AF().AFWindow();
}
}
Are you expecting the answer frame to pop up when you push the OK button? If so, you need to call the answer method:
if (e.getActionCommand().equalsIgnoreCase("ok")){
try {
this.length = Double.parseDouble(tlength.getText());
this.width = Double.parseDouble(twidth.getText());
answer(); // <--- This is missing
}
Also, some other things you need to do:
Generally, you should call JFrame.setVisible at the end of your GUI construction method, after you have added components to the frame. I have shown this in the example below, but you should move setVisible(..) to the bottom of the AFwindow() method as well.
When you do int area = (int) (length * width); outside of any method, this statement will be interpreted as an instance variable initialization and occur when you instantiate the AF object. And when the object is instantiated, you have not yet assigned any values to length and with. Hence, area will always be 0. Move that statement to the inside of the answer function instead.
You forgot to add the actual components to the frame in the answer method. Hence, when you set the frame to visible, only an empty frame will be displayed.
Here are examples of some suitable changes:
public void answer(){
int area = (int) (length * width); // <--- Move this inside answer method
JFrame answer = new JFrame();
answer.setBackground(Color.yellow);
JPanel pan2 = new JPanel();
JLabel howanswer = new JLabel("Your answer is" + area + "We got this by multiplying the length and width");
pan2.add(howanswer);
answer.add(pan2); // <--- Don't forget to add your components to the frame
answer.pack(); // <--- Resize the frame to a suitable size
answer.setVisible(true); // <--- Set the frame to visible AFTER you have added the components
}
This code works for me:
public class Test {
public static void main(String[] args){
JFrame test = new JFrame();
test.setVisible(true);
test.setSize(100,100);
test.setResizable(false);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I assume that you can try to reduce your code and try to find problem point such way. You can put some logging to ensure setVisible(true) was called. Also I recomend to use setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to terminate thread after exit GUI (if do not want to perform some post-exit actions).

Trouble with integer validation and showing users have entered invalid data

This is for a Java program I'm working on as part of a homework assignment. I don't want the work done for me, but I'm stuck. I'm fairly new to Java, and using NetBeans IDE 7.0.1.
I'm having difficulty with some exception handling when trying to validate user input. This program will log charitable donations from user input. However, I've not been successful in validating the donation amount text field input. If a user inputs text instead of numbers, I would like them to be notified that their input was invalid, and I'd like the exception handling to handle the error and carry on after the user fixes their entry. Any help is greatly appreciated.
Here is my code:
package donorgui;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;
public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;
//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;
// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 510;
//Constructor
public DonorGUI(){
// Set the title.
setTitle("Donor");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Add the panel to the content pane.
add(panel);
// Size and display the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
//The buildPanel method creates a panel containing other components.
private void buildPanel(){
// Create labels to display instructions.
JLabel message1 = new JLabel("Name of the Donor:");
JLabel message2 = new JLabel("Name of the Charity:");
JLabel message3 = new JLabel("Amount of the Pledge:");
//instantiate the results area
results = new JTextArea(25,60);
// Create text fields to receive user input
donorField = new JTextField(10);
charityField = new JTextField(10);
pledgeField = new JTextField(10);
//create the user buttons to cause action
entryButton = new JButton("Enter Donation.");
entryButton.addActionListener(new EntryButtonListener());
exitButton = new JButton("EXIT");
exitButton.addActionListener(new ExitButtonListener());
clearButton = new JButton ("Clear Fields");
clearButton.addActionListener(new ClearButtonListener());
// Create a panel.
panel = new JPanel();
//set the LayoutManager
panel.setLayout(new FlowLayout());
// Add the labels, text fields, and button to the panel.
panel.add(message1);
panel.add(donorField);
panel.add(message2);
panel.add(charityField);
panel.add(message3);
panel.add(pledgeField);
panel.add(results);
panel.add(entryButton);
panel.add(exitButton);
panel.add(clearButton);
}
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
donationAmt[i] = Double.parseDouble(pledgeField.getText());
results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
i++;
}
}
public boolean donationAmt(String amount) {
int i = 0;
try {
i = Integer.parseInt (amount);
return true;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid Input. Please enter a dollar amount");
return false;
}
}
private class ClearButtonListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
}
private class ExitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
/* Application method */
public static void main(String[] args){
DonorGUI rpc = new DonorGUI();
}
}
Here is my revised code. After some user input testing, I'm getting an exception when I use 100.00, 40.00, etc... instead of whole dollar amounts, such as 100, 40, etc.
Any thoughts?
package donorgui;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;
public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;
//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;
// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 550;
//Constructor
public DonorGUI(){
// Set the title.
setTitle("Donor");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Add the panel to the content pane.
add(panel);
// Size and display the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
//The buildPanel method creates a panel containing other components.
private void buildPanel(){
// Create labels to display instructions.
JLabel message1 = new JLabel("Name of the Donor:");
JLabel message2 = new JLabel("Name of the Charity:");
JLabel message3 = new JLabel("Amount of the Pledge:");
//instantiate the results area
results = new JTextArea(25,60);
// Create text fields to receive user input
donorField = new JTextField(10);
charityField = new JTextField(10);
pledgeField = new JTextField(10);
//create the user buttons to cause action
entryButton = new JButton("Enter Donation.");
entryButton.addActionListener(new EntryButtonListener());
exitButton = new JButton("EXIT");
exitButton.addActionListener(new ExitButtonListener());
clearButton = new JButton ("Clear Fields");
clearButton.addActionListener(new ClearButtonListener());
// Create a panel.
panel = new JPanel();
//set the LayoutManager
panel.setLayout(new FlowLayout());
// Add the labels, text fields, and button to the panel.
panel.add(message1);
panel.add(donorField);
panel.add(message2);
panel.add(charityField);
panel.add(message3);
panel.add(pledgeField);
panel.add(results);
panel.add(entryButton);
panel.add(exitButton);
panel.add(clearButton);
}
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
if (donationAmt(pledgeField.getText())) {
donationAmt[i] = Double.parseDouble(pledgeField.getText());
}
results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
i++;
}
}
public boolean donationAmt(String amount) {
if(amount==null || amount=="" || amount.length()<1){ //checking for empty field
JOptionPane.showMessageDialog(null, "Please enter a dollar amount");
return false;
}
for(int i = 0; i < amount.length(); i++){ //verifying dollar amount entered as number
if (!Character.isDigit(amount.charAt(i))){
JOptionPane.showMessageDialog(null, "Invalid input. Please enter a dollar amount");
return false;
}
}
return true;
}
private class ClearButtonListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
}
private class ExitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
/* Application method */
public static void main(String[] args){
DonorGUI rpc = new DonorGUI();
}
}
You can use InputVerifier, discussed here.
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
if(donationAmt(pledgeField.getText())){
donationAmt[i] = Double.parseDouble(pledgeField.getText());
results.append(donorName[i] + " " + charityName[i] + " " + donationAmt[i] + "\n ");
i++;
}
}
}
Something like this would work. This checks so that the amount is not empty and contains only digits based on your exisiting method.
public boolean donationAmt(String amount) {
if(amount==null || amount=="" || amount.length()<1){ //check so that the amount field is not empty, pherhaps you can add a check so the amound is not 0 :)
JOptionPane.showMessageDialog(null, "Invalid Input. The amount cannot be empty");
return false;
}
for(int i = 0; i < amount.length(); i++){ //loop thru the string and check so that each char is a digit
if (!Character.isDigit(amount.charAt(i))){
JOptionPane.showMessageDialog(null, "The amount can contain only numbers");
return false;
}
return true;
If you want to make sure that the amount is not 0, one approach would be to parse amount to int, and check so that parsedAmount<0. This should be done after it's verified that the amount is not empty and is only digits (e.i last:) ) to avoid NPE's and numberformatexception

Adding JPanels to JPanel array

I have declared an array:
private javax.swing.JPanel[] panelArray = new javax.swing.JPanel[3];
I also have 3 panels: panel0, panel1 and panel2. Can I add these panels to the array? i.e
panelArray[0] = panel0;
panelArray[1] = panel1;
panelArray[2] = panel2;
And then manipulate the arrays like this?
boolean[] myBools; .... then set them as true/false
for(int i=0; i<3; i++)
{
if(myBools[i])
panelArray[i].setVisible(true)
}
Because that does not work for me
On my side it's working fine, in this program :
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class MyPanel
{
private JPanel[] panelArray = new JPanel[3];
private boolean[] myBools = new boolean[]{false, false, false};
private int counter = 0;
private int prvPanelCounter = 0;
private Timer timer;
private ActionListener timerAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
counter++;
if (counter > 2)
counter = 0;
myBools[counter] = true;
for (int i = 0; i < 3; i++)
{
if (myBools[i])
{
panelArray[i].setVisible(myBools[i]);
panelArray[prvPanelCounter].setVisible(myBools[prvPanelCounter]);
myBools[i] = false;
prvPanelCounter = i;
break;
}
}
}
};
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Locate Mouse Position");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel0 = new JPanel();
panel0.setOpaque(true);
panel0.setBackground(Color.BLUE);
JPanel panel1 = new JPanel();
panel1.setOpaque(true);
panel1.setBackground(Color.RED);
JPanel panel2 = new JPanel();
panel2.setOpaque(true);
panel2.setBackground(Color.DARK_GRAY);
panelArray[0] = panel0;
panelArray[1] = panel1;
panelArray[2] = panel2;
JComponent contentPane = (JComponent) frame.getContentPane();
contentPane.setLayout(new GridLayout(0, 1));
frame.add(panel0);
frame.add(panel1);
frame.add(panel2);
panel0.setVisible(myBools[counter]);
panel1.setVisible(myBools[counter]);
panel2.setVisible(myBools[counter]);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
timer = new Timer(1000, timerAction);
timer.start();
}
public static void main(String\u005B\u005D args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new MyPanel().createAndDisplayGUI();
}
});
}
}
What you want to do can be done, but here's a few points to bear in mind:
Make sure you initialise the JPanels before referencing them.
The statement "panelArray[i].setVisible(true)" needs a semicolon after it.
None of these panels will be visible unless you add them to another component, such as a JFrame.
Rather than state javax.swing.JPanel, you could just import the JPanel at the top of the page and refer to it as simply JPanel.
Your "if" statement is unnecessary. Just do .setVisible(myBools[i]);
Hope these were of some help to you.
Yes, you can. Did you really not initialize the myBools array with new ?

Categories