Swing GUI and translator issues - java

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.

Related

I want to keep the values of Textarea from Textfield permanently (Java GUI)

I want to keep the values of Textarea1 after inputting them through the textfield1 via a button. Everytime I finish running it the value disappears for a new one. The first time I do it I get the value of the name I inserted, however when i do it a second time it erases. please help me, thanks. Here is the code:
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.border.Border;
import javax.swing.*;
public class GUI_project2 extends JFrame {
private JMenuBar menuBar;
private JButton button1;
private JTextArea textarea1;
private JTextField textfield1;
static String MYARRAY[] = new String[4];
static int COUNTER = 0;
static String NEWITEM = null;
//Constructor
public GUI_project2(){
this.setTitle("GUI_project2");
this.setSize(1118,845);
//menu generate method
generateMenu();
this.setJMenuBar(menuBar);
//pane with null layout
JPanel contentPane = new JPanel(null);
contentPane.setPreferredSize(new Dimension(1118,845));
contentPane.setBackground(new Color(192,192,192));
button1 = new JButton();
button1.setBounds(206,109,90,35);
button1.setBackground(new Color(214,217,223));
button1.setForeground(new Color(0,0,0));
button1.setEnabled(true);
button1.setFont(new Font("sansserif",0,12));
button1.setText("Add Word");
button1.setVisible(true);
//Set methods for mouse events
//Call defined methods
button1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
ButtonClicked(evt);
}
});
textfield1 = new JTextField();
textfield1.setBounds(203,46,90,35);
textfield1.setBackground(new Color(255,255,255));
textfield1.setForeground(new Color(0,0,0));
textfield1.setEnabled(true);
textfield1.setFont(new Font("sansserif",0,12));
textfield1.setText("");
textfield1.setVisible(true);
textarea1 = new JTextArea();
textarea1.setBounds(27,48,150,100);
textarea1.setBackground(new Color(255,255,255));
textarea1.setForeground(new Color(0,0,0));
textarea1.setEnabled(true);
textarea1.setFont(new Font("sansserif",0,12));
textarea1.setText("");
textarea1.setBorder(BorderFactory.createBevelBorder(1));
textarea1.setVisible(true);
//adding components to contentPane panel
contentPane.add(button1);
contentPane.add(textfield1);
contentPane.add(textarea1);
//adding panel to JFrame and seting of window position and close operation
this.add(contentPane);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.pack();
this.setVisible(true);
}
//Method mouseClicked for button1
private void ButtonClicked (MouseEvent evt) {
//TODO
NEWITEM = textfield1.getText();
if (NEWITEM.compareTo("end")!=0){
MYARRAY[COUNTER] = NEWITEM;
COUNTER++;
if (COUNTER == MYARRAY.length){
increaseArraySize();
}
}
String NEWITEM = "";
listArray();
}
public void listArray(){
for (int X=0;X<MYARRAY.length;X++){
textarea1.setText(textfield1.getText());
}
}
public static void increaseArraySize(){
System.out.print("Here we increase the size to ");
String TEMP[] = new String[MYARRAY.length*2];
System.arraycopy(MYARRAY, 0, TEMP, 0, MYARRAY.length);
MYARRAY = TEMP;
System.out.println(TEMP.length);
}
//method for generate menu
public void generateMenu(){
menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu tools = new JMenu("Tools");
JMenu help = new JMenu("Help");
JMenuItem open = new JMenuItem("Open ");
JMenuItem save = new JMenuItem("Save ");
JMenuItem exit = new JMenuItem("Exit ");
JMenuItem preferences = new JMenuItem("Preferences ");
JMenuItem about = new JMenuItem("About ");
file.add(open);
file.add(save);
file.addSeparator();
file.add(exit);
tools.add(preferences);
help.add(about);
menuBar.add(file);
menuBar.add(tools);
menuBar.add(help);
}
public static void main(String[] args){
System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUI_project2();
}
});
}
}
The first time I do it I get the value of the name I inserted, however when i do it a second time it erases
What do you think the setText(..) method does? Did you read the API for a description of the method?
textarea1.setText(textfield1.getText());
should be:
textarea1.append(textfield1.getText());
You can't program if you don't read the API! Take the time now to read the JTextArea API for other methods you may find useful in the future.
Every time you call textarea1.setText(someText), you are setting a fresh new content on the textarea that comes and replaces any other text that was here before.
What you should do is:
final StringBuilder content = new StringBuilder();
for (int X=0;X<MYARRAY.length;X++){
sb.append(MYARRAY[X]);
//Add this line if you eventually want to add a new line
sb.append("\r\n");
}
textarea1.setText(sb.toString());
Hello CSStudent I tried to stay as close as your code as possible and edited your listArray method in order to achieve what you are Aiming for.
I want to keep the values of Textarea1 after inputting them through the textfield1 via a button. Everytime I finish running it the value disappears for a new one. The first time I do it I get the value of the name I inserted, however when i do it a second time it erases. please help me, thanks. Here is the code:
What your current code does is 'SETTING' the text of your textarea.
According to the Docs setText does this:
Sets the text of this TextComponent to the specified text. If the text is null or empty, has the effect of simply deleting the old text. When text has been inserted, the resulting caret location is determined by the implementation of the caret class.
So lets take a look at your listArray method.
public void listArray(){
for (int X=0;X<MYARRAY.length;X++){
textarea1.setText(textfield1.getText());
}
}
It loops through your String Array which starts at the Size of 4 and increases by *2 if required. The problem is that since the size of the Array is 4 and you add the String on position 0 the array looks like this {"First thing you insert",null,null,null} according to the quote from the docs if the value is null or empty it will simply delete the old text. This is why it erases as you say.
However if you slighty modify it you will achieve what you desire
public void listArray(){
textarea1.setText("");
for (int X=0;X<MYARRAY.length;X++){
if(MYARRAY[X] != null)
textarea1.append(MYARRAY[X]+"\n");
}
}
As stated earlier I tried to stay as close to your code as possible, let me explain what this does aswell.
First of all it clears the textarea by inserting "" which is a blank String, followed by that it will loop through your Array and only IF it IS NOT (!=) null it will append the saved String and a linebreak ("\n"). (This check prevents the textarea from getting erased)
If this reply solved your Problem please make sure to mark my answer as accepted, click on the check mark beside the answer to toggle it from hollow to green

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;
}

