Getting data from JSpinner and store it into an Array - java

I am currently having another problem, this time with JSpinners. I want to add dynamically JSpinners on the screen by right click, via the add button. After I add them, I want them to be inserted in an array of JSpinners and then the data from the JSpinners to be stored into a Date ArrayList. So far I am facing this problem:
If I add a new JSpinner the Date Array does not get automatically the Date from the second JSpinner or third or so on. It only gets the data from the first JSpinner.
I am really lost here. Appreciate any help here. Thanks and best regards
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import java.text.SimpleDateFormat;
public class TestingGround
{
Toolkit toolkit;
JFrame frame;
JPopupMenu menu;
Calendar calendar1, calendar2;
Date startDate, saveThisDate;
String stringStoredInitialRequestDate;
ArrayList <Date> dateArray; // array to store the dates from the request date
JSpinner spinner;
ArrayList <JSpinner> spinnerArray;
SpinnerModel model1;
int countAddClicks;
int val1;
public TestingGround()
{
frame = new JFrame("Testing ground area");
centerToScreen();
menu = new JPopupMenu();
JMenuItem addRow = new JMenuItem("Add ComboBox");
JMenuItem removeRow = new JMenuItem("Remove ComboBox");
JPanel panel = new JPanel();
JPanel mainGridPanel = new JPanel();
mainGridPanel.setLayout(new GridLayout(0,2));
mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(mainGridPanel);
// -------------------------------------------
dateArray = new <Date> ArrayList(); // array used to store the initial request dates
spinnerArray = new <JSpinner> ArrayList();
JButton saveDataButton = new JButton("save state");
countAddClicks =0;
val1 = -1;
panel.add(saveDataButton);
// ACTION LISTENERS
addRow.addActionListener(new ActionListener(){ // Right click to add JComboBoxes to the screen
public void actionPerformed(ActionEvent event) {
System.out.println("Starting click is: " + countAddClicks);
// JSPINNER 1
calendar1 = Calendar.getInstance();
Date now = calendar1.getTime();
calendar1.add(Calendar.YEAR, -10);
Date startDate = calendar1.getTime();
calendar1.add(Calendar.YEAR, 20);
Date endDate = calendar1.getTime();
model1 = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);
spinner = new JSpinner(model1); // creating Visual Spinner
String format = "dd MMM yy"; // formatting Visual Spinner 1
JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, format);
spinner.setEditor(editor); // applying the formatting to the visual spinner
spinnerArray.add(countAddClicks,spinner); // adds the spinner to the array of spinners
/*
model1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
changedDate = ((SpinnerDateModel) e.getSource()).getDate();
}
});
*/
saveThisDate = now;
dateArray.add(countAddClicks, saveThisDate); // add to the DATE array the new date (in the correct slot, going side by side with the other array);
countAddClicks++;
System.out.println("After click is: " + countAddClicks);
mainGridPanel.add(spinner); // add the JTextField to the JPanel
mainGridPanel.repaint();
mainGridPanel.revalidate();
}
});
removeRow.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent event) {
countAddClicks--;
if (countAddClicks <0) {
countAddClicks = 0;
}
if (spinnerArray.size() > 0 & dateArray.size() >0 ) {
spinner = spinnerArray.remove(spinnerArray.size()-1);
mainGridPanel.remove(spinner);
}
System.out.println("After removal click is: " + countAddClicks);
mainGridPanel.revalidate();
mainGridPanel.repaint();
}
});
saveDataButton.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent e) {
dateArray.clear();
for (int i=0; i< spinnerArray.size(); i++) {
JSpinner tempSpinner = spinnerArray.get(i); // creating a temporary spinner
calendar2 = Calendar.getInstance(); // creating a temporary calendar
Date now2 = calendar2.getTime();
calendar1.add(Calendar.YEAR, -50);
Date startDate2 = calendar2.getTime();
calendar2.add(Calendar.YEAR, 50);
Date endDate2 = calendar2.getTime();
SpinnerModel model2 = new SpinnerDateModel(now2, startDate2, endDate2, Calendar.YEAR);
tempSpinner.setModel(model2); // setting up a temporary spinnerModel and adding it to this instance of JSpinner
model2.addChangeListener(new ChangeListener() { // adding a listener to this model2
public void stateChanged(ChangeEvent e) {
saveThisDate = ((SpinnerDateModel) e.getSource()).getDate(); // checking for user input
System.out.println(saveThisDate); // for testing purpose it is showing that it detects the change
}
});
dateArray.add(saveThisDate); // add to the DATE array the new date (in the correct slot, going side by side with the other array);
}
// Only for checking purpose if the arrays are the correct sizes
System.out.println();
System.out.println("The size of the JSpinner Array is: " + spinnerArray.size() ); // showing correct
System.out.println("The content of the Date Array is: " + dateArray ); // checking the Date array. This is where data is not added, it is not working!
System.out.println("The size of the Date Array is: " + dateArray.size()); // showing correct
System.out.println();
}
});
// Cand dau click din butonul cel mai din dreapta (3) se deschide menium popup
frame.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event) {
if (event.getButton() == event.BUTTON3) {
menu.show(event.getComponent(), event.getX(),event.getY());
}
}
});
menu.add(addRow);
menu.add(removeRow);
frame.add(panel);
frame.setVisible(true);
}
public void centerToScreen()
{
frame.setSize(700,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("A Popup Menu");
toolkit = frame.getToolkit();
Dimension size = toolkit.getScreenSize();
frame.setLocation((size.width-frame.getWidth())/2, (size.height-frame.getHeight())/2);
}
public static void main(String[]args){
new TestingGround();
}
}

