How to display a mask in jtextfield? - java

I want to display a mask in a text field. How can I do that? Is there any reusable java library to do that? I want to create a text field that only allow to enter eight digits (each digit should be either 0 or 1)
E.g.

This will create a masked text field. When you press enter it will output what the user typed in. This uses JPasswordField. http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JPasswordField.html
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PasswordField1 extends JApplet implements ActionListener {
/* Declaration */
private JPasswordField Input;
private JTextField Echo;
private Container Panel;
private LayoutManager Layout;
public PasswordField1 () {
/* Instantiation */
Input = new JPasswordField ("", 20);
Layout = new FlowLayout ();
Panel = getContentPane ();
/* Location */
Panel.setLayout (Layout);
Panel.add (Input);
/* Configuration */
Input.addActionListener (this);
}
public void actionPerformed (ActionEvent e) {
char [] Chars;
String Word;
Chars = Input.getPassword();
Word = new String(Chars);
System.out.println("You Entered: " + Word);
}
}

Related

Only single item is visible in the JFrame Window

I wrote this after seeing videos of thenewboston and then, when I ran, only the last item added was visible and all other textFields [textField1, textField2 and textField3] are not visible. It worked perfectly in his videos but when I tried, only the passwordField was visible. I'm a beginner and I was unable to find what's the problem. Please help me out what is the problem and what should I do to mitigate this error. One small request, please explain a bit detail because I a newbie to Java and GUI.
package learningPackage;
import java.awt.FlowLayout;
//gives the layout
import java.awt.event.ActionListener;
//this makes the field wait for an event.
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JTextField;
//creates a field where we can type text.
import javax.swing.JPasswordField;
//creates a text field where the text typed is hidden with asterics.
class tuna extends JFrame
{
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JPasswordField passwordField;
public tuna()
{
super("Title Text");
textField1 = new JTextField(10);
//sets a the default value of 10.
add(textField1);
textField2 = new JTextField("Enter a Text");
//sets default text of "Enter a Text" without the quotes
add(textField2);
textField3 = new JTextField("Uneditable", 20);
//Displays Uneditable with a default value of 20.
//To make this Uneditable, you must do this...
textField3.setEditable(false);
//this makes the textField uneditable.
add(textField3);
passwordField = new JPasswordField("myPassword");
add(passwordField);
thehandler Handler = new thehandler();
textField1.addActionListener(Handler);
textField2.addActionListener(Handler);
textField3.addActionListener(Handler);
passwordField.addActionListener(Handler);
/*
* The addActionListener method takes an object of Event Handler class.
*
* Therefore, we must create an object of Event Handler Class.
*
*
* The addActionListener method takes an object because, sometimes, we might
* have different classes with different code to execute. So, we pass the object to
* identify which class code is to be executed.
*/
}
class thehandler implements ActionListener
{
/*
* In order to handle events in Java, you need Event handler Class.
* and, that Event Handler Class must implement ActionListener.
*
* What the ActionListener does is that
*
* It will wait for some Event to happen and after that particular event happens,
* it will implement some piece of code.
*/
public void actionPerformed(ActionEvent event)
{
String string = "";
if(event.getSource()==textField1)
string = String.format("Text Field 1 : %s", event.getActionCommand());
else if(event.getSource()==textField2)
string = String.format("Text Field 2 : %s", event.getActionCommand());
else if(event.getSource()==textField3)
string = String.format("Text Field 3 : %s", event.getActionCommand());
else if(event.getSource()==passwordField)
string = String.format("Password Field : %s", event.getActionCommand());
//when the user presses enter key after entering text, this actually stores the
//thing entered into the String.
JOptionPane.showConfirmDialog(null, string);
}
}
}
public class Apples {
public static void main(String[] args)
{
tuna Srivathsan = new tuna();
Srivathsan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this would close the window when X button is pressed.
Srivathsan.setSize(500, 500);
Srivathsan.setVisible(true);
Srivathsan.setLocationRelativeTo(null);
}
}
Here is the image of the window :
import java.awt.FlowLayout;
//gives the layout
That statement imports the layout & makes it available to the code, but does not set the layout on any container.
While a JPanel has a default layout of FlowLayout, the default layout of the (content pane of the) JFrame is BorderLayout. A BorderLayout accepts up to 5 components or containers (like JPanel) in each of 5 constraints. If no constraint is given, it defaults to the CENTER. If more than one component is added to the CENTER (or any other area of a BorderLayout), all but one of those components will fail to appear. I cannot recall if it is the first or last that appears, but it's a moot point, because the code should not do that.
My advice would be as follows:
Don't extend JFrame (or JPanel).
Add one JPanel to the JFrame.
Add the components (and/or containers) to that JPanel.
Here is an example implementing points 2 & 3. Point 1 is not implemented (batteries not included).
import javax.swing.*;
public class SingleComponentLayoutProblem extends JFrame {
private final JTextField textField1;
private final JTextField textField2;
private final JTextField textField3;
private final JPasswordField passwordField;
public SingleComponentLayoutProblem() {
super("Title Text");
JPanel panel = new JPanel(); // uses FlowLayout be DEFAULT
add(panel);
textField1 = new JTextField(10);
//sets a the default value of 10.
panel.add(textField1);
textField2 = new JTextField("Enter a Text");
//sets default text of "Enter a Text" without the quotes
panel.add(textField2);
textField3 = new JTextField("Uneditable", 20);
//Displays Uneditable with a default value of 20.
//To make this Uneditable, you must do this...
textField3.setEditable(false);
//this makes the textField uneditable.
panel.add(textField3);
passwordField = new JPasswordField("myPassword");
panel.add(passwordField);
}
public static void main(String[] args) {
Runnable r = () -> {
SingleComponentLayoutProblem sclp =
new SingleComponentLayoutProblem();
sclp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this would close the window when X button is pressed.
// don't guess sizes! ..
//sclp.setSize(500, 500);
// .. instead ..
sclp.pack();
sclp.setVisible(true);
sclp.setLocationRelativeTo(null);
};
SwingUtilities.invokeLater(r);
}
}

