Hey there I'm trying to make a questionnaire form in java that stores the questions and the person can answer with a number corresponding to the question e.g. 1=not okay at all 2=not okay 3=neither 4=good 5=very good but I'm getting confused on how to go about it cos does anyone have an ideas cos I need 1 app class and 1 instansiable. Your help would be appreciated cos I'm very confused 😭😭😭
#making a questionaire form in java
37 messages · Page 1 of 1 (latest)
ask for the input by the user with Java's Scanner, save the values from there to variables and at the end display it somehow.
All you need is a main method really
@worldly vessel
how would i be able to make it so if using using radio buttons itll do the function
cos im kinda confused about gui for it
Is this the whole code?
Making a GUI can be tricky. It help to break it down into steps. I made this program as an example:
I'll be breaking it down in the next few messages
First, let's break it down into components:
- The main window: this is, well, the main window of the application. This is where everything is displayed to the user.
- Question container: This is any kind of component container that we'll be using to display each question to the user
- Submit button: When the user clicks "Submit", something should happen in response.
There are a few different methods of organization when it comes to the main window. Some people like to write everything inside the main() method of a program, creating JFrame variables for the window itself. This is fine, but I prefer a different approach.
I prefer to create a subclass of javax.swing.JFrame and build off that as a starting point. Here's an example: ```java
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import javax.swing.SwingUtilities;
public class MainWindow extends JFrame {
private JPanel container; // parent component of our app
private JLabel textLabel;
public MainWindow() {
// Use the JFrame constructor with the "title" argument
super("Main Window");
// When the user closes the window, exit the program.
// If you don't do this, nothing will happen when you press 'close'
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create the main container and use a vertical layout
// All components will be added to the bottom of the screen
container = new JPanel();
container.setLayout( new BoxLayout(container, BoxLayout.Y_AXIS) );
// Create a text label, and change its font size to 24px
textLabel = new JLabel("Hello!");
textLabel.setFont(
textLabel.getFont().deriveFont(24f));
// After you create each component, add it to its parent
container.add(textLabel);
// Once all components have been added to the screen,
// pack everything together so it looks pretty.
add(container);
pack();
// By default, the window is not visible
setVisible(true);
}
public static void main(String[] args) {
// In Swing, it's best practice to not create an application directly.
// Instead, use Swing's invokeLater() method to add it when available.
// How this works isn't too important right now.
SwingUtilities.invokeLater(() -> {
MainWindow window = new MainWindow();
});
}
}
This produces a very small window:
It isn't much, but hey, it's all there!
You can resize it by dragging the corners
Anyway, now that that's out of the way, let's create a question!
Actually, before we get into that, let's define what makes a question.
- It has a title, such as "Who is the king of France?"
- In this case, since we're making a multiple-choice question, there are different choices or options the user can choose as an answer
- (Almost) every question has a correct answer
These attributes would be really convenient when used together as a class because they make it easier to organize our program.
I'll leave it up to you to create the Question class, but make sure it has all of those attributes. (Hint: I suggest using a String for the title, a String array (String[]) for the possible choices, and either an integer (representing an index) or a String (representing the text) for the correct answer
You could also use a List<String> or ArrayList<String> to represent choices if that's easier
Next, let's create the Swing component for a single multiple-choice question. Like the MainWindow class, we'll be making a subclass of an existing Swing component: javax.swing.JPanel. This way, we can use the panel as a container for the question in a way that can be reused throughout the program.
Here's a basic question panel:
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.BoxLayout;
import javax.swing.BorderFactory;
import java.awt.Component;
public class QuestionPanel extends JPanel {
private Question question;
private JLabel titleLabel;
private JPanel btnPanel;
private JRadioButton[] buttons;
public QuestionPanel(Question question) {
// Since the constructor for BoxLayout() requires a component,
// We must first use an empty constructor, then make our changes.
super();
setLayout( new BoxLayout(this, BoxLayout.Y_AXIS) );
setBorder( BorderFactory.createTitledBorder("Question #1") );
// Since we named the parameter "question", we have to use the "this" keyword
// to differenciate between it and our private variable
this.question = question;
// Create the title label and set the font size to 16px
titleLabel = new JLabel(question.getTitle());
titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
titleLabel.setFont(
titleLabel.getFont().deriveFont(20f));
// The default layout manager is a left-to-right FlowLayout, which works for us
btnPanel = new JPanel();
// Question choices
String[] choices = question.getChoices();
buttons = new JRadioButton[ choices.length ];
// In Swing, radio buttons are grouped together using a ButtonGroup
// This way, you can only select one button per group.
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < buttons.length; i++) {
// Create a button and set font size to 16px
JRadioButton btn = new JRadioButton( choices[i] );
btn.setFont(
btn.getFont().deriveFont(16f));
group.add(btn);
btnPanel.add(btn);
}
add(titleLabel);
add(btnPanel);
}
}
And here, I've added this to the MainWindow class: ```java
String title = "Who is the king of France?";
String[] choices = {"Charlemagne", "Louis XIV", "James II", "N/A"};
String correct = "N/A";
Question question = new Question(title, choices, correct);
QuestionPanel qp = new QuestionPanel(question);
container.add(qp);
Now we're cooking with oil
Anyway, I think you can take it from here
@worldly vessel Hey, make sure to read this and let me know if you have any questions!
Hm, I just realized that I misunderstood your question slightly. Your task is to make a questionaire, not a multiple-choice question quiz. My mistake!
But that's not so bad, there isn't much to change in the code. Just remove the "correct answer" nonsense
tbh if there's only 2 parts to a question, maybe we shouldnt make it a class. It's easy enough to add the title and choices to QuestionPanel anyway
@worldly vessel do you still need help?
I generated a user script that lets you skip between <form> elements with the tab key and then 'choose' radio selects via an 'a-z' index using keys on the keyboard. So hitting 'd' picks option 'd'?
// ==UserScript==
// @name Cycle through form elements and select radio buttons
// @version 1
// @description Cycle through which <form> element is in focus using the tab key and then hitting a-z keys should work to choose multiple choices as radio button items in each form.
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
let forms = document.getElementsByTagName('form');
let currentFormIndex = 0;
let currentForm = forms[currentFormIndex];
let currentRadioIndex = 0;
let radios = currentForm.querySelectorAll('input[type="radio"]');
let currentRadio = radios[currentRadioIndex];
currentForm.scrollIntoView({block: "center"});
document.addEventListener('keydown', function(event) {
if (event.keyCode === 9) { // tab key
event.preventDefault();
currentRadioIndex = 0;
currentFormIndex++;
if (currentFormIndex >= forms.length) {
currentFormIndex = 0;
}
currentForm = forms[currentFormIndex];
radios = currentForm.querySelectorAll('input[type="radio"]');
currentRadio = radios[currentRadioIndex];
currentForm.scrollIntoView({block: "center"});
} else if (event.keyCode >= 65 && event.keyCode <= 90) { // a-z keys
event.preventDefault();
currentRadio.checked = false;
currentRadioIndex++;
if (currentRadioIndex >= radios.length) {
currentRadioIndex = 0;
}
currentRadio = radios[currentRadioIndex];
currentRadio.checked = true;
}
});
})();
What's a user script? Is that JavaScript? The question was about using Java, specifically the Swing package
Yep. I misread. A userscript hangs out in the browser using an extension to act as a script manager like Greasemonkey/Tampermonkey. As you browse the web the extension can call scripts to transform what you're browsing.
That may help others.
I know when it's a topic I understand and the person has the actual data it's easier to help them since I can provide a working example.
I just learn stuff as it gets in my way to completing goals, and I'd never had an objective where Java was a roadblock so far.
@worldly vessel
File Attachments Not Allowed
For safety reasons we do not allow file and video attachments.
Code Formatting
You can share your code using triple backticks like this:
```
YOUR CODE
```
Large Portions of Code
For longer scripts use Hastebin or GitHub Gists and share the link here
Ignored these files
- java.zip
im using netbeans to do it in
im also using a jframe so im kinda unsure how to send that
@worldly vessel
@worldly vessel
@worldly vessel
_missrandom Uploaded Some Code
Attachment: QuizApp.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package quizapp;
/**
*
* @author marym
*/
public class QuizApp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
QuizGUI myQuiz = new QuizGUI();
myQuiz.setVisible(true);
}
}
For safety reasons we do not allow file attachments.