The source of the nulls in one of the ArrayLists: You're adding null values to the dateArray ArrayList
Date changedDate; // null
addRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// .....
dateArray.add(countAddClicks, changedDate); // changedDate is null
and you never change these values. Yes you assign a new Date instance to the changedDate variable, but the ArrayList is not holding variables, it's holding objects.
Note that here:
saveDataButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dateArray.clear();
for (int i = 0; i < spinnerArray.size(); i++) {
//.....
model2.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
changedDate = ((SpinnerDateModel) e.getSource()).getDate(); // **** (A) ****
System.out.println(changedDate);
}
});
// ...
}
}
});
again you change the Date instance held by the dateArray variable, but again, this has no effect on the nulls held by the ArrayList.
I suggest that you get rid of the dateArray ArrayList and instead extract the data from the JSpinners when needed (in a listener).

#Hovercraft Full Of Eels I have solved this problem!! I am so proud, now everything works. So it adds dynamically JSpinners and stores the dates in individual Array Slots. I will paste the code if anyone will search for something similar so they can use it as a reference. Thanks again
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import java.text.SimpleDateFormat;
public class TestingGround {
Toolkit toolkit;
JFrame frame;
JPopupMenu menu;
Calendar calendar1, calendar2;
Date startDate, saveThisDate;
ArrayList<Date> dateArray; // array to store the dates from the request date
JSpinner spinner;
ArrayList<JSpinner> spinnerArray;
SpinnerModel model1;
JPanel mainGridPanel;
int countAddClicks;
public TestingGround() {
frame = new JFrame("Testing ground area");
centerToScreen();
menu = new JPopupMenu();
JMenuItem addRow = new JMenuItem("Add ComboBox");
JMenuItem removeRow = new JMenuItem("Remove ComboBox");
JPanel panel = new JPanel();
mainGridPanel = new JPanel();
mainGridPanel.setLayout(new GridLayout(0, 2));
mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(mainGridPanel);
// -------------------------------------------
dateArray = new <Date>ArrayList(); // array used to store the initial
// request dates
spinnerArray = new <JSpinner>ArrayList();
JButton saveDataButton = new JButton("save state");
countAddClicks = 0;
panel.add(saveDataButton);
// ACTION LISTENERS
addRow.addActionListener(new ActionListener() { // Right click to add
// JComboBoxes to the
// screen
public void actionPerformed(ActionEvent event) {
System.out.println("Starting click is: " + countAddClicks);
// JSPINNER 1
calendar1 = Calendar.getInstance();
Date now = calendar1.getTime();
calendar1.add(Calendar.YEAR, -10);
Date startDate = calendar1.getTime();
calendar1.add(Calendar.YEAR, 20);
Date endDate = calendar1.getTime();
model1 = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);
spinner = new JSpinner(model1); // creating Visual Spinner
String format = "dd MMM yy"; // formatting Visual Spinner 1
JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, format);
spinner.setEditor(editor); // applying the formatting to the
// visual spinner
spinnerArray.add(countAddClicks, spinner); // adds the spinner
// to the array of
// spinners
saveThisDate = now;
dateArray.add(countAddClicks, saveThisDate); // add to the DATE
// array the new
// date (in the
// correct slot,
// going side by
// side with the
// other array);
countAddClicks++;
System.out.println("After click is: " + countAddClicks);
mainGridPanel.add(spinner); // add the JTextField to the JPanel
mainGridPanel.repaint();
mainGridPanel.revalidate();
}
});
removeRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
countAddClicks--;
if (countAddClicks < 0) {
countAddClicks = 0;
}
if (spinnerArray.size() > 0 & dateArray.size() > 0) {
spinner = spinnerArray.remove(spinnerArray.size() - 1);
dateArray.remove(dateArray.size() - 1);
mainGridPanel.remove(spinner);
}
System.out.println("After removal click is: " + countAddClicks);
mainGridPanel.revalidate();
mainGridPanel.repaint();
}
});
saveDataButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dateArray.clear();
for (int i = 0; i < spinnerArray.size(); i++) {
JSpinner tempSpinner = new JSpinner(); // creating a
// temporary spinner
calendar2 = Calendar.getInstance(); // creating a temporary
// calendar
Date now2 = calendar2.getTime();
calendar2.add(Calendar.YEAR, -50);
Date startDate2 = calendar2.getTime();
calendar2.add(Calendar.YEAR, 50);
Date endDate2 = calendar2.getTime();
SpinnerModel model2 = new SpinnerDateModel(now2, startDate2, endDate2, Calendar.YEAR);
tempSpinner.setModel(model2); // setting up a temporary
// spinnerModel and adding
// it to this instance of
// JSpinner
model2.addChangeListener(new ChangeListener() { // adding a
// listener
// to this
// model2
public void stateChanged(ChangeEvent e) {
saveThisDate = ((SpinnerDateModel) e.getSource()).getDate(); // checking
// for
// user
// input
System.out.println(saveThisDate); // for testing
// purpose it is
// showing that
// it detects
// the change
}
});
saveThisDate = (Date) spinnerArray.get(i).getValue();
System.out.println("Content of the Spinner Array is: " + spinnerArray.get(i).getValue());
dateArray.add(saveThisDate); // add to the DATE array the
// new date (in the correct
// slot, going side by side
// with the other array);
}
// Only for checking purpose if the arrays are the correct sizes
System.out.println();
System.out.println("The size of the JSpinner Array is: " + spinnerArray.size()); // showing
// correct
System.out.println("The content of the Date Array is: " + dateArray); // checking
// the
// Date
// array.
// This
// is
// where
// data
// is
// not
// added,
// it
// is
// not
// working!
System.out.println("The size of the Date Array is: " + dateArray.size()); // showing
// correct
System.out.println();
}
});
// Cand dau click din butonul cel mai din dreapta (3) se deschide menium
// popup
frame.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event) {
if (event.getButton() == event.BUTTON3) {
menu.show(event.getComponent(), event.getX(), event.getY());
}
}
});
menu.add(addRow);
menu.add(removeRow);
frame.add(panel);
frame.setVisible(true);
}
public void centerToScreen() {
frame.setSize(700, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("A Popup Menu");
toolkit = frame.getToolkit();
Dimension size = toolkit.getScreenSize();
frame.setLocation((size.width - frame.getWidth()) / 2, (size.height - frame.getHeight()) / 2);
}
public static void main(String[] args) {
new TestingGround();
}
}

