Getting User Input

How to get the user input in Java?

You can use any of the following options based on the requirements.

Scanner class

import java.util.Scanner; 
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();


BufferedReader and InputStreamReader classes

import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);


DataInputStream class

import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader



Console class

import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

Apparently, this method does not work well in some IDEs.

How to get the input from user?

You can make a function that takes the user input and converts it to the actual name you need as such;

def get_group_name_from_id(id):
if id == "0":
return "All_Groups"
elif id == "1":
return "Caltech"
elif id == "2":
return "KKI"
elif id == "3":
return "Leuven"
else:
return "an invalid option"

group_id = input("Which group you want to analyze: \n 0-All_Groups \n 1-Caltech \n 2-KKI \n 3-Leuven")
group_name = get_group_name_from_id(group_id)
print("You have chosen:", group_name, "!")

Getting user input while a timer is counting and updating the console

I ended up using async and learning a bit in the process. Here's the code. And BTW it is a lot lighter weight than my threaded verssion. My Macbook pro fans spin up to max speed when I run the threaded version. But I can barely hear them at all with the async version.

import sys
import asyncio
from count_timer import CountTimer
from blessed import Terminal

def count():
if counter.remaining > 10:
print(
term.bold
+ term.green
+ term.move_x(0)
+ term.move_up
+ term.clear_eol
+ str(round(counter.remaining, 3))
)
elif counter.remaining > 5:
print(
term.bold
+ term.yellow2
+ term.move_x(0)
+ term.move_up
+ term.clear_eol
+ str(round(counter.remaining, 3))
)
elif counter.remaining > 0:
print(
term.bold
+ term.red
+ term.move_x(0)
+ term.move_up
+ term.clear_eol
+ str(round(counter.remaining, 3))
)
else:
print(
term.bold
+ term.magenta
+ term.move_x(0)
+ term.move_up
+ term.clear_eol
+ "TIME'S UP!"
)

def kb_input():
if counter.remaining <= 0:
return
with term.cbreak():
key = term.inkey(timeout=0.01).lower()
if key:
if key == "q":
print(
term.bold
+ term.magenta
+ term.move_x(0)
+ term.move_up
+ term.clear_eol
+ "Quitting..."
)
sys.exit()
elif key == "r":
counter.reset(duration=float(duration))
counter.start()
elif key == " ":
counter.pause() if counter.running else counter.resume()

async def main():
global counter
global term
global duration

duration = input("Enter countdown timer duration: ")
counter = CountTimer(duration=float(duration))
counter.start()
term = Terminal()

def _run_executor_count():
count()

def _run_executor_kb_input():
kb_input()

while counter.remaining > 0:
await asyncio.get_event_loop().run_in_executor(None, _run_executor_count)
await asyncio.get_event_loop().run_in_executor(None, _run_executor_kb_input)

await asyncio.get_event_loop().run_in_executor(None, _run_executor_count)

def async_main_entry():
asyncio.get_event_loop().run_until_complete(main())

if __name__ == "__main__":
async_main_entry()

How to get user input from contenteditable div in a grid?

https://codepen.io/codmitu/pen/LYegzNN?editors=0011

html:

<p>absolute</p>
<div contenteditable="true" style="border: 5px solid; padding: 5px"></div>
<button>check</button>

js:

const pText = document.querySelector("p").innerText
const div = document.querySelector("div")
const button = document.querySelector("button")

button.addEventListener("click", () => {
const text = div.textContent
//checking for numbers
if (text.match(/\d/gi)) {
div.innerText = text
return
}

div.innerHTML = ""
text.split("").forEach(letter => {
if (pText.includes(letter)) {
div.innerHTML += `<span style="color: green">${letter}</span>`
} else {
div.innerHTML += `<span style="color: grey">${letter}</span>`
}
})
})

//blur the div if text is longer than 8 letters
div.addEventListener("keydown", (e) => {
if (div.innerText.length > 7 || e.keyCode == 32) {
div.blur()
}
})

//clear on focus
div.addEventListener("focus", () => {
div.innerHTML = ""
})

Get User Input and show it on field - Java

