Use result from if statement in another if statement [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 6 years ago.
Improve this question
I am writing a quiz app, where you get marks as you answer the correct questions and your score increases, and I have to use if statements. Please does any one know how to use a value in an if statement in another if statement! I'm kinda confused about it and its hooking me up at work here....Thanks for the help!... here is a little code example;
int x = 3;
String xy = Integer.toString(x);
int y = 0;
String yy = Integer.toString(y);
JButton one = new JButton ("Quest 1");
one.addActionListener (new ActionListener (){
public void actionPerformed(ActionEvent p) {
JFrame ex = new JFrame ();
ex.setTitle("Question 1);
ex.setSize(400, 400);
ex.setLayout(new FlowLayout());
ex.setBackground(Color.WHITE);
JLabel ey = new JLabel ("What is the capital of Japan?);
Font tan = new Font ("Script MT Bold", Font.BOLD, 18);
ey.setFont(tan);
ey.setForeground(Color.BLACK);
ex.add(ey, BorderLayout.NORTH);
JButton answ = new JButton("submit");
JTextField g = new JTextField (10);
g.setFont(tan);
String ans = "Tokyo";
String merit = "Correct";
String flop = "wrong";
String mer = merit + ans;
String flip = flop + ans;
answ.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent p) {
if (g.getText.equals("Tokyo") {
JOptionPane.showMessageDialog(null, mer);
one.setText(xy);
}
else {
JOptionPane.showMessageDialog(null,flip);
one.setText(yy);
}
//In my next Action Listener, I would love to
//pick the score from the previous listener....and add to the next score....
//So that we have something like ....
//x(updated from previous listener) + x
ex.add(g, BorderLayout.SOUTH);
}
});
}
});

The only problem I can guess at in the code supplied is that you're testing if a JTextField's text contains a specific String, "Tokyo" in your GUI creational code. This is code that runs at GUI creation and before the user has had any chance to enter data. To fix this, the if test should be within some listener, perhaps a JButton's ActionListener. Otherwise I have no idea what you mean by if within an if.
Edit
Regarding your new information:
I am writing a quiz app, where you get marks as you answer the correct questions and your score increases, and I have to use if statements.
You need to completely re-design your code as you're hard coding your code logic within the GUI, making for a very rigid, huge, and difficult to enhance program (as you're finding out) since the code logic must change as the state of the program changes.
Instead you should split out your program logic, the "model" from the GUI, the "view", and try to create them and test them independently, something similar to (or equal to) a "Model-View-Controller" or "MVC" program design. Start with the model, the "guts" of the program and create your non-GUI Question class, one with instance fields, methods, and any other supporting classes. Once this has been tested and debugged, then try to create a GUI or view class that can use this model and display its state. You might also want to create a "Controller" class with listeners that help connect the view to the model.
For example, if your quiz is to be a multiple-choice type of program, then consider:
A Question class that contains the question String, possible answer Strings and the correct answer String.
Give it a public boolean test(String testString) that returns true if the correct answer String is passed into it.
Allow the Question class to randomize the order of the possible answer Strings, likely held in an ArrayList.
Then create a Quiz class that holds an ArrayList of Questions.
Then create a GUI to display these.
I generally create GUI's that are geared to create JPanels, not JFrames for increased flexibility and then create the JFrame when needed.
Create a QuestionPanel that displays the question String and the randomized possible answer Strings.
Display the possible answers as JRadioButtons with a ButtonGroup to limit the selection to one.
etc....
You'll also want a class to read from a text file data for each question, and load that data into the Quiz class.
You'll also want a mechanism to grade.