Related

How to move and change the size of a Jpanel rectangle?

I have a rectangle, and I am trying to grow it like a graph of some sorts, but it does not show it growing in real time, it just has a white screen then I see a rectangle. Any help would be appreciated, thanks. The code I am having a problem with is under the ¨Animates the bar¨ comment.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Main extends JPanel {
static String[] mainArr;
static int start;
static boolean done = false;
static double datapoint1;
static double datapoint2;
static int jPlaceholder;
public static void main(String[] args) throws Exception {
// Creating the window
JFrame panel = new JFrame();
panel.setSize(450,250);
// Creating the window that shows the animation
JFrame drawingFrame = new JFrame();
drawingFrame.setSize(450,250);
JPanel jp = new JPanel();
jp.setLayout(null);
jp.setBackground(Color.red);
drawingFrame.add(jp);
// Creating all the text fields
JTextField dataTypesTextField = new JTextField("This box is currently not in use. Please do not type anything into this box");
dataTypesTextField.setBounds(50,50, 400,30);
panel.add(dataTypesTextField);
JTextField yearStartTextField = new JTextField("Type in this box what year your data starts in:");
yearStartTextField.setBounds(50,100, 400,30);
panel.add(yearStartTextField);
JTextField yearEndTextField = new JTextField("Type in this box what year your data ends in:");
yearEndTextField.setBounds(50,150, 400,30);
panel.add(yearEndTextField);
// Creating the button to submit the data
JButton enterButton = new JButton("Enter");
enterButton.setBounds(50,200, 100, 30);
panel.add(enterButton);
// =================================== ActionListener for enter button ========================================
enterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (done==false) {
// Creating the variables to store the data the user just inputted
start = Integer.parseInt(yearStartTextField.getText());
int end = Integer.parseInt(yearEndTextField.getText());
mainArr = new String[end-start+1];
// Gets the data points
dataTypesTextField.setText("Datapoints you will use in order, space between each: ");
done = true;
} else {
// Getting all the data needed
mainArr = dataTypesTextField.getText().split(" ");
double[] datapoints = new double[mainArr.length];
for (int i=0; i<datapoints.length; i++) {
datapoints[i] = Double.parseDouble(mainArr[i]);
}
under here is where I had my problems I am pretty sure, but I could have screwed up somewhere else.
// Animates the bar
for (int i=0; i<datapoints.length-1; i++) {
// Getting all the datapoints
datapoint1 = datapoints[i];
datapoint2 = datapoints[i+1];
int j = 0;
while(j<50) {
j++;
int width = (int) (datapoint1+((datapoint2-datapoint1)/50)*j);
JPanel rectangle = new JPanel();
rectangle.setBackground(Color.black);
rectangle.setBounds(50, 50, width, 30);
jp.add(rectangle);
drawingFrame.setVisible(true);
rectangle.repaint();
System.out.println("The width is: "+width);
at first I thought it was because there was no pause between each ¨frame¨ but it still just shows a white screen, then it shows the rectangle.
try {
Thread.sleep(20);
} catch (Exception exp) {
}
}
}
}
}
});
// =====================================================================================================
// Finishes up both the windows
panel.setLayout(null);
panel.setVisible(true);
}
}