Trying to create a character counter, but my button is not updating the while loop boolean to do so

so I am trying to make a small java program to count the number of characters in a given string.
Right now, my code works in the console output, but it is not updating the text field I have created in a JFrame and I am unsure why. Can someone please explain this to me?
BTW: I have set "onPress" to true, so the button doesn't really have an effect right now, I'm just trying to test the functionality of the program before I implement button functionality.
Thank you :)! Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class characterCounterTwov2 extends JFrame {
static boolean onPress = true;
public characterCounterTwov2(){
/*******************/
/* Local Variables */
/*******************/
//creates a new Jframe to put our frame objets in
JFrame frame = new JFrame();
//creates a text field frame object
JTextField txtField = new JTextField("Enter your text here", 25);
//stores the string of the the jtextfield into a variable text
String text = txtField.getText();
//creates a text field that is uneditable with the word "characters"
String charString = "Characters: ";
JTextField charField = new JTextField(charString, 25);
charField.setEditable(false);
//integer to count the characters
int charCounter = 0;
//string that will be used in a text field to display the # of chars
String charCount = Integer.toString(charCounter);
//Text field that displays charCount
JTextField charFieldTwo = new JTextField(charCount, 10);
//calculate button
JButton calcButton = new JButton("Calculate");
calcButton.addActionListener(new calcButtonFunc());
/*******************/
/* Frame Setup */
/*******************/
//sets the layout of the frame
frame.setLayout(new BorderLayout());
//add's elements to the frame
frame.add(txtField, BorderLayout.NORTH);
frame.add(charField, BorderLayout.CENTER);
frame.add(charFieldTwo, BorderLayout.SOUTH);
frame.add(calcButton, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
//begin while loop
//infinite while loop
System.out.println("Entering main while loop");
while(true)
{
while(onPress == true)
{
System.out.println("text length is:" + charCount);
for(int i = 0; i < text.length(); i++)
{
charCounter++;
System.out.println("Number of characters:" + charCounter);
}
//charCount = Integer.toString(charCounter);
onPress = false;
}
}
}
static class calcButtonFunc implements ActionListener
{
public void actionPerformed(java.awt.event.ActionEvent event)
{
onPress = true;
}
}
public static void main(String[] args){
new characterCounterTwov2();
System.out.println("End of program. Should not get here");
}
}
~~~~~~~~~
EDIT
I was given a lot of helpful tips by Hovercraft Full of Eels, and cleaned up my code. I am still having a problem with calculating the character count on button press, and having it reflect in the GUI. I am thinking my bug lies within the line "text = txtField.getText();" inside my button listener class.
Here is my updated code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class characterCounterTwov4{
//creates a new Jframe to put our frame objets in
JFrame frame = new JFrame();
//creates a text field frame object
JTextField txtField = new JTextField(25);
//stores the string of the the jtextfield into a variable text
String text = txtField.getText();
//creates a text field that is uneditable with the word "characters"
String charString = "Characters: ";
JTextField charField = new JTextField(charString, 25);
public characterCounterTwov4(){
charField.setEditable(false);
//integer to count the characters
int charCounter = 0;
//string that will be used in a text field to display the # of chars
String charCount = Integer.toString(text.length());
//Text field that displays charCount
JTextField charFieldTwo = new JTextField(charCount, 10);
//calculate button
JButton calcButton = new JButton("Calculate");
calcButton.addActionListener(new ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event)
{
System.out.println("button pressed");
//stores the string of the the jtextfield into a variable text
text = txtField.getText();
//string that will be used in a text field to display the # of chars
String charCount = Integer.toString(text.length());
//Text field that displays charCount
JTextField charFieldTwo = new JTextField(charCount, 10);
}
});
/*******************/
/* Frame Setup */
/*******************/
//sets the layout of the frame
frame.setLayout(new BorderLayout());
//add's elements to the frame
frame.add(txtField, BorderLayout.NORTH);
frame.add(charField, BorderLayout.CENTER);
frame.add(charFieldTwo, BorderLayout.SOUTH);
frame.add(calcButton, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
new characterCounterTwov4();
System.out.println("End of program. Should not get here");
}
}
Your code is not structured for correct Swing GUI event-driven programming but rather looks like a linear console program that is being shoe-horned into a GUI. Get rid of that while loop, get rid of that static boolean variable. Instead give your class a non-static (instance) int counter variable and a JTextField non-static variable and simply increment your counter in the actionPerformed method and display the results in the JTextField (or JLabel if you prefer).
So the actionPerformed could look something like:
public void actionPerformed(ActionEVent e) {
counter++; // increment the counter variable
charCount.setText("Count: " + counter); // display the results
}
and again, counter and charCount are non-static and are declared and initialized in the class, not inside of the constructor or any method.
Edit
Additional notes:
Why does your class extend JFrame when you don't use it as a JFrame?
In general, it's a good idea to start all Swing proggrams on the Swing Event Dispatch Thread or EDT. This can be done by passing a Runnable with your start-up code in it to the SwingUtilities static method invokeLater(...).
For example:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
// create and display your GUI from in here
MainGui mainGui = new MainGui();
JFrame mainFrame = new JFrame("Main GUI");
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.add(mainGui);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
Edit 2
Oops, I read your requirements wrong. You need to count the chars in a String, and so you will need another class instance JTextField, one to hold the user's String, get rid of the counter instance field since it no longer will be needed, and then in the actionPerformed method, simply get the String from the JTextField, get its length, and display the length in another JTextField or in a JLabel, again your choice.
Edit 3
Your code is now almost there!
Problems:
The charFieldTwo variable is a non-final local variable. To be able to use it in your anonymous inner class, either make it final, and note that doing this won't harm its ability to work since it is a reference variable, not a primite,
Or you could move its declaration out of the constructor, like you do the other variables.
Once you've done this, it is easy to call charFieldTwo.setText(charCount); on it at the bottom of your ActionListener, and you're pretty much done.

