I want to make a form using java frame. I have two fields Name and Age. After entering the details, when the button is clicked, the entered data must be displayed as shown below, but I am not sure how to align it.
The entered data are:
FirstName: abcd
LastName: efg
This is what I have so far:
import java.awt.*;
import java.awt.event.*;
public class DataEntry {
public static void main(String[] args) {
Frame frm=new Frame("DataEntry frame");
Label lbl = new Label("Please fill this blank:");
frm.add(lbl);
frm.setSize(350,200);
frm.setVisible(true);
frm.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Panel p = new Panel();
Panel p1 = new Panel();
Label jFirstName = new Label("First Name");
TextField lFirstName = new TextField(20);
Label jLastName =new Label("Last Name");
TextField lLastName=new TextField(20);
p.setLayout(new GridLayout(3,1));
p.add(jFirstName);
p.add(lFirstName);
p.add(jLastName);
p.add(lLastName);
Button Submit=new Button("Submit");
p.add(Submit);
p1.add(p);
frm.add(p1,BorderLayout.NORTH);
}
}
Firstly, you need to add an event to the button, when it is clicked.
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Add the code to output the relevant details.
}
}
Then it's up to you to add the relevant code to the method body.
You should read the Documentation
Add a listener to your "Submit" button:
Submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myLabelForShowingTheOutput.setText("<html><body>Name: " + lFirstName + "<br>Last name: " + lLastName + "</body></html>");
}
});
Note that "myLabelForShowingTheOutput" is the JLabel you want to print. The text to print is basic HTML, so the label can show multiple lines. Other way to do it without HTML would be create a JLabel for the name and another for the age. Note as well that I did put the last name in the output, because there isn't an obvious JTextField for the age.
Remember, as well, that variables should start their name in lower case, so Submit would be "submit".
Related
I'm beginner is java. I'm trying to check textfield is empty or not in java. I'm using awt, awt event.I have taken 2 texfield 1 button and 1 label. When Button click it will check that both text field are not blank if both textfields are blank then it will show Error text in label else if both fields are not blank then it will show Success text in label.
check my code
import java.awt.*;
import java.awt.event.*;
public class form{
public static void main(String args[]){
//initializing components here//
Frame f= new Frame("Test");
TextField tf1= new TextField();
TextField tf2= new TextField();
Button b1= new Button("click me");
Label Toast= new Label("Default Toast");
//Setting Positions//
tf1.setBounds(30,50,100,20);
tf2.setBounds(30,100,100,20);
b1.setBounds(30,150,100,20);
Toast.setBounds(30,185,100,20);
//End Setting Postitions//
//Start Button Listener//
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(tf1.getText()==null && tf2.getText()==null){
Toast.setText("Null field");}
else{
Toast.setText("Success");}
}
});
//End Button Listener here//
//Adding to Frame//
f.add(tf1);f.add(tf2);f.add(b1);f.add(Toast);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
//Adding to Frame End//
The string is empty, not null. tf1.getText()==null won't work in that case, you need to do
tf1.getText().isEmpty()
To check if the String is empty.
I want to construct a Swing component JTextField, here is my Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTextFieldGui{
JTextField textField;
JLabel labelInput;
JLabel labelOutput;
public static void main(String[] args) {
JTextFieldGui gui = new JTextFieldGui();
gui.go();
}
public void go(){
JFrame frame = new JFrame();
JPanel panelInput = new JPanel();
JPanel panelOutput = new JPanel();
labelInput = new JLabel("Your first name: ");
labelOutput = new JLabel("Enter your name, and you will see it here.");
textField = new JTextField(20);
JButton enter = new JButton("Enter");
JButton selectAll = new JButton("Select all text");
frame.setSize(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelInput.setLayout(new BoxLayout(panelInput, BoxLayout.X_AXIS));
textField.addActionListener(new LabelActionListener());
enter.addActionListener(new LabelActionListener());
selectAll.addActionListener(new TextFieldActionlistener());
frame.getContentPane().add(BorderLayout.NORTH, panelInput);
panelInput.add(labelInput);
panelInput.add(textField);
panelInput.add(enter);
panelInput.add(selectAll);
frame.getContentPane().add(BorderLayout.CENTER, panelOutput);
panelOutput.add(labelOutput);
}
class LabelActionListener implements ActionListener{
public void actionPerformed(ActionEvent event){
labelOutput.setText(textField.getText());
}
}
class TextFieldActionlistener implements ActionListener{
public void actionPerformed(ActionEvent event){
textField.selectAll();
}
}
}
Question1: I define the width of the text field in 20 columns, but it always take up a row, like image:
Question2: how to use the selectAll() method, I use it in a listener of the button selectAll, but when I click the button, nothing happens, why
I define the width of the text field in 20 columns, but it always take up a row,
This is the rule of a BoxLayout. A component is resized to fill the space available. A JTextField doesn't have a maximum size so it grows. The buttons and label do have a maximum size so they don't grow.
Don't use a BoxLayout, just use a FlowLayout. It will automatically leave space between each component which is a better layout.
I use it in a listener of the button selectAll, but when I click the button, nothing happens, why
Focus is still on the button. The selected text only displays when the text field has focus.
So in he listener code you need to add:
textField.requestFocusInWindow();
The following code is old:
frame.getContentPane().add(BorderLayout.NORTH, panelInput);
you don't need to get the content pane. You can just add the component to the frame.
the constraint should be the second parameter
there are new constraints to make the names more meaningful
So the code should be:
frame.add(panelInput, BorderLayout.PAGE_START, panelInput);
See the section from the Swing tutorial on How to Use BorderLayout for more information.
I am writing a Java GUI program. I have two JTextFields:
'txtNet' and 'txtExcise'. I want values in these two textfields added as soon as I enter them and populate the result in another textfield 'txtTotal' without using a button.
I want values in these two textfields added as soon as I enter them
and populate the result in another textfield 'txtTotal' without using
a button.
This can be done using a DocumentListener on the JTextField's.
Here is a tutorial that covers the basics on how to use them: How to Write a Document Listener
Important extract from tutorial:
Document events occur when the content of a document changes in any
way
This will allow you to monitor changes on the textfield values and react accordingly. For your case this would involve checking the values of the 2 inputs and provided both are valid, displaying the result in the output textfield
Here is a quick SSCCE (Stack overflow glossary of acronyms):
public class AutoCalculationDemo {
public static void main(String[] args) {
JTextField firstInput = new JTextField();
JTextField secondInput = new JTextField();
JTextField output = new JTextField();
output.setEditable(false);
DocumentListener additionListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
attemptAddition();
}
#Override
public void removeUpdate(DocumentEvent e) {
attemptAddition();
}
#Override
public void changedUpdate(DocumentEvent e) {
attemptAddition();
}
public void attemptAddition(){
try{
double firstValue = Double.parseDouble(firstInput.getText());
double secondValue = Double.parseDouble(secondInput.getText());
output.setText(String.valueOf(firstValue + secondValue));
}catch (NumberFormatException nfe){
System.out.println("Invalid number(s) provided");
}
}
};
firstInput.getDocument().addDocumentListener(additionListener);
secondInput.getDocument().addDocumentListener(additionListener);
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(new JLabel("First number: "));
panel.add(firstInput);
panel.add(new JLabel("Second number: "));
panel.add(secondInput);
panel.add(new JLabel("Output: "));
panel.add(output);
frame.add(panel);
frame.setSize(250,150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I'm trying to make a texted based game where I ask the user a series of questions similar to how a survey works. I want to make a GUI with a box where these questions can be asked and another box so that they can input their answers. I've researched this a bit but i'm not sure how to get the text they input as an answer because depending on how they answer the question, a different action occurs. So my question is how to create a text box that can hold my print statements and another text box where the user can input answers.
If you are using Swing: for your questions you can use a JLabel and set the text in it either through the constructor or through its setText() method.
As for user answers you can use a JTextField or JTextArea object (depending on the expected size of user input) and call the getText() methods to retrieve the user input as a String.
print statements print the output to the console not to the application, so what you can do is replace the print statements with the loadQuestion() function.
public void LoadQuestion(String question)
{
label1.setText(question);//label1 is the questions label which sets the string question to the label
}
//==setting up the labels
JButton answerButton;
JPanel panel;
JLabel label1,label2;
final JTextField text2;
JLabel scoreLabel;
int score = 0;
Quiz()
{
label1 = new JLabel();
label1.setText("Questions:");//questions label
scoreLabel = new JLabel("SCORE: ");
label2 = new JLabel();
label2.setText("Answer:");//answer label
text2 = new JTextField(15);//answer textfield
answerButton=new JButton("ANSWER");
panel=new JPanel(new GridLayout(3,1));
panel.add(scoreLabel);
panel.add(label1);
panel.add(label2);
panel.add(text2);
panel.add(answerButton);
add(panel,BorderLayout.CENTER);
answerButton.addActionListener(this);
setTitle("QUIZ");
}
SetUp your UI.
A Score Label which maintains score.
A Questions Label which has the question to display.
An Answer TextBox which takes the answer from the user.
A submit button which validates the answer.
Add Actions to your button, take the text from the answer box and validate.
public void actionPerformed(ActionEvent ae)
{
String answer =text2.getText();
if(answer.equals(" "))
{
JOptionPane.showMessageDialog(this,"Correct Answer");
score++;
scoreLabel.setText("SCORE: "+score);
}
else{
JOptionPane.showMessageDialog(this,"Wrong Answer");
scoreLabel.setText("SCORE: "+score);
}
}
The total code for the Application is here:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Quiz extends JFrame implements ActionListener
{
JButton answerButton;
JPanel panel;
JLabel label1,label2;
final JTextField text2;
JLabel scoreLabel;
int score = 0;
Quiz()
{
label1 = new JLabel();
label1.setText("Questions:");//questions label
scoreLabel = new JLabel("SCORE: ");
label2 = new JLabel();
label2.setText("Answer:");//answer label
text2 = new JTextField(15);//answer textfield
answerButton=new JButton("ANSWER");
panel=new JPanel(new GridLayout(3,1));
panel.add(scoreLabel);
panel.add(label1);
panel.add(label2);
panel.add(text2);
panel.add(answerButton);
add(panel,BorderLayout.CENTER);
answerButton.addActionListener(this);
setTitle("QUIZ");
}
public void LoadQuestion(String question)
{
label1.setText(question);
}
public void actionPerformed(ActionEvent ae)
{
String answer =text2.getText();
if(answer.equals(" "))
{
JOptionPane.showMessageDialog(this,"Correct Answer");
score++;
scoreLabel.setText("SCORE: "+score);
}
else{
JOptionPane.showMessageDialog(this,"Wrong Answer");
scoreLabel.setText("SCORE: "+score);
}
}
}
class QuizDemo
{
public static void main(String arg[])
{
try
{
Quiz frame=new Quiz();
frame.setSize(300,100);
frame.setVisible(true);
}
catch(Exception e)
{JOptionPane.showMessageDialog(null, e.getMessage());}
}
}
EDIT
Setting Answers
As soon as you load a question set an answer for it, compare it when the user clicks the answer button, If it is the same then correct else a wrong answer.
I'm trying to display a name in a textlabel after it is entered in a textfield and pressed a 'Play' button.
The text field and button
private JTextField nameEnter = new JTextField("Enter name here");
private JButton saveName = new JButton("Play");
private JLabel namelabel = new JLabel("Player 1");
To add to board and position
getContentPane().add(nameEnter);
getContentPane().add(saveName);
getContentPane().add(namelabel);
nameEnter.setBounds(80,80+gize*bsize,200,50);
saveName.setBounds(100,100+gsize*bsize,200,50);
namelabel.setBounds(40,40+gsize*bsize,200,50);
This displays fine.
public void UpdateName() {
JButton saveName = new JButton("Play");
saveName.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
final String pName = nameEnter.getText();
namelabel.setText(pName);
}
});
}
I tried to create the above method to store it but this doesn't seem to do anything at all.
Any help appreciated.
Your UpdateName() method is creating its own local JButton saveName button and adding ActionListener to it. Problem is that this button is not the same as button you added to your content pane.
I am not sure why you even need this method. Simplest solution would be placing code responsible for adding this listener
saveName.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
namelabel.setText(nameEnter.getText());
}
});
in initializing method (somewhere after getContentPane().add(saveName);)
The method does:
Create a new button
Attach a listener
On action (click), update the name
To reuse the existing saveName button you already added to your layout,
drop the line that creates a new button, that is:
public void UpdateName() {
saveName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final String pName = nameEnter.getText();
namelabel.setText(pName);
}
});
}