Display not Changing [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I am working on this program that calculates the Beats per Minute (BPM) when you click the button. When you click two times, it is supposed to display the current BPM, and display the new one with every click after that. What the problem is, though, is that the display isn't changing. What do I need to do?
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class BPM extends JPanel implements ActionListener {
JLabel label;
public String display;
public int bpm;
public int buttonPressed;
public int time1;
public int time2;
public int time3;
public int counter[];
public void addComponents(Container pane) {
JPanel buttons = new JPanel();
JButton bpmButton = new JButton("Click");
bpmButton.setSize(new Dimension(100, 50));
bpmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed++;
counter = new int[2];
if (buttonPressed == 1) {
counter[0] = (int)(System.currentTimeMillis());
} else if (buttonPressed == 2) {
counter[1] = (int)(System.currentTimeMillis());
calculateTimeBetweenClicks();
setTime();
} else {
counter[0] = counter[1];
counter[1] = (int)(System.currentTimeMillis());
calculateTimeBetweenClicks();
setTime();
}
}
});
display = "0";
label = new JLabel(display, SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(100.0f)); // original 45
pane.add(label, BorderLayout.PAGE_START);
pane.add(bpmButton, BorderLayout.CENTER);
}
// Calculates the difference between the two saved clicks
public void calculateTimeBetweenClicks() {
if (buttonPressed == 1) {
time1 = counter[0];
} else {
time1 = counter[0];
time2 = counter[1];
}
time3 = time2 - time1;
}
// Calculates the BPM and changes the display accordingly
public void setTime() {
bpm = 60000 / time3;
display = "" + bpm + "";
label.setText(display);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public static void createAndShowGUI() {
// Creates the window
JFrame frame = new JFrame("BPM Calculator");
frame.setPreferredSize(new Dimension(300, 200)); // original (250, 130)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Adds the components to the content pane
BPM window = new BPM();
window.addComponents(frame.getContentPane());
//Displays the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Turns off bold text
UIManager.put("swing.boldMetal", Boolean.FALSE);
// Allows the components to be used and interacted with
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The problem is in your addComponents method, you are creating a new array on each and every button click (so you end up with a new and empty array). This is throwing off your calculation. Simply move the instantiation of your array to somewhere outside of the ActionListener like this...
public void addComponents(Container pane) {
JPanel buttons = new JPanel();
counter = new int[2]; //Move this line to here...
JButton bpmButton = new JButton("Click");
bpmButton.setSize(new Dimension(100, 50));
bpmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed++;
if (buttonPressed == 1) {
counter[0] = (int)(System.currentTimeMillis());
} else if (buttonPressed == 2) {
counter[1] = (int)(System.currentTimeMillis());
calculateTimeBetweenClicks();
setTime();
} //Removed the else - see edit below :-)
}
});
Additional
Your code as-is seems to get a litle confused after the 2nd click (the first BPM calculation) as it seems to take that 2nd click as the first click of the next set of 2 clicks if you get what I mean. I'm not sure if this is intended behaviour, but if not, I would reset everything in the calculateTimeBetweenClicks method after you've calculated the correct bpm ready for a new set of 2 clicks...
// Calculates the difference between the two saved clicks
public void calculateTimeBetweenClicks() {
if (buttonPressed == 1) {
time1 = counter[0];
} else {
time1 = counter[0];
time2 = counter[1];
//Reset here ready for next 2 clicks...
counter[0]=0;
counter[1]=0;
buttonPressed = 0;
}
time3 = time2 - time1;
}