Below code is a rewrite of your GUI application.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Login {
private JCheckBox c1;
private JPasswordField confirmPasswordText;
private JPasswordField passwordText;
private JRadioButton femaleButton;
private JRadioButton maleButton;
private JTextArea textArea;
private JTextField emailText;
private JTextField nameText;

private void createAndDisplayGui() {
JFrame frame = new JFrame("Registration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createHeading(), BorderLayout.PAGE_START);
frame.add(createForm(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

private JButton createButton(String text,
int mnemonic,
ActionListener listener) {
JButton button = new JButton(text);
button.setMnemonic(mnemonic);
button.addActionListener(listener);
return button;
}

private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton("Submit", KeyEvent.VK_S, this::submit));
return buttonsPanel;
}

private JPanel createForm() {
JPanel form = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets.bottom = 5;
gbc.insets.left = 10;
gbc.insets.right = 10;
gbc.insets.top = 0;
JLabel nameLabel = new JLabel("Name");
form.add(nameLabel, gbc);
gbc.gridx = 1;
nameText = new JTextField(16);
form.add(nameText, gbc);
gbc.gridy = 1;
form.add(createRadioButtons(), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
JLabel eMailLabel = new JLabel("E-mail");
form.add(eMailLabel, gbc);
gbc.gridx = 1;
emailText = new JTextField(16);
form.add(emailText, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
JLabel passwordLabel = new JLabel("Password");
form.add(passwordLabel, gbc);
gbc.gridx = 1;
passwordText = new JPasswordField(16);
form.add(passwordText, gbc);
gbc.gridx = 0;
gbc.gridy = 4;
JLabel confirmLabel = new JLabel("Confirm password");
form.add(confirmLabel, gbc);
gbc.gridx = 1;
confirmPasswordText = new JPasswordField(16);
form.add(confirmPasswordText, gbc);
gbc.gridx = 1;
gbc.gridy = 5;
c1 = new JCheckBox("I agree to websites rules!");
form.add(c1, gbc);
gbc.gridx = 1;
gbc.gridy = 6;
textArea = new JTextArea(2, 30);
textArea.setEditable(false);
textArea.setFocusable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
form.add(scrollPane, gbc);
return form;
}

private JPanel createHeading() {
JPanel heading = new JPanel();
JLabel label = new JLabel("REGISTRATION FORM");
label.setFont(label.getFont().deriveFont(Font.BOLD, 14.0f));
heading.add(label);
return heading;
}

private JPanel createRadioButtons() {
JPanel radioButtons = new JPanel();
ButtonGroup group = new ButtonGroup();
maleButton = new JRadioButton("Male");
maleButton.setSelected(true);
radioButtons.add(maleButton);
group.add(maleButton);
femaleButton = new JRadioButton("Female");
radioButtons.add(femaleButton);
group.add(femaleButton);
return radioButtons;
}

private void submit(ActionEvent event) {
textArea.setText("");
String name = nameText.getText();
textArea.append(name);
String gender;
if (maleButton.isSelected()) {
gender = "male";
}
else {
gender = "female";
}
textArea.append(", " + gender);
String email = emailText.getText();
textArea.append(", " + email);
String password = new String(passwordText.getPassword());
textArea.append(", " + password);
String confirmPassword = new String(confirmPasswordText.getPassword());
textArea.append(", " + confirmPassword);
textArea.append(", " + c1.isSelected());
}

public static void main(String[] args) {
EventQueue.invokeLater(() -> new Login().createAndDisplayGui());
}
}
  • Usually you use a layout manager rather than setting it to null. Refer to Laying Out Components Within a Container
  • You need to group JRadioButtons in a ButtonGroup to ensure that only one can be selected. Refer to How to Use Buttons, Check Boxes, and Radio Buttons
  • Method getText is deprecated for JPasswordField. Refer to How to Use Password Fields.
  • I chose to display the user inputs in a JTextArea in a JScrollPane but there are other options. Refer to Using Text Components and How to Use Scroll Panes.
  • Since Java 8, the ActionListener interface can be implemented via a method reference.


Related Topics



Leave a reply



Submit