Swing GUI and translator issues

So I have a class project where I have to create a translator where a user can enter in text, in English, hit a button, and get the Pig Latin translation.I have to use Swing GUI, FlowLayout, and JTextArea, with a separate JTextArea for the translation. My program brings up the GUI, it allows me to type in something, but when I hit the button, nothing happens. I looked through and it looks like I remembered to add everything to the JFrame, but I can't figure out why nothing is popping up.
// This program will take text that is English and translate it to Pig Latin
//import all the necessary packages for the program
import java.util.Scanner;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class PigLatin extends JFrame implements ActionListener{
public static final int WIDTH = 500;
public static final int HEIGHT= 400;
private JButton button;
private JTextArea original;
private JTextArea translation;
private JLabel english;
private JLabel pig;
public static void main(String[]args)
{
PigLatin gui = new PigLatin();
gui.setVisible(true);
/*
Scanner scan = new Scanner("far");
Scanner scan1 = new Scanner("and");
Scanner scan2 = new Scanner("away");
while (scan.hasNext())
{
//prints out original words
System.out.println(scan.next());
System.out.println(scan1.next());
System.out.println(scan2.next());
}
*/
}
public PigLatin()
{ //titles the box, creates size and what to do when 'x' is clicked
super("Pig latin translator");
this.setSize(WIDTH,HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setVisible(true);
//creates frame for everything to be added to
JPanel frame = new JPanel();
//creates labels for text boxes
english = new JLabel("English");
add(english);
//enters in origninal text
original = new JTextArea("Enter text here");
original.setEditable(true);
original.setLineWrap(true);
//adds the text area to the GUI
frame.add(original);
//create text area for translation
translation = new JTextArea();
translation.setEditable(false);
translation.setLineWrap(true);
//adds the text area to the GUI
frame.add(translation);
//adds the frame to the GUI
add(frame);
frame.setVisible(true);
//creates panel for the button
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout());
//create translate button
button = new JButton("TRANSLATE TO PIG LATIN");
button.addActionListener(this);
buttons.add(button);
JButton clear = new JButton("Clear");
buttons.add(clear);
//adds the buttons JPanel to the GUI
add(buttons);
}
private int findWordEnd(String text) {
int indexOfSpace = text.indexOf(" ");
if (indexOfSpace == -1) // Happens if there is no space
return text.length();
else
return indexOfSpace;
}
private int findVowel(String vowel)
{
int i;
//looks for vowel
for(i=0; i<vowel.length();i++)
{
if(vowel.charAt(i)=='a'||vowel.charAt(i)=='e'||vowel.charAt(i)=='i'||vowel.charAt(i)=='o'||vowel.charAt(i)=='u')
return i;
}
//if no vowels
return vowel.length();
}
private String englishToPig(String text)
{
String translate = "";
while(!text.equals(""))
{
//finds the first word
int wordEndIndex = findWordEnd(text);
String word = text.substring(0, wordEndIndex);
//finds the start and end in Pig Latin
int vowelIndex = findVowel(word);
String start = word.substring(vowelIndex);
String end = "-"+word.substring(0, vowelIndex)+"ay";
//creates the translation
translate = translate+start+end;
//gets rid of first word, so translation can continue
text = text.substring(wordEndIndex).trim();
}
return translate;
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == "TRANSLATE TO PIG LATIN") {
// Get the English they entered
String text = original.getText();
text = text.trim();
text = text.toLowerCase();
// Display the translation
translation.setText(englishToPig(text));
}
}
}
The source of the click event is the button. What you're interested in is the action command instead.
if (e.getActionCommand().equals("TRANSLATE TO PIG LATIN")) {
Also note equals() instead of ==. However, it's usually needless to use the same action listener for everything and then figure out between the sources in the listener. You could as well use an anonymous class, when the source is guaranteed to be the one you're interested in:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get the English they entered
String text = original.getText();
text = text.trim();
text = text.toLowerCase();
// Display the translation
translation.setText(englishToPig(text));
}
});
The clear button can then similarly have its own, as their functionality is not really related.