if statements,lables and combo boxes

Ok my code has to pick route combo box (check) display in label(check) have a return and single ticket combobox(check) need it to display text(check) my problem is it only prints text related to one of my statments hope someone can tell me how to fix my if statments. The lable changes on a button .It reads code by lable.So far it only prints 15 and wont print 20 unless i had another label but this wouldnt make sense for the program
package learning;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList.*;
import java.util.Arrays.*;
import java.util.List.*;
#SuppressWarnings("unused")
public class test {
String[] items = {"Tipperary_to_cork","Cork_to_Dublin","Limerick_to_Tipperary","Dublin_to_Cork"};
JComboBox c = new JComboBox(items);
JButton b = new JButton("From");
JLabel l = new JLabel();
String[] items2 = {"window","aisle"};
JComboBox m = new JComboBox(items2);
JButton n = new JButton("Seat");
JLabel o = new JLabel();
String[] items3 = {"Single","return"};
JComboBox x = new JComboBox(items3);
JButton y= new JButton("Ticket");
JLabel z = new JLabel("choose Ticket");
String[] items4 = {"1","2","3","4","5","6","7","8","9","10"};
JComboBox<?> xx = new JComboBox(items4);
JButton yy = new JButton("seat");
JLabel zz = new JLabel("Choose a seat");
JLabel hh = new JLabel("cost");
JButton ccc = new JButton("comfirm");
JLabel hhh = new JLabel("");{
}
public test(){
frame();
}
public void frame(){
JFrame wolf = new JFrame();//frame
wolf.setVisible(true);
wolf.setSize(350,350);
wolf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
JPanel p = new JPanel();
p.add(hh);
p.add(c);//
p.add(b);//
p.add(l);//lable1
p.add(m);//
p.add(n);//
p.add(o);//lable 2
p.add(x);//
p.add(y);//
p.add(z);//lable 2
p.add(xx);//
p.add(yy);//
p.add(zz);//lable 2
p.add(ccc);
p.add(hhh);
wolf.add(p);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = c.getSelectedItem().toString();
l.setText(s);
}
});
n.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = m.getSelectedItem().toString();
o.setText(s);
}
});
y.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = x.getSelectedItem().toString();
z.setText(s);
}
});
yy.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = xx.getSelectedItem().toString();
zz.setText(s);
}
});
}
{
if(l.getText().equals("Tipperary_to_cork")&&(z.getText().equals("single"))){
ccc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hh.setText("15"); //***
}});
if(l.getText().equals("Tipperary_to_cork")&&(z.getText().equals("return"))){
ccc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hh.setText("20"); //****
}
});
}}}
public static void main(String[]args){
new test();
}
}
You want to check "if some condition" when you click the button. So, start with one simple if statement inside one of the actionPerformed methods. You shouldn't add an action listener inside an if statement, you should always perform an action, and determine the event inside that action.
For example
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = c.getSelectedItem().toString();
if (s.equals("Tipperary to cork")) {
// TODO: do something
}
}
});
Original answer
These line just happen to work because you have if(false==false)
if(l.equals("Tipperary to cork")==(z.equals("single"))) { ... }
if(l.equals("Tipperary to cork")==(z.equals("return"))) { ... }
The reason they evaluate to false is because you are comparing a JLabel.equals(String). You should use l.getText().equals("text here"), but...
The problem is that you have those if statements inside the constructor for your class, meaning that they are the first thing that is evaluated in your code. You should move the corrected if statements into the ActionListeners for the respective buttons.
Additional note: You seem to want "Tipperary to cork" AND "single". In that case, use && in place of ==. Alternatively, you could do this (psuedocode intentional)
if "Tipperary to cork" {
if "single" { ... }
else if "return" { ... }
}
In reality, though, you should compare c.getSelectedItem().toString() instead of the text of the label, but that's your decision.

