Locker Program... Displaying the method once a button is clicked - java

I am doing the 1000 locker program. I am having one problem though, the code functions and with system.out.println it will display how I want it to display but, in the text area it won't display. Please Help Me, and commenting would be a great help. Thanks in Advance!
String output = "";
int numOpen = 0;
String numCount = "";
(Above code is declared at top of program)
private int runLockers(int Lockers)
{
final int numLockers = Integer.valueOf(numLockerTextField.getText());
int numClosed = Integer.valueOf(numLockerTextField.getText());
boolean lockers[] = new boolean[numLockers+1];
for(int studentNum = 1; studentNum <= numLockers; studentNum++)
{
for(int locker = studentNum; locker <= numLockers; locker+=studentNum)
{
lockers[locker]=!lockers[locker];
}
}
for(int count=1; count <= numLockers; count++)
{
if(lockers[count])
{
numOpen++;
numCount+="Locker: "+count+"\n";
System.out.println("Open Lockers:" + numOpen);
System.out.println(numCount);
output+="Open Lockers:" + numOpen + numCount;
}
}
//outputTextArea.setText(output);
return(numOpen);
}
private void simulateBtnActionPerformed (ActionEvent event)
{
outputTextArea.setText(output);
outputTextArea.setText("There are "+ Integer.valueOf(numLockerTextField.getText()) +" lockers, and "+ runLockers(0) +" are left open.");
}
This is the sumulate button code. It is before the method:
simulateButton = new JButton(); //declaring my new JButton
simulateButton.setText("Simulate"); //setting the text of the JButton
simulateButton.setBounds(160,500,100,30); //setting the bounds to which the Button is set to; The int x&y also the width&height
contentPane.add(simulateButton); //adding label to contentPane so it will be visible to user
simulateButton.addActionListener // adding an interface used to listen for an action event
(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
simulateBtnActionPerformed(event);
}
} // referencing what action is to be perform when button is pressed
);
Here is an example of how it out prints :
Open Lockers:1
Locker: 1
Open Lockers:2
Locker: 1
Locker: 4
Open Lockers:3
Locker: 1
Locker: 4
Locker: 9
This is the only line that appears in text area:
outputTextArea.setText("There are "+ Integer.valueOf(numLockerTextField.getText()) +" lockers, and "+ runLockers(0) +" are left open.");
... which looks like
There are 1000 lockers, and 31 are left open.
This is what the text area SHOULD look like:
Open Lockers:1
Locker: 1
Open Lockers:2
Locker: 1
Locker: 4
Open Lockers:3
Locker: 1
Locker: 4
Locker: 9
(.... that goes to 1000)
There are 1000 lockers, and 31 are left open.

You're setting the text of outputTextArea to output and then immediately replacing that with other text (the "There are ..." string). You probably want to be appending strings instead of setting the text twice. Maybe something like this:
private void simulateBtnActionPerformed (ActionEvent event)
{
outputTextArea.setText(output
+ "\nThere are "+ Integer.valueOf(numLockerTextField.getText()) +" lockers, and "+ runLockers(0) +" are left open.");
}

Related

The text does not change from the first click on the button

I need that when I click on the button, the text in cenApple changes to i * 132, but when I click on it, countApple becomes 1 more, as it should be, and cenApple remains the same, but if I click on it again, cenApple already changes to i * 132.
View.OnClickListener appleListenerPlus = new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = Integer.parseInt(countApple.getText().toString());
countApple.setText(String.valueOf(i + 1));
i = i;
int k = (i * 132);
String a = (String.valueOf(k));
cenApple.setText(a + " money");
}
};
why do you assigning same value again in this line: i = i;. it will stay the same...
when you change text then you should read it again or at least update i value also
int i = Integer.parseInt(countApple.getText().toString());
i++; // increment in here
countApple.setText(String.valueOf(i));
// or just read updated value again
//i = Integer.parseInt(countApple.getText().toString());
int k = (i * 132);
String a = (String.valueOf(k));
cenApple.setText(a + " money");

How to return Int from ActionListener?

I created a little code with visual interface using JFrame... you can type in a date and hit the conformation button. The problem is that I can't return the values out of the ActionListener... cause its a void of cause, I also tried to declare the variables outside of the ActionListener, but I get an Error like not possible from inner function or so. Any Ideas?
Heres a part of my code and a screenshot:
DVDAddenButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//((DefaultListModel)Liste.getModel()).addElement();
String Mediumtitel = DVDTextfeld.getText();
int DVDAusleihdatumZahlTag = 0;
int DVDAusleihdatumZahlMonat = 0;
int DVDAusleihdatumZahlJahr = 0;
String DVDAusleihdatumStringTag = "";
String DVDAusleihdatumStringMonat = "";
String DVDAusleihdatumStringJahr = "";
DVDAusleihdatumStringTag = DVDAusleihdatumFeldTag.getText();
DVDAusleihdatumStringMonat = DVDAusleihdatumFeldMonat.getText();
DVDAusleihdatumStringJahr = DVDAusleihdatumFeldJahr.getText();
try{
DVDAusleihdatumZahlTag = Integer.parseInt(DVDAusleihdatumStringTag);
DVDAusleihdatumZahlMonat = Integer.parseInt(DVDAusleihdatumStringMonat);
DVDAusleihdatumZahlJahr = Integer.parseInt(DVDAusleihdatumStringJahr);
}
catch(NumberFormatException ex){}
if (DVDAusleihdatumZahlTag < 32 && DVDAusleihdatumZahlTag > 0 && DVDAusleihdatumZahlMonat < 13 && DVDAusleihdatumZahlMonat > 0 && DVDAusleihdatumZahlJahr < date.getJahr()+1){
model.addElement(Mediumtitel);
model.addElement("Ausgeliehen am: " + DVDAusleihdatumZahlTag + "." + DVDAusleihdatumZahlMonat + "." + DVDAusleihdatumZahlJahr);
model.addElement(" ");
DatumFehler.setVisible(false);
}
else{
DatumFehler.setVisible(true);
}
}
});
enter image description here
Sorry for messed up code..
You can make a new class, then create the class inside ActionListener, then your class stores the information. When you want to access it, just call it from the class.