using string methods to count words

I am struggling with the below assignment:
assignment q:
using methods from the string class, write a program that will count the number of words which are separated by blanks in a string. For simplicity, use strings without punctuation or other white space characters(tabs, newlines etc). Use a JTextArea to allow the user to enter the text and allow the text area to scroll if necessary. when the user clicks a button to count the words , the total number of words counted is displayed in a textbox that cannot be modified by the user.
now my problem is that i am not getting the counted number to display in the un-editable textbox.
i also have the problem where the cusrsor is showing in the middle of the input screen instead of at the top.
please can you point me in the right direction.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.*;
public class WordCounter extends JFrame implements ActionListener
{
//Construct a panel for the fields and buttons
JPanel fieldPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Construct labels and text boxes
JTextField screen = new JTextField(1);
JLabel wordCount = new JLabel(" Word Count = ");
JTextField words = new JTextField(3);
//Construct button
JButton countButton = new JButton("Count Words");
public static void main(String[] args)
{
WordCounter f = new WordCounter();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,200);
f.setTitle("Word Counter");
f.setResizable(false);
f.setLocation(200,200);
f.setVisible(true);
}
public static int getWordCount(String screen)
{
int count = 0;
for (int i = 0; i < screen.length(); i++)
{
if (screen.charAt(i) == ' ')
{
count++;
}
}
return count;
}
public WordCounter()
{
Container c = getContentPane();
c.setLayout((new BorderLayout()));
fieldPanel.setLayout(new GridLayout(1,1));
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//add rows to panels
fieldPanel.add(screen);
//add button to panel
buttonPanel.add(countButton);
buttonPanel.add(wordCount);
buttonPanel.add(words);
//add panels to frame
c.add(fieldPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
//add functionality to button
countButton.addActionListener(this);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
int answer = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit?", "File Submission",JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION)
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{
}
}
To display the word count, you must modify your actionPerformed method like so:
public void actionPerformed(ActionEvent e)
{
words.setText(String.valueOf(getWordCount(screen.getText())));
}
And also your method for counting words produces incorrect result if the entered text doesn't end with a space. You could modify your getWordCount method for example like this to get correct word count:
public static int getWordCount(String screen)
{
String[] words = screen.split("\\s+");
return words.length;
}
And for your second problem: your cursor displays in the center because JTextField is a single line input. Use JTextArea instead. It is after all specified in your question that you should use it:
JTextArea screen = new JTextArea();
try it:
public static int getWordCount(String screen)
{
int count = 0;
string[] words = screen.split(' ');
count = words.Length;
return count;
}

How to print a string on the same window I typed and not in a popup in Java

So, this is my code:
import java.awt.*;
import javax.swing.*:
public class NewClass extends JFrame{
private JTextField item1;
private JTextField item3;
private JTextField item4;
public NewClass(){
super("The title");
setLayout(new FlowLayout());
item3 = new JTextField("Agrega el nombre del evento y da Enter", 22);
item3.setEditable(false);
add(item3);
item1 = new JTextField(22);
add(item1);
thehandler handler = new thehandler();
item1.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource()==item1)
string=String.format("Process ready: %s", event.getActionCommand());
else if(event.getSource()==item3)
string=String.format("field 3:%s", event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
}
}
And this is my main:
import javax.swing.JFrame;
public class ProyectoSOD {
public static void main(String[] args) {
NewClass odioSOD = new NewClass();
odioSOD.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
odioSOD.setSize(300, 350);
odioSOD.setVisible(true);
}
}
What I want to do, is to have the text in the TextField(from item3) saved unto another TextField with .setEditable(false) in the same window so I can write a text line(on item3), press enter, and have it saved in the same window, then rewrite the line, press enter, and have it shown with the previous text. I wanna be able to stack all this text everytime I press enter.
My current program has the message shown in a popup window, but I need to stack multiple lines.
Thanks :)
I'm not sure what you're looking to do. If you want to keep track of everything entered into the textfield, like a history of input, you could do what Eric Jablow said and use a JTextArea. So when the user enters input into the textfield and hits enter, it'll append the text from the textfield into the textarea.
http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html
That might be a good place to start.