nullpointerexception thrown while fields are not null

Hello I have created a application with several buttons in it. but when I press a button I get the NullPointerException. The strange thing here is that nothing is empty ( null )
here a code example
public class MuseumPanel extends JPanel implements ActionListener {
private JTextField kaartnummer;
private JTextField uur, minuut;
private JButton aankomst, vertrek, overzicht, sluiting;
private int hour;
private int minute;
private final int REFRESH = 1000;
MuseumRegistratie museum;
public MuseumPanel(MuseumRegistratie museum) {
// zorg ervoor dat de huidige tijd wordt opgehaald.
javax.swing.Timer timer = new javax.swing.Timer(REFRESH, this);
timer.start();
kaartnummer = new JTextField(15);
uur = new JTextField(2);
minuut = new JTextField(2);
aankomst = new JButton("Komt binnen");
aankomst.addActionListener(this);
vertrek = new JButton("Vertrekt");
vertrek.addActionListener(this);
overzicht = new JButton("aantal aanwezig");
overzicht.addActionListener(this);
sluiting = new JButton("sluiting");
sluiting.addActionListener(this);
add(new JLabel("Kaartnummer"));
add(kaartnummer);
add(new JLabel("tijdstip van aankomst of vertrek "));
add(uur);
add(new JLabel(" uur en "));
add(minuut);
add(new JLabel(" minuten"));
add(aankomst);
add(vertrek);
add(overzicht);
add(sluiting);
}
#Override
public void actionPerformed(ActionEvent e) {
Calendar now = Calendar.getInstance();
hour = now.get(Calendar.HOUR_OF_DAY);
minute = now.get(Calendar.MINUTE);
uur.setText("" + hour);
minuut.setText("" + minute);
// aankomst
if(e.getSource() == aankomst) {
try {
museum.checkIn(kaartnummer.getText(), hour, minute);
} catch (NullPointerException ex) {
System.out.println("cardnumber: " + kaartnummer.getText() + " hour " + hour + " minute " + minute);
}
}
// vertrek
if(e.getSource() == vertrek) {
museum.checkOut(kaartnummer.getText(), hour, minute);
}
// overzicht
if(e.getSource() == overzicht) {
museum.getAantalAanwezig();
}
// sluiting
if(e.getSource() == sluiting) {
museum.sluitRegistratie();
}
}
}
When pressing this button for example I get the exception with every variable correctly.. Does anyone know how this appears and how to solve it?
Without further information I would assume that the museum object is null which would trigger the nullpointerexception when you try to call museum.checkIn.
Looking at the Code museum is definitely null. in the constructor you should include:
this.museum = museum;
Assuming the museum object you pass in is NOT null then everything else should work.
You don't seem to be assigning a value to museum in your constructor, yet you dereference it in a lot of places. You'd want to do this:
this.museum = museum;
somewhere in your constructor. Alternatively, rename the variable so you don't accidentally do museum = museum, which would have no effect.

