Этот код выполняется, но новая проблема заключается в том, что я могу выбрать более одного переключателя в каждом разделе, чего не должно быть.
Кроме того, он неправильно подсчитывает баллы. Кто-нибудь может помочь мне это исправить? Спасибо!!!
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Q_Panel extends JPanel
{
//This is the radiobutton class
public JRadioButton one = new JRadioButton("none");
public JRadioButton two = new JRadioButton("none");
public JRadioButton three = new JRadioButton("none");
public JRadioButton four = new JRadioButton("none");
public String answer = new String("none");
public JLabel qLabel = new JLabel("none");
public ButtonGroup group = new ButtonGroup();
public Q_Panel()
{
group.add(one);
group.add(two);
group.add(three);
group.add(four);
QuoteListener listener = new QuoteListener();
one.addActionListener(listener);
two.addActionListener(listener);
three.addActionListener(listener);
four.addActionListener(listener);
add(qLabel);
add(one);
add(two);
add(three);
add(four);
}
private class QuoteListener implements ActionListener
{
//When I run this I do not notice it work...
public void actionPerformed (ActionEvent event)
{
String selected_answer = "";
Object source = event.getSource();
if(source == one)
answer = one.getText();
else
if(source == two)
answer = two.getText();
else
if(source == three)
answer = three.getText();
else
answer = four.getText();
System.out.println("Answer chosen : " + selected_answer);
}
}
};
class radio_button
{
//This is the the class where an instance of the radiobutton class is initialized
public static JFrame frame;
public static JPanel panel;
public static JLabel qLabel;
public static JButton Submit;
public static Q_Panel[] qnum;
public static String right_answer[];
public static int Number_of_lines;
public static String right[];
public static void create()
{
frame = new JFrame();
frame.setTitle("Sample Radio Buttons");
frame.setSize(500, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
qnum = new Q_Panel[10];
right = new String[10];
right_answer = new String[10];
submit = new JButton("Submit");
int y = 0;
int i = 0;
while( i < 10)
{
y = 60 * i;
//We want to assume that the right answer is only "male"
right_answer[i] = "male";
qLabel = new JLabel ("Name of Exam file: " + i);
qLabel.setBounds(10, y+20, 500, 25);
frame.add(qLabel);
qnum[i] = new Q_Panel();
qnum[i].one = new JRadioButton();
qnum[i].one.setText("male");
qnum[i].one.setBounds(10, y+40, 150, 25);
frame.add(qnum[i].one);
qnum[i].two = new JRadioButton();
qnum[i].two.setText("female");
qnum[i].two.setBounds(10, y+60, 150, 25);
frame.add(qnum[i].two);
qnum[i].three = new JRadioButton();
qnum[i].three.setText("shemale");
qnum[i].three.setBounds(200, y+40, 400, 25);
frame.add(qnum[i].three);
qnum[i].four = new JRadioButton();
qnum[i].four.setText("exmale");
qnum[i].four.setBounds(200, y+60, 400, 25);
frame.add(qnum[i].four);
i++;
}
submit.setBounds(400, y+80, 450, 50);
final int v = 0;
submit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//This is supposed to display all the text of the buttons selected and calculate the score in comparison to the right answer..
System.out.println("Submit has been pressed");
int right_answer_count = 0;
int score = 0;
String answer_chosen = "";
boolean checked = true;
int i = 0;
while( i < 10)
{
answer_chosen = "nil";
if (qnum[i].one.isSelected())
{
answer_chosen = qnum[i].one.getText();
}
else if (qnum[i].two.isSelected())
{
answer_chosen = qnum[i].two.getText();
}
else if (qnum[i].three.isSelected())
{
answer_chosen = qnum[i].three.getText();
}
else if (qnum[i].four.isSelected())
{
answer_chosen = qnum[i].four.getText();
}
else if (answer_chosen.equals("nil"))
{
checked = false;
}
if(answer_chosen.equals(right_answer[i]))
{
right_answer_count++;
}
System.out.println("Answer Chosen: " + answer_chosen);
System.out.println("This is the answer in qnum: "+ qnum[i].answer);
i++;
}
System.out.println("I: "+i);
System.out.println("Count right: "+right_answer_count);
score = (right_answer_count/i);
System.out.println("Score: " + score);
}
});
frame.add(submit);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
public static void main(String args[])
{
create();
}
}
1 ответ
Основной ответ: вы злоупотребили static
...
Вы объявляете JRadioButton
в Q_Panel
как ...
public static JRadioButton one = new JRadioButton("none");
public static JRadioButton two = new JRadioButton("none");
public static JRadioButton three = new JRadioButton("none");
public static JRadioButton four = new JRadioButton("none");
Затем в классе radio_button
вы начинаете делать такие вещи, как ...
qnum = new Q_Panel[10];
qnum[i].one = new JRadioButton();
qnum[i].one.setText("male");
Проблема в том, что каждый экземпляр Q_Panel
использует последний экземпляр one
, two
, three
и four
... что означает, что вы выбрали one
в qnum[0]
, все остальные экземпляры также выберут one
...
Удалите ссылки static
и измените код, чтобы разрешить Q_Panel
управлять кнопками JRadio
. Вы даже можете предоставить Q_Panel
метод, который вернет int
, String
или enum
, который описывает то, что было выбрано ...
Похожие вопросы
Новые вопросы
java
Java — это высокоуровневый объектно-ориентированный язык программирования. Используйте этот тег, если у вас возникли проблемы с использованием или пониманием самого языка. Этот тег часто используется вместе с другими тегами для библиотек и/или фреймворков, используемых разработчиками Java.
qnum[i] = new Q_Panel();
Однако я могу выбрать более одного переключателя. Что я не мог придумать, как это исправить .. Огромное спасибо!