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.
Related
When user push a button (I created), it makes the TextField editable.
First I use if condition in constructor as:
if(button.isSelected()) TextField.isEditable(true); else TextField.isEditable(false);
But, this gives me an error. Then I use the same statement (to give permission to user weather he want to make text editable or not) in a method with parameter ActionEvent in which is another method_implemented by ActionListener. But this also gives error. Code and output before applying action on button is given:
Code is given below
Output
package Radio_Button;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Radio_Buttons extends JPanel{
private JRadioButton bold;
private JRadioButton italic;
private JRadioButton both;
private JRadioButton plain;
private ButtonGroup group;
private JTextField TextField;
private JButton button;
public Radio_Buttons(){
//Declare all radio buttons
plain = new JRadioButton("Plain",false);
bold = new JRadioButton("Bold", false);
italic = new JRadioButton("Italic", false);
both = new JRadioButton("Bold+Italic", false);
//Declare Text Field
TextField = new JTextField("The quick brown fox jumps over the lazy dog.",40);
TextField.setFont(new Font("Chiller", Font.PLAIN, 30));
//For button
button = new JButton("Push to edit");
//Add in panel
add(bold);
add(italic);
add(both);
add(plain);
add(TextField);
add(button);
//Make a family of radiobuttons so they can understand each others.
group = new ButtonGroup();
group.add(bold);
group.add(italic);
group.add(both);
group.add(plain);
RadioListener listener = new RadioListener();
bold.addActionListener(listener);
italic.addActionListener(listener);
plain.addActionListener(listener);
both.addActionListener(listener);
setBackground(Color.yellow);
setPreferredSize(new Dimension(800,500));
}
private class RadioListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int source = 0;
if (bold.isSelected()) {source =Font.BOLD; }
else if (italic.isSelected()) {source = Font.ITALIC; }
else if (both.isSelected()){source = Font.BOLD+Font.ITALIC; }
else {source = Font.PLAIN; }
TextField.setFont(new Font("Chiller", source, 30));
}
}
public static void main (String [] args){
JFrame frame = new JFrame("Quote Options");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Radio_Buttons panel = new Radio_Buttons();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
First thing first. Spend some time to understand having meaningful "variable" names and Naming Convention. e.g variable name like TextField is a no no.
In your example, TextField is enabled by default itself. Initialize it with "editable" as false like below:
TextField.setEditable(false);
Add listener to your button and change editable of Textflied like below
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TextField.setEditable(true);
}
});
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.
This is not a duplicate as I already know the code .setEnabled(false);. My problem is that I am making a gui in netbeans and I cannot figure out how to disable/enable buttons. Obviously I am new to JAVA and Netbeans This is what I have to do:
Start the program with all buttons disabled except the Initialize
button.
When Initialize is pressed the ArrayList will be filled with 5 CD
titles. The Initialize button then becomes disabled and the other
buttons become enabled.
The only code I know for buttons is .setEnabled(false); but it only disables button after I click it and what i need is to make one enabled and rest disabled. After I click it, it should be disabled and rest should be enabled.
The current code is not relevant but if you need it I will edit this post! Any help is greatly appreciated and thank you in advance!
You need to use interface ActionListener and add ActionListener after clicking
of button. Implement default method ActionPerformed. Use this code as example.
import java.awt.*;
import java.awt.event.*;
class calc extends Frame implements ActionListener
{
TextField t1 =new TextField(20);
TextField t2 =new TextField(29);
TextField t3 =new TextField(29);
Label l1=new Label("first");
Label l2=new Label("second");
Label l3=new Label("sum");
Button b1=new Button("Add");
Button b2=new Button("close");
calc() //CONSTRUCTOR
{
add(l1);add(t1);
add(t2);add(l2);
add(t3);add(l3);
add(b1);
add(b2);
setSize(444,555);
setVisible(true);
setLayout(new FlowLayout());
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object o=e.getSource();
if(o==b2)
{
System.exit(1);
}
String n1=t1.getText();
String n2=t2.getText();
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
t3.setText(""+(a+b));
}
}
class Gi
{
public static void main(String[] args)
{
new calc();
}
}
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);
}
});
}
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".