Random Name Generator (inside frame)

I'm trying to create a name generator that generates names by random.
Now when i click the button, it generates a name, but it shows up in the Eclipse console and not in the same window as the button, which is what I want it to do.
Eventually I would like to be able to have a specific picture for for the button and for the background (window/frame). Also, as a bonus I'm hoping to add a bit of music to it that can play in the background once you open the app.
Now, I'm fairly new to java and I've only watched a couple of tutorials, but it's gotten me this far and hopefully I can learn a thing or two from one of you guys.
So please be kind, Best regards leal.
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class ClanNameGenerator {
public static void main (String[] args){
JFrame frame = new JFrame("ExETesT");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,350);
JPanel panel = new JPanel ();
frame.add(panel);
JButton button = new JButton("Click me");
panel.add(button);
button.addActionListener(new Action());
}
static class Action implements ActionListener{
public void actionPerformed (ActionEvent e){
String[] names = {"test", "Zero", "Club", "Moonkys", "znakes", "SeamOnster", "dnktwhm", "Rambo", "OmG", "siste"};
String[] names2 = {"Ylos", "zzzzz", "sdsd", "OK"};
String[] names3 = {"Hei", "ok", "jadd", "så drar vi", "det var det"};
int random = (int) (Math.random()*names.length);
int random2 = (int) (Math.random()*names2.length);
int random3 = (int) (Math.random()*names3.length);
System.out.println("Your clan name is: " + names[random] +" "+ names2[random2] +" "+ names3[random3]);
}
}
}
if you do something like this, the name will appear in JFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClanNameGenerator {
private static JLabel label;
public static void main (String[] args){
JFrame frame = new JFrame("ExETesT");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,350);
JPanel panel = new JPanel ();
frame.add(panel);
JButton button = new JButton("Click me");
panel.add(button);
label = new JLabel();
panel.add(label);
button.addActionListener(new Action());
}
static class Action implements ActionListener{
public void actionPerformed (ActionEvent e){
String[] names = {"test", "Zero", "Club", "Moonkys", "znakes", "SeamOnster", "dnktwhm", "Rambo", "OmG", "siste"};
String[] names2 = {"Ylos", "zzzzz", "sdsd", "OK"};
String[] names3 = {"Hei", "ok", "jadd", "så drar vi", "det var det"};
int random = (int) (Math.random()*names.length);
int random2 = (int) (Math.random()*names2.length);
int random3 = (int) (Math.random()*names3.length);
label.setText("Your clan name is: " + names[random] +" "+ names2[random2] +" "+ names3[random3]);
}
}
}
There's a lot going on in your question without you actually asking any questions. As for your text problem though, System.out.println(); will always print to the console, wherever it may be. To add it to the JFrame, you have a variety of options. The one you probably want is to use a JLabel, unless you have a lot of text, in which case a JTextArea may be better suited, or if you intend to do something a little fancier than regular text you may want to draw it directly using the Graphics class and drawString(String).
How to add text to JFrame?
As for the other parts of your... "question," do some research and try things before asking for help on the Stack. This community is for assisting you when things don't work, not for writing your projects for you.
Add a JLabel to your UI, then call the setText method of that JLabel object.
jLabelObject.setText("Your clan name is: " +
names[random] +" "+ names2[random2] +" "+ names3[random3);

How to display a mask in jtextfield?

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);
}
}

Categories