Please make all required variables as class level variables instead of declaring it in actionlistner method. Class level variables will be visible in all methods so no need to pass those. Declare score variable as class level.
public class ClassTest {
int score=0;
public void acgionlistner1(Event ev)
{
if(ans.equals(userinput))
{
score++;
}
}
public void acgionlistner2(Event ev)
{
if(ans.equals(userinput))
{
score++;
}
}
.
.

Related

How to detect when a user presses a key outside of the app [duplicate]

This question already has answers here:
Java - checking if parseInt throws exception
(8 answers)
Closed 1 year ago.
So I tried to look a bit in forums and StackOverflow but nothing worked for me I need when enter is pressed to stop my code this is my code `
JFrame f;
JTextField I;
// JButton
JToggleButton b;
// label to display text
JLabel l;
f = new JFrame("AutoClicker");
i = new JTextField("100");
// create a label to display text
l = new JLabel("clicks/seconds");
// create a new buttons
b = new JToggleButton("Start");
// create a panel to add buttons
JPanel p = new JPanel();
// add buttons and textfield to panel
p.add(b);
p.add(i);
p.add(l);
// setbackground of panel
p.setBackground(Color.red);
// add panel to frame
f.add(p);
// set the size of frame
f.setSize(280, 80);
f.setVisible(true);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int jml = Integer.parseInt(i.getText());
if(jml < 50)
{
jml = 50;
}
AutoClicker(jml);
}
});
}
static void AutoClicker(int jml)
{
while(true)
{
try{
Robot r = new Robot();
int button = InputEvent.BUTTON1_DOWN_MASK;
r.mousePress(button);
Thread.sleep(jml);
r.mouseRelease(button);
Thread.sleep(jml);
}
catch(Exception e){
e.printStackTrace();
System.out.println("not good");
}
}
}
}`
I tried to add a KeyListener but it did not work.
I don't understand why it doesn't work so if you can just help me know why it doesn't work it would be much apreciated.
KeyListener isn't going to solve the problem of the fact that you are simply not handling the potential of Integer.parseInt to throw an exception - I mean, how can it convert "" or "This is not a number" to an int. In those cases it throws an exception
The JavaDocs clearly state
Throws:NumberFormatException - if the string does not contain a
parsable integer.
Go back and have a look at the original error you were getting from your previous question on this exact topic
java.lang.NumberFormatException: For input string: "Enter"
It's telling you exactly what the problem is - the text "Enter" can not be converted to an int value.
YOU have to handle this possibility. No offence, but this is honestly basic Java 101. See Catching and Handling Exceptions
Another option which "might" help is to use a formatted text field
You also don't seem to have a firm grip on the concept of what a "event driven environment" is or what the potential risk of what doing something like while (true) will do if executed within the context of the Event Dispatching Thread. This makes me think you've got yourself in over all head.
You're going to want to learn about Concurrency in Swing as AutoClicker should never be called within the context of the Event Dispatching Thread, which is going to lead you another area of complexity, concurrency and all the joys that brings.
Updated
Wow, you changed the title. Maybe a better description of the problem you're trying to solve would have a gotten a better answer. In short, you can't, not natively in Java anyway. The only way you can detect keyboard input out side of the app is using native integration, JNA/JNI. Plenty of examples about, for example

First applet - Null Point Exception in browser? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
I know this question is probably asked a TON, but from what I understand it's pretty situational and nothing I've tried so far has worked.
I'm making a basic applet that simply needs to have an image and a simple function. Mine in particular gives a random quote of Dwight from "The Office" when a user hits the button (Later on their text input will have some sort of say in how the quote is determined).
My problem here though is the applet runs in my JGrasp, but doesn't run in the browser from a local file. The code is basically complete, but can anyone help me pinpoint where it's going wrong? I just don't really understand how it can work in my applet viewer but not my browser, it's odd. I tried switching over my SWING to AWT, but it didn't seem to help, so I used my older version.
I'm posting my code, HTML file and results from the java console when the applet failed. at the moment I'm still trying to figure out what exactly to print from the java console, but figured I'd post this regardless in the meantime. Thanks for any and all help!
// Imports
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
import java
public class AskDwight extends JApplet {
// initialize GUI components
private JPanel panel;
private JLabel questionLabel, responseLabel;
private JButton askButton;
private JTextField questionField;
// Constructor
public void init()
{
buildGUI();
// Add panel to content pane
add(panel);
}
// buildPanel method adds components to GUI
private void buildGUI()
{
questionLabel = new JLabel("Question :");
questionField = new JTextField(35);
askButton = new JButton("Ask!");
java.net.URL imageURL = AskDwight.class.getResource("dwight.PNG");
JLabel imageLabel = new JLabel();
imageLabel.setIcon(new ImageIcon(imageURL));
askButton.setPreferredSize(new Dimension(350, 30));
// Response label builder
responseLabel = new JLabel("");
responseLabel.setPreferredSize(new Dimension(350, 200));
responseLabel.setHorizontalAlignment(JLabel.CENTER);
responseLabel.setVerticalAlignment(JLabel.CENTER);
// Add an action listener to the button
askButton.addActionListener(new AskButtonListener());
// Create panels
panel = new JPanel(new FlowLayout());
// Add components to the panels
panel.add(questionLabel);
panel.add(questionField);
panel.add(askButton);
panel.add(imageLabel);
panel.add(responseLabel);
}
// Action Listener class for the ask button
private class AskButtonListener implements ActionListener
{
// Ask method exectutes when the button is clicked
public void actionPerformed(ActionEvent e)
{
String inputQuestion; // Holds user's input question
String[] response = new String[10]; // Holds Dwight's random responses
String randomResponse;
// Dwight Responses - contained in String array
response[0] = "<html>Fact: You can use the molten goose grease and save "
+ "it in the refrigerator.</html>";
response[1] = "<html>False: Bears do not eat beats.</html>";
response[2] = "<html>Question: Do you ever stop asking stupid questions?</html>";
response[3] = "<html>Fact: Bears can climb faster than they can run.</html>";
response[4] = "<html>What are you even asking? I order you to Cease and "
+ "desist right now, as third in command</html>.";
response[5] = "<html>You think that's funny? Millions suffer every year at "
+ "the expense of your jokes.</html>.";
response[6] = "<html>MICHAEL!";
response[7] = "<html>A day on Schrute's beet farm would shut your mouth.</html>";
response[8] = "<html>False: Nothing you say is important.</html>";
response[9] = "<html>I always keep concealed pepper spray just for an "
+ "occasion such as this.</html>";
// inputQuestion gets the user's entered string
inputQuestion = questionField.getText();
// When button is pressed, the following code will select
// a random response from the string array
Random rand = new Random();
randomResponse = response [rand.nextInt(response.length)];
responseLabel.setText(randomResponse);
}
}
}
Here's the HTML code
<HTML>
<HEAD>
<TITLE>Ask Dwight Schrute</TITLE>
</HEAD>
<BODY>
<applet code="AskDwight.class" width="420" height ="500">
</applet>
</BODY>
</HTML>
You've specified the programs class, but not provide the applications archive, this means that any call to Class#getResource is going to fail as the applet's classloader has no concept about where those resources might be stored, instead, consider trying something like...
<applet code = 'AskDwight'
archive = 'AskDwight.jar'
width = 420
height = 500>
</applet>
Assuming you've built the project into a Jar and have it deployed on the server...
It's been a (very) long time since I've done any applet program, so this might be slightly off...
Take a closer look at Deploying an Applet for more details
Updated based on feedback
If you can't use a Jar file then you'll need to use, something like Image img = getImage(getCodeBase(), "dwight.PNG"); to load the image...
The image will need to stored in the same location as your class files, for example, if AskDwight.class doesn't belong to a package, they would reside at the same location (on the drive). If AskDwight.class belonged to the com.foo.bar package, the image file would be in the directory above com

Refreshing display of a text panel in a GUI

I'm having more "I'm hopeless at programming" problems.
I have a piece of code which uses StringBuilder to display elements of an array in a text panel of a GUI when the program starts. Here's the StringBuilder code:
// memory tab
StringBuilder mList = new StringBuilder();
memLocList = new Memory[MEM_LOCATIONS];
mem = new Memory();
for (int i = 0; i < memLocList.length; i++) {
memLocList[i] = mem;
memLocList[i].setOpCode(00);
mList.append(String.format("%10s %04x %10s %6s", "Address: ", i,
"Value: ", memLocList[i].getOpCode()));
mList.append("\n");
}
JComponent memTab = makeTextPanel(mList.toString());
tabs.addTab("Memory", new JScrollPane(memTab));
}
protected JComponent makeTextPanel(String t) {
text = t;
JPanel panel = new JPanel(false);
JTextPane filler = new JTextPane();
filler.setFont(new Font("Courier", Font.PLAIN, 14));
filler.setText(text);
filler.setAlignmentX(LEFT_ALIGNMENT);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
The GUI also has a text entry panel where a String of hex values can be entered.
On clicking a button, the user is prompted for another value, which corresponds to the position in the array where the first hex value should be inserted.
Once these values have been entered, I'd like the display to be updated / refreshed to reflect this but am unsure of how to go about it.
I found this question here, which is similar but I'm not sure if implementing Observer/Observable pattern is the right way to proceed, and even if it is, how I'd go about it:
Best Way to Constantly Update GUI Elements
My initial approach was to add an "updateDisplay()" method, which I could call after processing the button click and re-call the makeTextPanel method:
public void updateDisplay() {
makeTextPanel(text);
}
I thought this might refresh it but it has no effect of the display.
Any help appreciated.
You hold your array in a model class, and you allow other classes to "listen" to this by giving this class a SwingPropertyChangeSupport object as well as an addPropertyChangeListener(...) method. Then give the array a setXXX(...) method, and in that method fire the SwingPropertyChangeSupport object after updating the array. There are examples of just this sort of thing on this site, some written by me.
For example: here, here, here, ...
By the way, I'm not surprised that your call to makeTextPanel(text) doesn't work. It creates a JPanel, but you don't appear to do anything with the JPanel that is returned from the method. But nor should you. I don't think that creating new JPanels is the solution you want, but rather updating the Strings displayed by a component of some sort such as a JList or JTextArea using the listener framework that I've described above.
If any of this is confusing, please ask for clarification.

How do I use requestFocus in a Java JFrame GUI?

I am given an assignment but I am totally new to Java (I have been programming in C++ and Python for two years).
So we are doing GUI and basically we extended JFrame and added a couple fields.
Say we have a field named "Text 1" and "Text 2". When user presses enter with the cursor in Text 1, move the focus to Text 2. I tried to add
private JTextField textfield1() {
textfield1 = new JTextField();
textfield1.setPreferredSize(new Dimension(200, 20));
textfield1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
textfield1text = textfield1.getText().trim();
textfield1.setText(textfield1text);
System.out.println(textfield1text);
textfield1.requestFocus();
}
});
return textfield1;
}
But that doesn't work at all.
I noticed that requestFocus is not recommended, and instead one should use requestFocusWindows. But I tried that too. Upon some readings it seems like I have to do keyboard action and listener? But my teacher said it only requires 1 line...
Well, you have textfield1.requestFocus(), but your description would imply you need textfield2.requestFocus(). (that's 2).
Another option might be to use:
textField1.transferFocus();
This way you don't need to know the name of the next component on the form.

Collecting data from a large number of Swing text fields

I am currently writing a sudoku solver in Java. What I need now is some kind of Swing GUI to input the known numbers. I created a JFrame, but manually adding 81 text fields from the toolbox seems like a bad solution. I am also able to add with code like this:
this.setLayout(new GridLayout(9, 9));
for (int i = 0; i < 81; i++)
{
this.add(new JTextField("Field"));
}
However, I do not know how to address these text fields afterwards to collect the user input into a two-dimensional array. How can I do that?
A different solution would be to use a JTable. You could allow for the TableModel to maintain the full data solution, as well as a copy of the user's attempts. The CellRenderers and CellEditors could handle the user experience. See this tutorial.
Struggled a bit with this for my own sudoku solver, but ended up going for painting on a JPanel, and adding a mouse listener to that.. Than determine the current field using mouse position with his function:
addMouseListener(new MouseAdapter() {
private int t(int z) {
return Math.min(z / factor, 8);
};
#Override
public void mouseMoved(MouseEvent e) {
setToolTipPossibilities(t(e.getX()), t(e.getY()));
}
#Override
public void mousePressed(MouseEvent e) {
clickColumn = t(e.getX());
clickRow = t(e.getY());
}
});
First you need to declare array of JTextFields.
So just like your array to store user input you do:
private JTextField[] textFields;
After that you can use some math to map your one-dimensional array to your two dimensions.
something like this should work:
floor(index / 9), index % 9
for x,y
Yes that will work to display the array. To read from the array you just need to call the getText method for each element.
JTable is your friend. Use a DefaultTableModel with editable String values.
String[] columnNames = new String[9];
for(int i=0; i<9; i++){columnNames[i]="";}
String[][] data = new String[9][9];
JTable tab = new JTable(columnNames,data);
When they fill it in, check that each string is an appropriate number and prompt for error.
1st way:
You could put the text fields into an array that mirrors the array that your cell values are in.
The problem with this method tho is that when you need to bind a mouseListener or ActionListener to the TextField you will have a hard time figuring out which cell number it corrisponds to.
2nd way:
You could extend the JTextField into a custom class with new instance variables that store cell number in it.
Using this method you can also implement MouseListener or ActionListener on the extended class too and get whatever information about the field you need, without searching through your array. And combining with the first to put them into an array organizes them for quick access.
Just want to post a little update.
I added an array of textfields as a field on my form:
private JTextField[] fields;
Initialized it:
fields = new JTextField[81];
And finally I am adding the fields to my form like this:
private void addComponents()
{
this.setLayout(new GridLayout(9, 9));
for (int i = 0; i < fields.length; i++)
{
fields[i] = new JTextField("" + i);
this.add(fields[i]);
}
}
The result as of now can be seen here:
Image of my textfields

Categories