Java submit button action

im training with GUI in Java. So I started creating pet game prototype or smth similar like game.
I have created menu to choose what to do, Register, Info, or Exit aplication.
Created fields and dorpdownBox to choose everything for register.
Also made sumbit button(its very start so i added just max characters validation on petName).
Now im stucked, i dont know how to take all information from dropdownBox and textbox that has been chosen and sent to other class Pet. I have googled but havent found anything that would be clear.
Maybe someone could give me some tips or write part for my code.
I want to take selected PetName , PetType, PetGender to other class pet.
P.s. i have copied many lines from google so I understand only 80-90% my code.
Main.java
import javax.swing.*;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener {
public static void main (String []args){
new Main("Meniu"); // Create title
}
// Main class constructor
public Main(String title) {
super(title);
setMenu(); //create menu
setSize(300, 400);// size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // close running program if window are closed
setLocationRelativeTo(null); // set window position at center
setResizable(false); //resizable or not
show();
}// Main class constructor
// menu choices
JMenuItem Registration, Apie, Exit;
// menu method for creation and style
private void setMenu() {
JMenuBar barObj = new JMenuBar(); // create menuBar obj
JMenu messagesObj = new JMenu("Meniu"); //create menu bar menu object
barObj.setBackground(Color.YELLOW); // set menu bar bg color
Registration = new JMenuItem("Registration");
Registration.setToolTipText("Push to register"); // write text when u hang mouse over
Registration.addActionListener(this);
Registration.setBackground(Color.WHITE); // set menu bar menu options bg color
messagesObj.add(Registration); // add Registration into messages
Apie = new JMenuItem("Apie");
Apie.setToolTipText("Push for information");
Apie.addActionListener(this);
Apie.setBackground(Color.WHITE);
messagesObj.add(Apie);
Exit = new JMenuItem("Exit");
Exit.setToolTipText("Here you will exit");
Exit.addActionListener(this);
Exit.setBackground(Color.WHITE);
messagesObj.add(Exit);
barObj.add(messagesObj);
setJMenuBar(barObj);
} //create menu end
// implemented method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Registration){
int registReply = JOptionPane.showConfirmDialog(this, "Norite registruotis?",
"Išeiti", JOptionPane.YES_NO_OPTION);
if(registReply == JOptionPane.YES_OPTION){ //registReply is what u have choosen
petRegistration ();
}
}else if (e.getSource() == Apie)
JOptionPane.showMessageDialog(this, "Jus esate informacijos lange.", "Apie", JOptionPane.PLAIN_MESSAGE);
else if (e.getSource() == Exit){
int exitReply = JOptionPane.showConfirmDialog(this, "Ar norite Exit?",
"Išeiti", JOptionPane.YES_NO_OPTION);// exitReply is what u have choosen
if(exitReply == JOptionPane.YES_OPTION){// if its has been chose/ program will shutdown
System.exit(0);
}
} // if end
}// actionPerformed
public void petRegistration(){
Container container = getContentPane();
// petName textbox and label
JTextField jtfRegLabel = new JTextField("***Registration***", 25);
jtfRegLabel.setHorizontalAlignment(JTextField.CENTER);
jtfRegLabel.setEditable(false);
JTextField jtfText1 = new JTextField(7);
JTextField jtfNameLabel = new JTextField("Pet Name (min 3, max 16 letters)", 17);
jtfNameLabel.setEditable(false);
jtfText1.setDocument(new JTextFieldLimit(16)); // add limit to text box
// pettype combobox and label
Frame frame = new Frame("Choice");
Label label = new Label("What is your Choice:");
Choice choice = new Choice();
frame.add(choice);
choice.add("Cat ");
choice.add("Dog ");
choice.add("Fish ");
choice.add("Mouse ");
choice.add("Bird ");
choice.add("Horse ");
JTextField jtfTypeLabel = new JTextField("Pet Type, Choose one ", 17);
jtfTypeLabel.setEditable(false);
// petGender combobox and label
Choice choice1 = new Choice();
frame.add(choice1);
choice1.add("Male ");
choice1.add("Female ");
JTextField jtfGenderLabel = new JTextField("Pet Gender, Choose one ", 17);
jtfGenderLabel.setEditable(false);
// submit registration
JButton submitRegObj = new JButton("Submit");
container.add(jtfRegLabel);
container.add(jtfText1);
container.add(jtfNameLabel);
container.add(choice);
container.add(jtfTypeLabel);
container.add(choice1);
container.add(jtfGenderLabel);
container.add(submitRegObj);
container.setLayout(new FlowLayout());
setSize(300, 400); // set size of window
setVisible(true);// set it visible
}
}// Main clases end
Pet.java
public class Pet {
private String petName;
private String petType;
private String petGender;
public Pet(String petName, String petType, String petGender) {
super();
this.petName = petName;
this.petType = petType;
this.petGender = petGender;
}
}
I think JTextFieldLimit class is necessary. Its just make max characters validation.
Thanks.
Firstly, you are mixing frameworks. Swing and AWT components don't play well together. I'd highly recommend against using AWT components and stick to the Swing framework.
Secondly, don't use JTextFields for labels, that's what JLabel is for
Start by taking the fields that are used for registriation and add them to their own JPanel as class instance fields...
public class RegistrationPanel extends JPanel {
JTextField jtfName;
JComboBox cbType;
JComboBox cbSex;
// Constructor and other code //
}
Then, in your RegistrationPanel, provide appropriate setters and getters...
public String getPetName() {
return jtfName.getText();
}
public void setPetName(String name) {
jtfName.setText(name);
}
// Other setters and getters //
This way, when you need it, you can retrieve the values from the panel.
When the user selects the registration menu, you would create a new instance of this panel and add it to your frame. You could even make use of a CardLayout to help switch between views
To make life easier, use enum types for restricted values like type and sex.
I highly recommend that you take the time to read through
Creating a GUI with Swing
Enum Types

Categories