Printing String of JList Selections with ListSelectionListener in Java

fairly new to java here. I'm writing a GUI program of which I want to be able to append the strings (rather than the index number) of selected list items to a text area using a JButton. I am unaware of which java method would allow me to do this. When I use the getSelectedIndex method, it only allows me to append the index number, rather than the string value of the list item to my text area. If it is still unclear what I am asking, here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class FantasyInterface extends JFrame implements ActionListener{
private JList list1;
private JList list2;
private JLabel runningbacks;
private JButton addPlayer1;
private JButton addPlayer2;
private JTextArea text;
String lineSeparator = System.getProperty("line.separator");
private String[] rbs = {"Matt Forte", "Arian Foster", "Maurice Jones-Drew", "Adrian Peterson", "Ray Rice"};
FantasyTeam team1 = new FantasyTeam(5);
FantasyTeam team2 = new FantasyTeam(5);
public FantasyInterface(){
super("Fantasy Football Simulator");
// Set up listsPanel
JPanel listsPanel = new JPanel();
runningbacks = new JLabel("Running Backs:");
listsPanel.add(runningbacks);
list1 = new JList(rbs);
list1.setVisibleRowCount(5);
list1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
listsPanel.add(list1);
addPlayer1 = new JButton("Add To Team 1");
listsPanel.add(addPlayer1);
list2 = new JList(rbs);
list2.setVisibleRowCount(5);
list2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
listsPanel.add(list2);
addPlayer2 = new JButton("Add To Team 2");
listsPanel.add(addPlayer2);
// Add formatted JPanels to Content Pane
getContentPane().add(listsPanel, BorderLayout.NORTH);
// Set up textPanel, where info will appear
JPanel textPanel = new JPanel();
text = new JTextArea(20, 20);
textPanel.add(text);
// Add formatted JPanels to Content Pane
getContentPane().add(text, BorderLayout.SOUTH);
ListSelectionListener listSelectionListener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent listSelectionEvent) {
//System.out.println("First index: " + listSelectionEvent.getFirstIndex());
//System.out.println(", Last index: " + listSelectionEvent.getLastIndex());
boolean adjust = listSelectionEvent.getValueIsAdjusting();
//System.out.println(", Adjusting? " + adjust);
if (!adjust) {
JList list = (JList) listSelectionEvent.getSource();
int selections[] = list.getSelectedIndices();
Object selectionValues[] = list.getSelectedValues();
for (int i = 0, n = selections.length; i < n; i++) {
if (i == 0) {
System.out.println(" Selections: ");
}
System.out.println(selections[i] + "/" + selectionValues[i] + " ");
}
}
}
};
list1.addListSelectionListener(listSelectionListener);
addPlayer1.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
Object srcObj = event.getSource();
if (srcObj == addPlayer1){
text.append(lineSeparator + list1.getSelectedIndex());
}
}
}
The last part,
if (srcObj == addPlayer1){
text.append(lineSeparator + list1.getSelectedIndex());
}
is where I am wondering if there is a method to get the selected index in string form. Thanks to anyone who helps!
Use:
if (!list1.isSelectionEmpty()) {
text.append(lineSeparator + list1.getModel().getElementAt(list1.getSelectedIndex()));
}

Categories