Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I declared my boolean variable, but it seems to be doing the opposite of what I want it to do. When I click on a button, it deletes itself, when the boolean variable was false. How could I fix it so that whenever I click on the 'delete' button is turns the 'deleteNow' variable to true? Because it seems that deleteNow is always true. Here is a snippet of my code:
public class deleteButton
{
public boolean deleteNow = false;
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
deleteNow = true;
}
}
ActionListener deleteButtonClicked = new ClickListener();
deleteButton.addActionListener(deleteButtonClicked);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
if (deleteNow = true)
{
JButton buttonThatWasClicked = (JButton) e.getSource();
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revalidate();
parent.repaint();
}
else
{
System.out.println("The button wasn't deleted");
}
}
}
}
if (deleteNow = true) needs to be changed to if (deleteNow == true)
= operator assigns the value true to the variable whereas == operator just performs the comparison.
the following line is your error:
if (deleteNow = true)
needs to be
if (deleteNow == true)
To make it work.
Instead of checking for equality, you do an assignment in your case, which will always result in the condition being true, so delete your button.
Since your code is pseudocode and invalid java, my guess is that the error #Darshan Mehta mentions is not the real problem.
From your code the real problem is that you have two event listeners operating on the same state. Then the result will depend on whether the first event listener has changed the state of the button before the other has a chance to read its value. It seems as if the simple logic here is that the event listeners are called in the order added. A quickfix would then be to simply reverse the order of the event listeners.
A better approach would be to not have to different event listeners operating on the same state. Combine them into one if they are really meant to operate in tandem - as they do here. Then you can more easily control the flow of operations.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
There is a status variable in a Java application that can be set to one of many statutes, depending on many conditions. The status field is a String. When a condition is met, the status should be returned immediately, as follows:
e.g
String status = "";
if (condition1) {
return "STATUS_1";
} else if (condition2) {
return "STATUS_2";
} else if (condition3) {
return "STATUS_3";
} else if (condition4) {
return "STATUS_4";
}
...
else if (condition10) {
return "STATUS_10";
}
I've considered which pattern would be best to make this code more SOLID... e.g. if a new condition is required then this class would need to edited to add the new condition, which would break the open / closed SOLID principle
I've looked at the Strategy Pattern, in particular "Replace Conditional Logic with Strategy", however that seems more appropriate when you want to decide on just one calculation / operation to use... My scenario does not seem to fit the Strategy Pattern as my logic determines the status, rather than determining which individual operation to execute - I need to run all the conditions until one is true
I wondered if the following pattern could work...
Have an interface as follows
public interace StatusCondition {
boolean condition(Context context);
String getStatus();
}
With an implementation as follows:
public class StatusAStatusCondition implements StatusCondition {
boolean condition(Context context){
return context.getValue1() == 0 && context.getValue2().equals("A");
}
String getStatus(){
return "STATUS_A";
}
}
This would allow a list of StatusCondition classes to be executed in order and return the status of the first StatusCondition where the condition() method returns true. e.g:
public String getStatus(List<StatusCondition> statusConditions) {
for (StatusCondition statusCondition : statusConditions) {
if (statusCondition.condition()) {
return statusCondition.getStatus();
}
}
return "";
}
usage:
List<StatusCondition> statusConditions = new ArrayList<>();
statusConditions.add(statusAStatusCondition);
statusConditions.add(statusBStatusCondition);
statusConditions.add(statusCStatusCondition);
statusConditions.add(statusDStatusCondition);
statusConditions.add(statusEStatusCondition);
statusConditions.add(statusFStatusCondition);
...
String status = getStatus(statusConditions);
To me this solves the open closed principle issue and also ensures the implementations are single responsibility... My question is, how could this pattern i've suggested be improved, or is there a pattern better suited to my scenario?
First, you are absolutely correct that the original if/else ladder violates the Open/Closed Principle. Second, converting the status value to an interface is exactly the right step to take, to move away from stringly-typed programming. Third, your solution is essentially the Chain of Responsibility Pattern. It's an excellent solution to this problem. In summary, your instincts are spot on.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
How to pass actual checkbox state (true/false) from GUI class to another class? I want to run some part of code only if checkbox in GUI is selected. I guess it has to be if statement (highlithed part below) but i cant get it working.
public class csvtoxls {
public static void main() throws IOException {
//here you enter the path to your directory.
//for example: Path workDir = Paths.get("C:\\Users\\Kamil\Desktop\\csvtoxlspython\\Nowy folder (2)")
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setDialogTitle("Wybierz folder do konwersji: ");
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setAcceptAllFileFilterUsed(false);
int returnValue = jfc.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
if (jfc.getSelectedFile().isDirectory()) {
System.out.println("You selected the directory: " + jfc.getSelectedFile());
String z;
//#SuppressWarnings("deprecation")
Path workDir = jfc.getSelectedFile().toPath();
System.out.println(workDir);
//Path workDir = FileSystems.getDefault(jfc.getCurrentDirectory()).jfc.getCurrentDirectory();
//Path workDir = Paths.get(gui.pickPath(jfc));
File dirg = jfc.getSelectedFile();
//String str = dirg.getPath();
// ************* CODE WITH ISSUE *************
if TextAreaLogProgram.checkbox.isSelected() {
try {
Thread.sleep(5000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
String str = dirg.getPath();
delfiles td = new delfiles();
td.deleteFiles(str + "/", ".csv");
System.out.println("SUCCESS!");
msgbox.infoBox("SUCCES!", "CSVtoXLS");
}
GUI class:
public class TextAreaLogProgram extends JFrame {
private JTextArea textArea;
private JButton buttonStart = new JButton("CONVERT");
private JButton buttonClear = new JButton("CLEAR");
private PrintStream standardOut;
public TextAreaLogProgram() {
super("CSVtoXLS");
JCheckBox checkbox = new JCheckBox();
add(checkbox);
checkbox.setText("Delete files");
checkbox.setSelected(true);
Your other class will need a method or constructor with a parameter to be able to accept the value from the other class
See Passing Information to a Method or a Constructor for more details
Other issues:
Your program structure needs to be redone completely. Right now your main method is much too large, meaning that you're doing too much within the static world and not using Java to its best OOPs advantage.
Before even thinking of creating the GUI, first create the non-GUI "model" classes that your program will need. Like all your classes, these should have minimal static fields and methods, and strive to follow object-oriented best practices
You've got a Thread.sleep within your GUI code, something that does not work well with Swing GUI's since this risks putting the entire GUI to sleep, making it non-responsive. If you want Swing delays, use a Swing Timer (google the excellent tutorial on this)
You're trying to check the checkbox as if it were a static field of the TextAreaLogProgram class. It's not a static field and in fact its not even a field of the class.
The fact that you're doing the above suggests that you would benefit greatly from studying introductory tutorials on Object-Oriented programming and Java -- you are putting the cart before the horse by trying to create a GUI before first understanding Java fundamentals. Again, you won't regret the effort expended doing this.
Whatever you do, don't make the JCheckBox a static field and try to access it this way. This will lead to spaghetti code and increased risk for bugs.
Instead, make it a non-static (instance) private field of the TextAreaLogProgram class, and give the class a getter method to allow other objects access to the JCheckgbox's state.
There's so much more that can be mentioned about your code and problem... but this will do for now.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
In my main class I want to check if there was a change by using a boolean variable:
public class Main {
private boolean change = false;
public boolean getChange() {
return change;
}
public void setChange(boolean change) {
this.change = change;
}
private void method1() {
// some command
setChange(true);
method1();
}
If I want to get this boolean value in my second class, I always get returned "false", no matter if my method1 ran or not.
public class BoolTest {
Main m = new Main();
System.out.println(m.getChange()); // returns "false"
}
You must have two instances of Main. Use the same one. Example:
Main m = new Main();
System.out.println(m.getChange());
m.setChange(true);
System.out.println(m.getChange());
You probably want to share the same instance over multiple classes. Pass the instance to the other classes and use them as expected.
This question already has answers here:
The final local variable cannot be assigned
(6 answers)
Closed 8 years ago.
Code:
final boolean saveedit = true;
btnSaveEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (saveedit) {
// save function
if (txtMessage.getText().length() != 0) {
message = txtMessage.getText();
}
// show popup
JOptionPane.showMessageDialog(frmEventsAndProperties,
"Your last message is: " + message, "Message",
JOptionPane.PLAIN_MESSAGE);
btnSaveEdit.setText("Edit");
txtMessage.setEnabled(false);
saveedit = false;
} else {
// edit function
}
}
});
Error:
'The final local variable saveedit cannot be assigned, since it is defined in an enclosing type'.
Question:
I have seen other solutions for similar same errors, yet there must be a simple way to implement it - probably as simple as defining something earlier or moving it around.
I would appreciate any help.
Wherenver you want to use a variable inside an inner class (here ActionListener), you have two choices (regarding how you want to use it, modify(mutate) or access):
Using the final keyword with a local variable (it is not recommended for your case, since you want to modify your variable inside the inner class, not access only)
Using a field vairable, that need not be final (it is recommended)
As I mentioned, the seconed solution is feasible for you, since you want to do saveedit = false; which is mutating.
I completely agree with sager89. But i want to add one thing here which is.
If the keyword final is used for an instance variable, Then the final variable can be assigned only once and at the time of declaration or you will have to assign it in each and every constructor once.
This question is not a duplicate, the answer is for anyone wondering to simply move
final boolean saveedit = true;
to inbetween these lines:
btnSaveEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
That way it is not defined in an enclosing type :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am having a problem of how to call a method once when the condition achieves many times! for example:
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened){
callAMethodOnce();// this method is called once even if the condition achieved again
}
}
Please help with that
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened){
if (!isAlreadyCalled){
callAMethodOnce();// this method is called once even if the condition achieved again
isAlreadyCalled = true;
}
}
}
boolean isHappendBefore = false;
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened && (! isHappendBefore) ){
isHappendBefore = true;
callAMethodOnce();// this method is called once even if the condition achieved again
}
}
You could simply set a flag. If you just need it to only happen once with each instance of the Activity then set a member variable.
public class MyActivity extends Activity
{
boolean itHappened = false;
...
public void onLocaitonChanged(Location location)
{
// this if statement may achieve the condition many times
if(somethingHappened && !itHappened)
{
callAMethodOnce();// this method is called once even if the condition achieved again
itHappened = true;
}
}
If you want it to only happen once ever in the life of the application then set that variable as a SharedPreference
set a class wide boolean
if(!hasRun){
callAMethodOnce();
hasRun = true;
}
Maybe I don't understand your question correctly but from your problem definition I would suggest using a boolean variable something like.
boolean run = false;
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened && run == false){
run = true;
callAMethodOnce();// this method is called once even if the condition achieved again
}
}
Once the code under if statement gets executed once run would be true and there won't be any subsequent calls to callAMethodOnce()