JavaFX TextField listener

I need some help. I have an ArrayList of Textfields.
static List<TextField> lfLetters = new ArrayList<>();
And I want to check if the value has changed. And if it was I want to know which textfield it was. I know I can do this with a Listener but that only worked for a single one.
TextField textField = new TextField();
textField.textProperty().addListener((observable, oldValue, newValue) -> {
System.out.println("textfield changed from " + oldValue + " to " + newValue);
});
I want it to work on an Array and determine which textfield has changed.
Thanks in advance!
You can use ObservableList with appropriate extractor and add listener directly to list. This way it will be automatically watching changes in the specified properties of its elements. It is more convenient, than adding listener to each text field, but in this case you can't get old value:
ObservableList<TextField> oList =
FXCollections.observableArrayList(tf -> new Observable[]{tf.textProperty()});
oList.addListener((ListChangeListener.Change<? extends TextField> c) -> {
while (c.next()) {
if (c.wasUpdated()) {
for (int i = c.getFrom(); i < c.getTo(); ++i) {
System.out.println("Updated index: " + i + ", new value: " + c.getList().get(i).getText());
}
}
}
});
I was thinking that I will mark this quesiton as a duplicate, as you have a totally similar question here.
But in the end, you want to have the reference to the TextField also in the listener, so I will add an answer.
This snippet adds 10 TextField objects to the ArrayList and adds a listener to each.
for (int i = 0; i < 10; i++) {
TextField tf = new TextField();
final int index = i;
tf.textProperty().addListener((obs, oldVal, newVal) -> {
System.out.println("Text of Textfield on index " + index + " changed from " + oldVal
+ " to " + newVal);
});
lfLetters.add(tf);
}
Or if your ArrayList is already initialized, you can iterate through it simply:
lfLetters.forEach(tf -> {
tf.textProperty().addListener((obs, oldVal, newVal) -> {
System.out.println("Text of Textfield on index " + lfLetters.indexOf(tf) + " changed from " + oldVal
+ " to " + newVal);
});
});
Sample output
Text of Textfield on index 2 changed from InitialText - 2 to ModifiedText - 2
Text of Textfield on index 6 changed from InitialText - 6 to ModifiedText - 6

Return index of a clicked JButton in Java swing

I have the following Java code:
I have a for loop and I'm creating JButtons.
I would like to return the index of the clicked button.
So i use:
JButton jbtn = (JButton) e.getSource();
Is there any method that returns the JButton's index?
My code is as follows:
for (int button = 0 ; button <= ListofJButtons.size() - 1; button++) {
ListofJButtons.get(button).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("I clicked on button !");
JButton buttonSource = (JButton) e.getSource();
System.out.println( " sourceButton " + buttonSource.getIndex()); //is there any method like that in Java?
}
} );
}//for loop
Is it possible to get the Index of the clicked JButton?
thanks
There are several ways. The simplest would be to do:
for (int button = 0 ; button <= ListofJButtons.size() - 1; button++) {
final int index = button;
ListofJButtons.get(button).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Because index is final I can access it here and know the index
System.out.println("I clicked on button "+index+"!");
JButton buttonSource = (JButton) e.getSource();
System.out.println( " sourceButton " + buttonSource.getIndex()); //is there any method like that in Java?
}
} );
}//for loop
The other simplest way would be just to do ListofJButtons.indexOf(buttonSource).
I guess ListofJButtons is a java.util.List. If so you can use
JButton buttonSource = (JButton) e.getSource();
int index = ListofJButtons.indexOf(buttonSource);
From ActionEvent you can do getActionCommand or from button you can get the getText or getLabel. Since buttons do not have any property which gives them a index you can't get the index. Index in not defined for them.

Refreshing a label through jtextfield

i am developing a project to a class and i came up with a stand-still.
So, what i want to do is to refresh the label when the user presses enter in the textfield to verify the ID.
Here is my code to catch when "enter" key is pressed, it's an event of the textfield "txtNbi":
if (evt.getKeyCode() == 10) {
this.BI = txtNbi.getText();
String BIs[];
BIs = DadosAplicacao.getInstance().getBIs();
for (int i = 0; i < BIs.length; i++) {
System.out.println("BI: " + this.BI + "\nBIlista: " + BIs[i]);
if (this.BI.equals(BIs[i])) {
encontrou.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pt/estg/dint/imagens/Ok.png")));
this.repaint();
} else {
encontrou.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pt/estg/dint/imagens/Cross.png")));
this.repaint();
}
}
}
txtNbi = name of my textfield;
BIs = array of strings that get pre-inserted IDs from the 'DadosAplicacao' class;
encontrou = name of my label that receives the image as an icon
So here is my problem:
I have the following data:
- BIs[0] = 12345678
- BIs[1] = 87654321
- BIs[2] = 54321678
When i type in the first 2 the label doesn't change to the "Ok.png" icon, but when i type the last one the label changes his icon to "Ok.png"!
Can anyone help me fix this?
You need to use the DocumentListener class:
txtNbi.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent documentEvent) {
//add the code handling the different conditions here
}
});
you need a break after you found the typed ID
if(this.BI.equals(BIs[i]))
{
encontrou.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/pt/estg/dint/imagens/Ok.png")));
this.repaint();
break;
}

Categories