I have an array of question, an array of possible answers and an array of properties I want to find out by answering the questions
String[] questions = new String[]{"Question1", "Question2", "Question3"};
String[] possibleAnswers = new String[]{"yes,no", "yes,no", "big,small"};
String[] properties = new String[]{"", "", ""};
I created a label for every question and JRadioButtons for every answer for that question by using split on the corresponding element in the possibleAnswers array.
for (int i = 0; i < questions.length; i++) {
//label that holds the current question
JLabel questionLabel = new JLabel(questions[i]);
questionPanel.add(questionLabel);
// string that holds answers for current question i.e. {yes, no}
String[] currentQuestionAnswers = possibleAnswers[i].split(",");
ButtonGroup buttonGroup = new ButtonGroup();
for (int j = 0; j < currentQuestionAnswers.length; j++) {
JRadioButton btnRadio = new JRadioButton(currentQuestionAnswers[j]);
// action listener that will store the selected answer and the question
btnRadio.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
answer = btnRadio.getText();
// some code that moves answer at the right index in the properties array
}
});
buttonGroup.add(btnRadio);
questionPanel.add(btnRadio);
}
}
This image shows what I want it to look like.
For each question I want to find a property. Let's say {Question1, Question2, Question3} are actually these questions {"talks?", "expensive?", "dimension?"}. When I get the text from the selected buttons, I'll have talks -> yes, expensive -> no, dimension -> big, so the properties array will become {"yes", "no", "big"}.
I know how to get the selected answer, but I can't figure out how to find the question that corresponds to that answer. I thounght I can somehow use the button groups I created, but I don't know how.
I hope this makes sense and someone can help. Thank you.
One way to do it would be to extend JRadioButton and add a simple ID field (a tag). I can't test this code right now but I think
it should work.
class MyRadioButton extends JRadioButton{
private int tag;
public getTag(){ return tag;}
public setTag(int val){ tag = val}
}
And then in the actionPerfomed method, just check this tag and take an appropriate action based on it.
int tag = 0;
btnRadio.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
answer = btnRadio.getText();
switch(btnRadio.getTag()){
case 0:
//do some action
break;
case 1:
....
}
// some code that moves answer at the right index in the properties array
}
});
btnRadio.setTag(tag++);//this will set a unique tag for each radio button
buttonGroup.add(btnRadio);
Alternatively, if you don't want to extend JRadioButton,which arguably might be overkill for your use case, you can use RadioButton.setActionCommand and ActionEvent.getActionCommand
btnRadio.setActionCommand("some_unique_string")
and then just check this command string in actionPerformed
if("some_unique_string".equals(ae.getActionCommand())
//do something
Related
To start with -- I'm not sure, that I have properly formulated the question (I'm new in Java and in making programs with GUI).
It is the following thing, I'm trying to do. I have a window with several similar parameters (numbers are just for distinction between lines and it ist just very simplified example, of what should my GUI be):
Initial Window
Then, by clicking on the "+"-button I would like to add an new line, like here:
Line 35 is added
It should be also possible to delete lines, like here: Line 30 was deleted, by pressing "-"-Button.
As I wrote at the beginning, it is possible, that there was such a question, but I couldn't find anything (probably, because I do not now the keywords or I was looking with a wrong ones).
How such window can be done? The only idea I have is to draw a new window after every +/-.
Addition: Code (not working in the part of changing the number of rows).
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame {
public Test() {
setSize(200, 600);
JButton plusButton[] = new JButton[100];
JButton minusButton[] = new JButton[100];
JTextField fields[] = new JTextField[100];
JPanel panel1 = new JPanel();
for (int i=0; i<plusButton.length; i++) {
plusButton[i]=new JButton("+");
minusButton[i]=new JButton("-");
fields[i] = new JTextField("Text "+ i);
}
for (int i=1; i<4; i++) {
panel1.add(plusButton[i*10]);
plusButton[i*10].setActionCommand("add after " +String.valueOf(i));
panel1.add(minusButton[i*10]);
minusButton[i*10].setActionCommand("remove " +String.valueOf(i));
panel1.add(fields[i*10]);
}
panel1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
this.getContentPane().add(panel1);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
for (int i=0; i<100; i++) {
String stand1 = "add after "+String.valueOf(i);
String stand2 = "remove "+String.valueOf(i);
if (stand1.equals(e.getActionCommand())) {
//add "row" of elements
panel1.add(plusButton[i]);
plusButton[i+1].setActionCommand("add");
panel1.add(minusButton[i+1]);
minusButton[i+1].setActionCommand("remove");
panel1.add(fields[i+1]);
} else if (stand2.equals(e.getActionCommand())) {
//delete "row" of elements
}
}
}
public static void main(String[] args) {
Test a = new Test();
}
}
The Problem, that is obvious -- when I want to add 2 rows (i think it is proper definition) of buttons after button 20, there will be an doubling of numbers. As a solution I see here a creation of a new panel for each new row. But it is sounds wrong for me.
P.S. Unfortunately I do not have time to end this topic or to post a working example. I actually found some kind of solution, beginning from the Question here, on Stack Overflow:
Adding JButton to JTable as cell.
So, in case somebody will be looking for such topic, it should sounds like "jButton in jTable".
There are multiple GUI frameworks for Java. First decide which one you wanna use.
As for your particular query
Add functionality to the + and - such that it will create an instance of a field object (that line with parameters as you call them) or destroy that particular instance of the object.
+ is clicked -> Create new object on consecutive line and increase the pointer-count(?) of the following fields.
- is clicked -> Call destructor for the particular object and decrease the pointer-count of the following fields.
I have two combo boxes with a list of distance units to convert from/to. Now, when I want to choose eg. "Centimeter" from the ComboBox From (distance)..., I really don't need to have "Centimeter" in ComboBox To (distance)..., because it doesn't make sense to convert from centimeter to centimeter.
So when "Centimeter" is selected in From (distance)... I want it to be removed in To (distance)... ComboBox. But, when I change my selection (say "Meter"), I want "Centimeter" to be back and "Meter" disappear etc.
I managed to remove the selected item in To (distance)... box, but don't know how to return it back when I change my selection. Besides, when I change selection, the code below just removes the corresponding item in To (distance)... ComboBox.
Please guide me to the correct solution. Here is the corresponding code. I can give you the whole code if you need. Thank you!
private String[] convertFromDistance = {"From (distance)...", "Centimeter", "Inch", "Kilometer", "Knot", "Meter", "Mile", "Millimeter", "Yard"};
private String[] convertToDistance = {"To (distance)...", "Centimeter", "Inch", "Kilometer","Knot", "Meter", "Mile", "Millimeter", "Yard"};
private JComboBox fromListDistance, toListDistance;
fromListDistance.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String list = (String)fromListDistance.getSelectedItem();
for (int i=0; i<convertToDistance.length; i++) {
if (convertToDistance[i].equals(list)) {
toListDistance.removeItem(convertToDistance[i]);
//here should go the code for adding back the item if selection is changed
}
}
}
});
toListDistance = new JComboBox<String>(convertToDistance);
first thing you i should do in your problem is to know what is the selected choice from fromListDistance combo box ..
after that i have to refill the toListDistance combo box except for the choice that the user have selected ..
it's easy to do this with if statement
fromListDistance.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//saving the selected choice
String choise=fromListDistance.getSelectedItem().toString();
//here we remove all items from the combo box
toListDistance.removeAllItems();
for (int i = 0; i < convertToDistance.length; i++) {
String distance=convertToDistance[i];
//compare the selected choice with the convertToDistance[i]
if (choise.equals(distance)) {
continue;
}
toListDistance.addItem(distance);
}
}
});
I have two tables and I need to add the value from specific cell in table_3 to table_4 .. but its not working. Any help please?
Code :
JTable table_3 = new JTable(TableModel2);
final JTable table_4 = new JTable(TableModel3);
JButton btnAdd = new JButton("add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table_3.getSelectedRow();
int column = table_3.getSelectedColumn();
Object selectedPlanet = TableModel2.getValueAt(row, column);
int columnContainingPlanets = 0;
for (int index = columnContainingPlanets; index < TableModel3.getRowCount();index ++){
Object value = TableModel3.getValueAt(index, columnContainingPlanets) ;
if (value == selectedPlanet) {
JOptionPane.showMessageDialog(panel_10,"This item was selected ,Please select another item");
return; }}
TableModel3.addRow(new Object[] { selectedPlanet });
}
});
Still waiting for your Minimal, Complete, and Verifiable Example(MCVE). What makes you think the problem is in the code you posted? Until a problem is solved every question should have a simple example demonstrating the problem which proves that you tried to simplify problem to better debug it.
What is the point of posting the error message without indicating the line of code causing the problem? Again another reason to post the MCVE. You don't know until the question is answered what information is needed to solve the problem.
Without all the information all we can do is guess.
As a newbie to the forum you get one guess. Future questions will require an MCVE
My guess is that the "tableModel3" doesn't have any columns, so you can't add a row to the model containing a single column of data.
So the model should be created with code something like:
String[] columnNames = { "Planets" };
DefaultTableModel tableModel3 = new DefaultTableMNodel(columnNames, 0);
So I'm trying to make a quiz in which I will have 4 buttons for possible answers. I want to check if the right button is pressed, if so I want to change the image for about 2 seconds and load the next question (which will be an image stored in an array) this will be in a for loop the length of the question array I believe?
I'm having some trouble with this, as I'm also unsure on how to load a new question and then it know which button needs to be pressed, for example. question 1 might need button 1 pressing but question 2 might be button 3 but I don't want to change activity.
creating the array and setting image view:
private int[] ImageArr = new int[5];
private ImageView image = (ImageView) findViewById(R.id.Question_ImgView);
filling array:
public void FillImage() {
ImageArr[0] = R.drawable.img1;
ImageArr[1] = R.drawable.img2;
ImageArr[2] = R.drawable.img3;
ImageArr[3] = R.drawable.img4;
ImageArr[4] = R.drawable.img5;}
this is then called in the "onCreate method" to fill array on launch
then i will have a questions method, this is where I want the before mentioned things to happen.
tldr; I need to know how to loop through an image array if correct button is pressed (correct button changes for each question), and change the text on the buttons, till all questions are answered.
any help would be appreciated, thanks in advance. :)
I think the best thing you should do is to create a Question class.
public class Question {
#DrawableRes
private int imageId;
private String[] answers;
private int correctAnswerIndex;
public Question(int imageId, int correctAnswerIndex, String... answers) {
this.imageId = imageId;
this.correctAnswerIndex = correctAnswerIndex;
this.answers = answers;
}
#DrawableRes
public int getImageId() { return imageId; }
public String[] getAnswers() { return answers; }
public int getCorrectAnswerIndex() { return correctAnswerIndex; }
}
This class represents a question. It has
an imageId field to store the image of the question
an answers field to store all the possible answers that the user can choose
a correctAnswerIndex to store the correct answer. This actually stores the index of the correct answer in the answers array. Say you have {"blue", "red", "green", "yellow"} as the answers array and the correct answer is blue, you will set the correct answer index to 0.
Don't understand how to use it? Let's see an example.
At the moment, you have an array of image ids. You should change that to an array of Questions.
private Question[] questions = new Question[4];
And your fillQuestion method would be:
questions[0] = new Question(R.drawable.sweeper_is_handsome, 0, "True", "False", "Maybe", "I don't know");
questions[1] = new Question(R.drawable.no_one_can_beat_jon_skeet_in_reputation, 1, "True", "False", "Maybe", "I don't know");
// you get the idea.
As you can see, the answer to the first question is "True" (correctAnswerIndex = 0) and that to the second question is "False" (correctAnswerIndex = 1).
Now you have an array full of questions. How do you display it?
I think you can work out how to display the image yourself, so let's focus on how to get the buttons working.
I guess your buttons will be in an array, right? If it is isn't, then you're totally doing this wrong. Just add four buttons to an array, it's simple.
You can use the same on click handler for each button. It doesn't matter. In the on click listener, you have a view parameter like this right?
public void buttonOnClick(View view) {
// ⬆︎
// here
}
If you are doing this right, view should be an item in your buttons array. You can use the indexOf method to get the index of the button in the array. If this index matches the correctAnswerIndex of the question, the user chose the correct answer!
But how do you know which question is displaying? You create a variable in your activity class called questionIndex to keep track of it! It should start at 0 and each time you display a new question, you increment it!
EDIT:
This is how your button on click handler would look like:
int pressedButtonIndex = btns.indexOf(view);
int correctAnswerIndex = questions[questionIndex].getCorrectAnswerIndex();
if (pressedButtonIndex == correctAnswerIndex) {
// This means the user chose the correct answer
if (questionIndex == 4) {
// This is actually the last question! No need to display the next!
return;
}
// load next question
questionIndex++;
someImageView.setImage(questions[questionIndex].getImageId());
for (int i = 0 ; i < 4 ; i++) {
btns[i].setText(questions[questionIndex].getAnswers()[i]);
}
// YAY! The next question is displayed.
} else {
// User chose the wrong answer, do whatever you want here.
}
I would like to give a general approach to your question, you can or may need to modify according to your needs,
You have an Image Array of questions and would like to know the correct Button was pressed or not, for that you will need the options and a correct answer to compare with the Button clicked to check if the correct Button was pressed or not,
and you do not need to loop through all the questions at once, what you can do is when the button is pressed, compare button text with the correct answer and if its correct then show the next question image, some code example for the same,
if(btnClicked.getText().toString().equals("Correct Answer")){
questionPos++;
imgView.setImageResource(questionPos);
// Update all the buttons as per the new options
btn1.setText(options1);
// .... like wise update other buttons
}
see if this makes sense
Edit
as per you are asking how to know which button is clicked you can do something like this ...
btn1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
if(btn1.getText().toString().equals("Correct Answer")){
questionPos++;
imgView.setImageResource(questionPos);
// Update all the buttons as per the new options
btn1.setText(options1);
}
}
});
// Similarly you can do for all other buttons
I am making a Basic calculator app in java which has 2 JTextFields and 1 JComboBox. What i want to know if there is a way to let a JButton detect what you selected in the JComboBox, when i did it with the text field it looked something like this
static String divide = "/";
if (n == JOptionPane.OK_OPTION) {
if (symbol.getText().equals(divide)){
<code>
}
}
So is there a similar way to do this with JComboBoxs??
String[] symbols = {times, minus, plus, divide};
That's the JComboBox's content code.
You can get selected item from JComboBox with method .getSelectedItem().
Say you have String[] symbols = {times, minus, plus, divide}; as an input when constructing JComboBox (see constructor JComboBox(E[] items) )
JComboBox jcb = new JComboBox(symbols);
//you will see the string you selected
System.out.println(jcb.getSelectedItem());
Perhaps use action listener
String[] quantities1 = {"/","+"};
JComboBox comboBox = new JComboBox(quantities1);
comboBox.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
//do stuff when a section is performed
//you can use comboBox.getSelectedItem() to get the selected value
}
}
);