Using Multiple ActionListeners in Java Swing - java

My problem is that at the moment I am making a GUI for a game and this GUI has many buttons. I had a problem earlier in my code where the actionListener I was using was looking for events in two buttons in rapid succession, not giving enough time for the second button to perform and action and rendering it useless. I thought I overcame that by making the second button a different actionListener in an inner class
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
and now I'm trying to do the same for a third (and eventually fourth and fifth button
P1Roll.addActionListener(new ActionListener(){
public void ActionPerformed(ActionEvent e){
but it is throwing me all kinds of errors. As I am very new to swing, I am unsure how to proceed. Any tips on this, or anything in my code at all would be very much appreciated. :)
import java.awt.Font;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.Border;
public class GUI_Windows extends JFrame implements ActionListener {
public static void main(String[] args) {
new GUI_Windows();
Random rand1, rand2, rand3, rand4;
int dice1, dice2, dice3, dice4;
int numTurns = Turns.getValue();
rand1 = new Random();
rand2 = new Random();
rand3 = new Random();
rand4 = new Random();
dice1 = rand1.nextInt(6 - 1 + 1) + 1;
dice2 = rand2.nextInt(6 - 1 + 1) + 1;
dice3 = rand3.nextInt(6 - 1 + 1) + 1;
dice4 = rand4.nextInt(6 - 1 + 1) + 1;
}
Box MegaBox, box1, box2, box3, box4, box5, box6, box7, box8, box9, box10,
box11;
Box Minibox1, Minibox2, Minibox3, Minibox4, Minibox5, MiniMegaBox;
Box MegaBox2, box12, box13, box14, box15, box16, box17, box18, box19,
box20, box21, box22, box23;
JLabel TitleLabel, InstructionLabel, Instructions, SelectMode, LoG;
Border spacer1 = BorderFactory.createEmptyBorder(5, 5, 50, 5);
Border spacer2 = BorderFactory.createEmptyBorder(5, 60, 5, 0);
Border spacer3 = BorderFactory.createEmptyBorder(5, 0, 5, 60);
Border spacer4 = BorderFactory.createEmptyBorder(0, 0, 5, 45);
Border spacer5 = BorderFactory.createEmptyBorder(0, 0, 6, 0);
Border spacer6 = BorderFactory.createEmptyBorder(5, 10, 0, 70);
Border spacer7 = BorderFactory.createEmptyBorder(0, 0, 0, 35);
JRadioButton button1, button2;
JButton button3, button4;
JButton button5, button6;
static JSlider Turns;
public GUI_Windows() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
button3.doClick();
}
});
this.setTitle("Bottom Out!");
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setResizable(false);
this.setLocation(500, 125);
this.setSize(350, 421);
MegaBox = Box.createVerticalBox();
box1 = Box.createVerticalBox();
box1.setBorder(spacer1);
box2 = Box.createVerticalBox();
box2.setBorder(spacer2);
box3 = Box.createHorizontalBox();
box4 = Box.createHorizontalBox();
box4.setBorder(spacer3);
box5 = Box.createVerticalBox();
box5.setBorder(spacer5);
box6 = Box.createHorizontalBox();
box7 = Box.createHorizontalBox();
box8 = Box.createHorizontalBox();
box9 = Box.createHorizontalBox();
box10 = Box.createHorizontalBox();
box10.setBorder(spacer7);
box11 = Box.createHorizontalBox();
box11.setBorder(spacer6);
button1 = new JRadioButton();
button1.addActionListener(this);
button2 = new JRadioButton();
button2.addActionListener(this);
TitleLabel = new JLabel("BOTTOM OUT");
TitleLabel.setFont(new Font("Times New Roman", Font.BOLD, 20));
TitleLabel.setAlignmentY(1);
InstructionLabel = new JLabel("Instructions:");
InstructionLabel.setAlignmentY(0);
InstructionLabel.setFont(new Font("Arial", Font.BOLD, 15));
Instructions = new JLabel();
Instructions.setAlignmentY(0);
Instructions
.setText("<HTML>Each game will be 3 - 20 turns, with either One Player versus the Computer, or Two Players "
+ "versus each other. Each turn, you will roll two die, and then the two die are totaled up, and "
+ "multiplied by the number of the roll it is for that turn. If this total is equal to, or higher than the "
+ "total of your last scores in that turn, than you add those points to your score for that turn. Then you "
+ "may choose to roll again, or end your turn to lock in your points for that turn.</HTML>");
SelectMode = new JLabel("Select Mode:");
SelectMode.setFont(new Font("Arial", Font.BOLD, 15));
LoG = new JLabel("Select number of Turns:");
Turns = new JSlider(2, 20, 2);
Turns.setMajorTickSpacing(2);
Turns.setMinorTickSpacing(1);
Turns.setPaintTicks(true);
Turns.setPaintLabels(true);
Turns.setSnapToTicks(true);
button3 = new JButton("Quit");
button3.setVisible(true);
button3.addActionListener(this);
button4 = new JButton("Next");
button4.setVisible(true);
button4.addActionListener(this);
button5 = new JButton("Done");
button5.setVisible(true);
// button5.addActionListener(this);
button6 = new JButton("Done");
button6.setVisible(true);
button6.addActionListener(this);
ButtonGroup group1 = new ButtonGroup();
group1.add(button1);
group1.add(button2);
ButtonGroup group2 = new ButtonGroup();
group2.add(button3);
group2.add(button4);
box6.add(TitleLabel);
box7.add(InstructionLabel);
box7.add(Box.createHorizontalGlue());
box7.add(new JLabel(" "));
box8.add(Instructions);
box3.add(SelectMode);
box3.add(Box.createHorizontalGlue());
box3.add(new JLabel(" "));
box4.add(button1);
box4.add(new JLabel(" One Player"));
box4.add(Box.createHorizontalGlue());
box4.add(button2);
box4.add(new JLabel(" Two Players"));
box9.add(LoG);
box9.setBorder(spacer4);
box10.add(Turns);
box10.add(Box.createHorizontalGlue());
box10.add(new JLabel(" "));
box11.add(button3);
box11.add(Box.createHorizontalGlue());
box11.add(button4);
box1.add(box6);
box1.add(box7);
box1.add(box8);
box5.add(box3);
box5.add(box4);
box2.add(box5);
box2.add(box9);
box2.add(box10);
box2.add(box11);
MegaBox.add(box1);
MegaBox.add(box2);
this.add(MegaBox);
this.setVisible(true);
}
int onePlayer = 0;
int isDone = 0;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button3) {
System.exit(0);
}
if (button1.isSelected()) {
onePlayer = 1;
} else if (button2.isSelected()) {
onePlayer = 2;
}
if (e.getSource() == button4 && onePlayer == 0) {
JOptionPane.showMessageDialog(button1,
"You must select the number of players!", "Try again!",
JOptionPane.WARNING_MESSAGE);
} else if (e.getSource() == button4 && onePlayer != 0) {
final JFrame pFrame = new JFrame();
pFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pFrame.setTitle("Bottom Out!");
pFrame.setResizable(false);
pFrame.setLocation(500, 125);
pFrame.setSize(250, 200);
JLabel EnterName1, EnterName2;
final JTextField NameBox1;
final JTextField NameBox2;
Border border1 = BorderFactory.createEmptyBorder(5, 25, 15, 25);
Border border2 = BorderFactory.createEmptyBorder(15, 25, 5, 25);
Border border3 = BorderFactory.createEmptyBorder(5, 0, 5, 0);
EnterName1 = new JLabel("Player 1, please enter your name:");
EnterName2 = new JLabel("Player 2, please enter your name:");
NameBox1 = new JTextField("Miller");
NameBox2 = new JTextField("Julian");
if (onePlayer == 1) {
NameBox2.setEditable(false);
NameBox2.setText("Watson");
}
Minibox1 = Box.createVerticalBox();
Minibox2 = Box.createVerticalBox();
Minibox3 = Box.createVerticalBox();
Minibox4 = Box.createHorizontalBox();
MiniMegaBox = Box.createVerticalBox();
Minibox1.add(EnterName1);
Minibox1.add(NameBox1);
Minibox1.setBorder(border1);
Minibox2.add(EnterName2);
Minibox2.add(NameBox2);
Minibox2.setBorder(border2);
Minibox3.add(Minibox1);
Minibox3.add(Minibox2);
Minibox4.add(new JLabel(" "));
Minibox4.add(Box.createHorizontalGlue());
Minibox4.add(button5);
Minibox4.add(Box.createHorizontalGlue());
Minibox4.add(new JLabel(" "));
Minibox4.setBorder(border3);
MiniMegaBox.add(Minibox3);
MiniMegaBox.add(Minibox4);
pFrame.add(MiniMegaBox);
pFrame.setVisible(true);
this.setVisible(false);
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button5) {
Border spaceBorder1 = BorderFactory.createEmptyBorder(
45, 45, 15, 45);
Border spaceBorder2 = BorderFactory.createEmptyBorder(
15, 45, 30, 45);
Border spaceBorder3 = BorderFactory.createEmptyBorder(
5, 15, 5, 0);
Border spaceBorder4 = BorderFactory.createEmptyBorder(
5, 0, 10, 10);
Border spaceborder5 = BorderFactory.createEmptyBorder(
0, 0, 15, 0);
Border spaceborder6 = BorderFactory.createEmptyBorder(
15, 0, 0, 0);
JFrame gFrame = new JFrame();
gFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gFrame.setTitle("Bottom Out!");
gFrame.setResizable(false);
gFrame.setLocation(500, 125);
gFrame.setSize(350, 421);
TitleLabel = new JLabel("BOTTOM OUT");
TitleLabel.setFont(new Font("Times New Roman",
Font.BOLD, 20));
TitleLabel.setAlignmentY(1);
box23 = Box.createHorizontalBox();
box23.add(TitleLabel);
box23.setBorder(spaceborder6);
box12 = Box.createHorizontalBox();
box12.setBorder(spaceBorder1);
box13 = Box.createHorizontalBox();
box13.setBorder(spaceBorder2);
box14 = Box.createHorizontalBox();
box14.setBorder(spaceborder5);
box15 = Box.createVerticalBox();
box16 = Box.createHorizontalBox();
box16.setBorder(spaceBorder3);
box17 = Box.createHorizontalBox();
box17.setBorder(spaceBorder3);
box18 = Box.createHorizontalBox();
box18.setBorder(spaceBorder3);
box19 = Box.createHorizontalBox();
box19.setBorder(spaceBorder3);
box20 = Box.createHorizontalBox();
box20.setBorder(spaceBorder3);
box21 = Box.createHorizontalBox();
box21.setBorder(spaceBorder4);
box22 = Box.createVerticalBox();
MegaBox2 = Box.createVerticalBox();
JLabel Player1, Player2, P1Score, P2Score;
JButton P1Roll, P2Roll, EndTurn;
JLabel TurnNum, TurnMax, TurnsRem, P1TScore, P2TScore, Winner;
Player1 = new JLabel(NameBox1.getText() + ":");
P1Score = new JLabel("Score");
P1Roll = new JButton("Roll!");
Player2 = new JLabel(NameBox2.getText() + ":");
P2Score = new JLabel("Score");
P2Roll = new JButton("Roll!");
EndTurn = new JButton("End Turn");
TurnNum = new JLabel("Turn Number: ");
TurnMax = new JLabel("Turn max: ");
TurnsRem = new JLabel("Turns left: ");
P1TScore = new JLabel("Player 1 Score: ");
P2TScore = new JLabel("Player 2 Score: ");
Winner = new JLabel("Player is Winning");
box12.add(Player1);
box12.add(Box.createHorizontalGlue());
box12.add(P1Score);
box12.add(Box.createHorizontalGlue());
box12.add(P1Roll);
box13.add(Player2);
box13.add(Box.createHorizontalGlue());
box13.add(P2Score);
box13.add(Box.createHorizontalGlue());
box13.add(P2Roll);
box14.add(new JLabel(" "));
box14.add(Box.createHorizontalGlue());
box14.add(EndTurn);
box14.add(Box.createHorizontalGlue());
box14.add(new JLabel(" "));
box15.add(box23);
box15.add(box12);
box15.add(box13);
box15.add(box14);
box16.add(TurnNum);
box16.add(Box.createHorizontalGlue());
box16.add(new JLabel(" "));
box17.add(TurnMax);
box17.add(Box.createHorizontalGlue());
box17.add(new JLabel(" "));
box18.add(TurnsRem);
box18.add(Box.createHorizontalGlue());
box18.add(new JLabel(" "));
box19.add(P1TScore);
box19.add(Box.createHorizontalGlue());
box19.add(new JLabel(" "));
box20.add(P2TScore);
box20.add(Box.createHorizontalGlue());
box20.add(new JLabel(" "));
box21.add(new JLabel(" "));
box21.add(Box.createHorizontalGlue());
box21.add(Winner);
box22.add(box16);
box22.add(box17);
box22.add(box18);
box22.add(box19);
box22.add(box20);
box22.add(box21);
MegaBox2.add(box15);
MegaBox2.add(box22);
gFrame.add(MegaBox2);
gFrame.setVisible(true);
pFrame.setVisible(false);
P1Roll.addActionListener(new ActionListener(){ public void ActionPerformed(ActionEvent e){
}
#Override
public void actionPerformed(ActionEvent e) {
int turnNum;
for(turnNum; numTurns > 0 ; numTurns -- ){
}
}});
}
}
});
}
}}

From an initial reading of the code, it appears you're creating the anonymous ActionListener with incorrect syntax.
P1Roll.addActionListener(new ActionListener(){ public void ActionPerformed(ActionEvent e){
}
#Override
public void actionPerformed(ActionEvent e) {
int turnNum;
for(turnNum; numTurns > 0 ; numTurns -- ){
}
}});
Should be
P1Roll.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e)
{
int turnNum;
for(turnNum; numTurns > 0 ; numTurns -- )
{
}
});

Related

How do I make a JButton hit the enter key when pressed?

So in my code, I have 2 JTextField inputs that need input for the rest of the program to work. Both of them contain variables that cannot be left empty for the rest of the program to work. The problem is that whenever you enter something into the text field, you have to press enter in the end and that process is not that straightforward in the program as you are not able to see whether or not you have already pressed enter without looking into the console.
ActionListener buttonlistener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame2.setTitle("Multiplayer");
frame2.setVisible(true);
JLabel labelM = new JLabel("Geben sie eine Höhstzahl ein:");
JTextField hZahl = new JTextField();
JLabel labelN= new JLabel("Mit wie vielen Rateversuchen wollen sie spielen?");
JTextField rVers = new JTextField();
JButton b = new JButton("Submit");
Now I want the JButton b to press enter for both text field hZahl and rVers when pushed. How do I achieve that?
This is what button bdoes so far:
ActionListener buttonlistener3 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if((arr[0] > 0) && (arr[1] > 0)){
frame3.setTitle("1 Player Game");
frame3.setVisible(true);
JLabel labelB = new JLabel("Erraten sie die Zahl:");
JTextField rVers1 = new JTextField();
labelB.setBounds(50, 105, 400, 70);
rVers1.setBounds(45, 150, 100, 30);
frame3.add(labelB);
frame3.add(rVers1);
rVers1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.out.println("Rateversuch: " + rVers1.getText());
int r = Integer.parseInt(rVers1.getText());
arr[2] = r;
System.out.println("werte " + arr[1] +" " + arr[3] +" " + r);
if(arr[1] == 1){
JLabel lv = new JLabel("Letzer Versuch!");
lv.setBounds(50, 50, 400, 70);
lv.setForeground(Color.red);
frame4.add(lv);
}
tru = arr[3] == arr[2];
if(r < arr[3]){
labelB.setText("Die Gesuchte Zahl ist größer.");
rVers1.setText("");
arr[1] = arr[1] -1;
}
if(r > arr[3]){
labelB.setText("Die Gesuchte Zahl ist kleiner.");
rVers1.setText("");
arr[1] = arr[1] -1;
}
if(tru){
frame4.setVisible(true);
JLabel cor = new JLabel("Richtig!");
JLabel win = new JLabel("Sie haben Gewonnen");
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.green);
frame4.add(cor);
frame4.add(win);
}
if(arr[1] == 0){
frame4.setVisible(true);
JLabel cor = new JLabel("Falsch!");
JLabel win = new JLabel("Die Zahl war: " + arr[3]);
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.green);
frame4.add(cor);
frame4.add(win);
}
if(arr[1] == 0){
frame4.setVisible(true);
JLabel cor = new JLabel("Falsch!");
JLabel win = new JLabel("Die Zahl war: " + arr[3]);
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.red);
frame4.add(cor);
frame4.add(win);
}
System.out.println("werte neu " + arr[1] +" " + arr[3] +" " + r);
}
});
}
}
};
b.addActionListener(buttonlistener3);
}
};

How can I clear the JTextField and have it ready for input immediately without requiring a click or other action?

I posted my full code below so you guys could have a solid understanding of what I want. When I click send, the text field clears but is not ready for input. I have to click for the input. I want it to be ready for the input immediately and textfield.setText("") will not work. Any ideas?
package javaapplication2;
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.*;
import javax.swing.*;//class to use to create GUI's
import javax.swing.border.Border;
import javax.swing.plaf.FontUIResource;
/**
*
* #author Jordan Anthony Hangman with dictionary
*/
public class JavaApplication2 extends JFrame{
static JLabel[] labels = new JLabel[20];//labels for displaying words under 20 characters
static int counter = 0;
static int badguess = 0;//keeps track of wrong guesses
static String wordbank = " Letter Bank:";
static char[] guesses = new char[26];
static int nguesses = 0;
static int amountc = 0;
public JavaApplication2(){
}
public static void main(String[] args) throws FileNotFoundException, IOException {
//Loading images to use for hangman game
ImageIcon hanginit = new ImageIcon("hangmaninit.jpg");
ImageIcon hang1 = new ImageIcon("hangman1.jpg");
ImageIcon hang2 = new ImageIcon("hangman2.jpg");
ImageIcon hang3 = new ImageIcon("hangman3.jpg");
ImageIcon hang4 = new ImageIcon("hangman4.jpg");
ImageIcon hang5 = new ImageIcon("hangman5.jpg");
ImageIcon hang6 = new ImageIcon("hangman6.jpg");
//initializing array for index values
int wordcount = 10;
String[] words1 = new String[wordcount];
int[] wordssel = new int[10];
for (int j=0; j<10; j++){
wordssel[j] = -1;
}
//setting instructions
String Instructions = "To start the game, click on the new game button. You get 6 incorrect guesses for every word. Once you get 6 guesses, the game will end. Click the end game button to go back to the home page. If you want to play again, you can click New Game and you will be able to guess a different word. After every game, a message will appear to tell you how many words you have guesses correctly. When all the words are played, a dialog box will be shown that says Game Over. Exit this box to exit the game.";
//reading in the words
int number = 0;
try(BufferedReader br = new BufferedReader(new FileReader("words.txt")))
{
String line = br.readLine();
while(line != null){
words1[number] = line;
number++;
line = br.readLine();
}
}
//randomizes words
boolean flag = false;
int rand = 0;
int count = 0;
int wordcounter = 0;
while(!flag){
Random random = new Random();
rand = random.nextInt(wordcount);
count = 0;
for (int o=0; o<wordcount; o++){
if(wordssel[o] != rand){
count++;
}
}
if(count == wordcount){
wordssel[wordcounter] = rand;
wordcounter++;
}
if(wordcounter == wordcount){
flag = true;
}
}
String[] randwords = new String[10];
for(int o=0; o<10; o++){
randwords[wordssel[o]] = words1[o];
}
//initializing label
for(int i=0; i<20; i++){
labels[i] = new JLabel(" ");
labels[i].setFont(new Font("Serif", Font.BOLD, 30));
}
//initializing guessedchar array
for(int i=0; i<26; i++){
guesses[i] = ' ';
}
//value for window size
int xlim = 1200;
int ylim = 1200;
int xlim2 = 1600;
int ylim2 = 1600;
int xlim3 = 900;
int ylim3 = 600;
//value for x and y centers
int xcent = xlim/2 - 20;
int ycent = ylim/2;
int xcent2 = xlim2/2;
int ycent2 = ylim2/2 - 20;
int xcent3 = xlim3/2;
int ycent3 = ylim3/2 - 20;
//creating frames
JFrame frame1 = new JFrame("Hangman");//creates a new frame or window
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// I thiunk exits when clicks on red x
frame1.setSize(xlim, ylim); //size of window in pixels
JFrame frame2 = new JFrame("Hangman");//creates a new frame or window
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// I thiunk exits when clicks on red x
frame2.setSize(xlim2, ylim2); //size of window in pixels
JFrame frame3 = new JFrame();
frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame3.setSize(xlim3, ylim3);
//change font size for label, button, and textfield
UIManager.put("Button.font", new FontUIResource(new Font("Dialog", Font.BOLD, 24)));
UIManager.put("Label.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
UIManager.put("TextField.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
UIManager.put("TextArea.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
//creates buttons
JButton button1 = new JButton("New Game?");
button1.setBounds(xcent - 90, ycent - 165, 180, 130);//(xstart, ytop, width, height)
JButton button2 = new JButton("End Game?");
button2.setBounds(xcent - 90, ycent - 65, 180, 130);//(xstart, ytop, width, height)
JButton button3 = new JButton("Instructions");
button3.setBounds(xcent - 120, ycent, 240, 100);
JButton button4 = new JButton("Main Menu");
button4.setBounds(xcent - 100, ycent + 100, 200, 100);
//creating border
Border border = BorderFactory.createLineBorder(Color.BLACK, 4);
//creating labels
JLabel labelresult = new JLabel("");//label for win or losing game
labelresult.setBounds(400, 400, 400, 40);
JLabel labelhang = new JLabel();//label for hangman images
labelhang.setBounds(450, 375, 677, 620);
JLabel label3 = new JLabel("Hello");
label3.setBounds(200, 260, 500, 40);
JLabel label4 = new JLabel("Hello");
label4.setBounds(440, 1300, 800, 40);
JLabel label5 = new JLabel("Hello");
label5.setBounds(590, 1300, 800, 40);
JLabel label6 = new JLabel("Game Over");
label6.setBounds(380, 250, 200, 40);
JLabel lettersw = new JLabel();
JLabel label7 = new JLabel("How To Play");
label7.setBounds(500, 50, 200, 40);
JLabel label8 = new JLabel("Error");
label8.setBounds(590, 1300, 800, 40);
label8.setText("You can only enter one letter at a time.");
JLabel label9 = new JLabel("Error");
label9.setBounds(674, 1300, 800, 40);
label9.setText("You must enter a letter");
JLabel label10 = new JLabel(wordbank);
label10.setBounds(xcent2 - 200, 220, 400, 40);
JLabel label11 = new JLabel("You have already entered this letter.");
label11.setBounds(608, 1300, 800, 40);
JLabel label12 = new JLabel("You must exit game to guess.");
label12.setBounds(639, 1300, 800, 40);
//creating text area and setting properties
JTextArea texta1 = new JTextArea();
texta1.setOpaque(false);
texta1.setLineWrap(true);
texta1.setWrapStyleWord(true);
texta1.setBounds(100, 100, 1000, 600);
texta1.setText(Instructions);
//adding items to frames
frame1.add(button1);
frame1.add(button3);
frame2.add(button2);
frame2.add(labelhang);
frame3.add(label6);
frame2.add(label4);
frame2.add(label5);
frame3.add(label6);
frame1.add(label7);
frame1.add(texta1);
frame1.add(button4);
frame2.add(label8);
frame2.add(label9);
frame2.add(label10);
frame2.add(label11);
frame2.add(label12);
//set item properties
labelresult.setVisible(false);
button2.setVisible(false);
labelhang.setIcon(hanginit);
label4.setVisible(false);
label5.setVisible(false);
label7.setVisible(false);
texta1.setVisible(false);
button4.setVisible(false);
label8.setVisible(false);
label9.setVisible(false);
label10.setBorder(border);
label11.setVisible(false);
label12.setVisible(false);
//set frame properties
frame1.setLayout(null);
frame1.setVisible(true);//makes the frame visible to the user
frame3.setLayout(null);
//When End Game button is pressed
button2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//end of game conditions
label5.setVisible(false);
label4.setVisible(false);
label12.setVisible(false);
button2.setVisible(false);
frame2.setVisible(false);
wordbank = " Letter Bank:";
badguess = 0;
amountc = 0;
if(counter == wordcount){
frame3.setVisible(true);//frame after all words gone through
}
else{
labelhang.setIcon(hanginit);
frame1.setVisible(true);
}
}
});
//When Instructions button is pressed
button3.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
button1.setVisible(false);
button3.setVisible(false);
label7.setVisible(true);
texta1.setVisible(true);
button4.setVisible(true);
}
});
//When Main Menu is pressed
button4.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
button1.setVisible(true);
button4.setVisible(false);
button2.setVisible(true);
label7.setVisible(false);
texta1.setVisible(false);
button3.setVisible(true);
}
});
//When New Game is press
button1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//set item properties
frame2.setLayout(null);
frame2.setVisible(true);
frame1.setVisible(false);
button2.setVisible(false);
label8.setVisible(false);
label9.setVisible(false);
wordbank = " Letter Bank:";
label10.setText(wordbank);
//initializes labels and word
for(int i=0; i<20; i++){
labels[i].setText(" ");
}
String currentword = randwords[counter];
counter++;
//initializing previos guesses
for(int i=0; i<26; i++){
guesses[i] = ' ';
}
nguesses = 0;
//creating panel and panel components always create panels and all components in the same place that they are being added
JButton send = new JButton("Send");
JButton clear = new JButton("clear");
JTextField tf = new JTextField(1);
JLabel label = new JLabel("Enter Guess");
JPanel panel = new JPanel();
panel.add(label);
panel.add(tf);
panel.add(send);
panel.add(clear);
panel.setBounds(xcent2 - 250, ylim2 - 102, 500, 40);
frame2.add(panel);
//placing labels for letters
int letters = currentword.length();
int spacing2 = 800-(int)(letters*12.5);
for (int i=0; i<letters; i++){
labels[i].setText("_");
int spacing = 25 * i;
labels[i].setBounds(spacing2 + spacing, 1100, 25, 40);
frame2.add(labels[i]);
}
//when clear button is pressed
clear.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
tf.setText("");
}
});
//when send button is pressed
send.addActionListener(new ActionListener(){
int amountc1 = 0;//keeps track of correctly guessed amount of words
int counter2 = 0;//keeps track of amount of correct letter guesses for each word
int letters2 = 0;
#Override
public void actionPerformed(ActionEvent e){
//initialize word and user guess
String currentword = randwords[counter-1];
letters2 = currentword.length();
char[] wordcurrent = new char[20];
wordcurrent = currentword.toCharArray();
String userguess = tf.getText();
userguess = userguess.toLowerCase();
tf.setText("");
//set properties
label4.setVisible(false);
label5.setVisible(false);
label8.setVisible(false);
label9.setVisible(false);
label11.setVisible(false);
//checking guess with word
boolean flag2 = false;
boolean flag3 = false;
//checking if word is already solved and user is entering data
System.out.println(badguess);
System.out.println(amountc);
System.out.println(nguesses);
if(nguesses > badguess + amountc){
label4.setVisible(false);
label5.setVisible(false);
label12.setVisible(true);
nguesses++;
flag2 = true;
}
else if(userguess.length() > 1){
label8.setVisible(true);
flag2 = true;
nguesses++;
}
else if(userguess.length() < 1){
label9.setVisible(true);
flag2 = true;
nguesses++;
}
else{
char[] guessuser = userguess.toCharArray();
char guessedchar = guessuser[0];
int charval = (int)guessedchar;//97-122 lowercase, 65-90 for uppercase
//checks for previous guesses
for(int t=0; t<=nguesses; t++){
if(guessedchar == guesses[t]){
flag3 = true;
break;
}
}
nguesses++;
//checking word against guess
for(int i=0; i<letters2; i++){
if(!flag3){
if(((charval>96 & charval<123))){
guesses[nguesses] = guessedchar;
if(wordcurrent[i] == guessedchar){
labels[i].setText(userguess);
labels[i].setVisible(true);
flag2 = true;
counter2++;
nguesses++;
amountc++;
}
}
else{
label9.setVisible(true);
flag2 = true;
}
}
else{
label11.setVisible(true);
flag2 = true;
}
}
}
//checks if full word is guessed correctly
if(counter2 == letters2){
this.amountc1++;
nguesses++;
button2.setVisible(true);
String correctword = "Well done! You have solved " + amountc1 + " out of " + counter;
label5.setText(correctword);
label5.setVisible(true);
counter2 = 0;
if(counter == wordcount){
label3.setText(correctword);
}
}
//checks for wrong guess and changes hangman picture accordingly
if (flag2 == false){
badguess++;
switch(badguess){
case 1:
wordbank += " " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang1);
break;
case 2:
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang2);
break;
case 3:
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang3);
break;
case 4:
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang4);
break;
case 5:
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang5);
break;
case 6:
nguesses++;
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang6);
button2.setVisible(true);
String incorrectword = "Sorry, The correct word was " + currentword + " You have solved " + amountc1 + " out of " + counter;
label4.setText(incorrectword);
label4.setVisible(true);
this.counter2 = 0;
if(counter == wordcount){
label3.setText(incorrectword);
}
break;
default:
break;
}
}
else{
nguesses--;
}
}
});
}
});
}
}
To focus text field after setText(""); method you can use the following,
textFieldName.requestFocus();
To center the text field you can use this code,
textFieldName.setHorizontalAlignment(JTextField.CENTER);

JComboBox[] loop to show on JApplet not working

public class NewAccountApplet extends JApplet implements ActionListener{
JPanel jp1, jp2, jp3, jp4, jp5, jp6;
GridLayout productLO = new GridLayout(10,4,10,10);
int qty = 5;
JComboBox<Object>[] selectQty;
if (e.getActionCommand().equals("Login")) {
if (id.equals(checkID) && pw.equals(checkPW)) {
JOptionPane.showMessageDialog(null, "Authenticated");
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
selectQty = new JComboBox[qty];
jp1.setVisible(false);
jp2.setVisible(false);
jp3.setVisible(false);
jp4.setVisible(true);
jp5.setVisible(true);
jp6.setVisible(true);
String[] itemText = {"1", "2", "3", "4", "5"};
JLabel[] items = new JLabel[6];
JLabel purchasePage = new JLabel("Items for Purchase");
jp4.add(purchasePage);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp4);
jp4 = new JPanel();
jp5 = new JPanel(new GridBagLayout()); //set jp5 as a new jpanel with gridbaglayout
jp6 = new JPanel();
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel(); //adds items[i] as JLabel
items[i].setText(itemText[i]); //sets text of items as itemText[]
jp5.add(items[i], firstCol); //adds items to firstcol of jp5
selectQty[i] = new JComboBox<Object>(); //JComboBox selectqty[i]
selectQty[i].setPreferredSize(new Dimension(300, 20)); //sets the size
jp5.add(selectQty[i], lastCol); //sadsdasd
}
}
else JOptionPane.showMessageDialog(null, "Wrong account information");}
I have some questions regarding adding a JComboBox into a loop to display on my JApplet.
the for loop on the bottom adds my JComboBox (selectQty) to the screen. But I get an error message on eclipse where i coded as: items[i].setText(itemText[i]);.
It shows up my JPanel jp4 correctly. but the JPanel jp5 is not showing up.. I wonder what is wrong...
So to summarize, the code compiles (with other codes that are not on here), but japplet only shows jp4 jpanel, and error occrs on line: items[i].setText(itemText[i]);.
itemText has 5 elements {"1", "2", "3", "4", "5"} but JLabel[] items = new JLabel[6] items has 6.
You appear to be re-creating jp5 but neither removing the old instance or adding the new instance...
// This suggests that jp5 has already been created
jp5.setVisible(true);
//...
// But you create a new instance here
jp5 = new JPanel(new GridBagLayout());
// Then add stuff to it...
Try using jp5.removeAll() instead of jp5 = new JPanel(new GridBagLayout());
The likely cause of your error is probably IndexOutOfBoundsException caused by the fact the itemText and items have different numbers of elements
String[] itemText = {"1", "2", "3", "4", "5"};
JLabel[] items = new JLabel[6];
//...
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel(); //adds items[i] as JLabel
// Error here on the last element...
items[i].setText(itemText[i]); //sets text of items as itemText[]
Instead, consider using something like...
String[] itemText = {"1", "2", "3", "4", "5"};
JLabel[] items = new JLabel[itemText.length];
And remember, magic numbers are a bad idea
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.*;
public class NewAccountApplet extends JApplet implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel titlePage;
JLabel[] txt;
JTextField[] jtf;
JButton accept, decline;
JPanel jp1, jp2, jp3, jp4, jp5, jp6;
String[] accountlist = {"Select Account Type.", "Customer", "Admin"};
JComboBox<Object> textAlignment = new JComboBox<Object>(accountlist);
GridLayout productLO = new GridLayout(10,4,10,10);
int qty = 5;
JComboBox<Object>[] selectQty;
public void init(){
setSize(400,400);
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
String[] labeltxt = {"Name","Account ID","Password","E-Mail","Phone","Address","","","Account Type"};
titlePage = new JLabel("Create New Account");
txt = new JLabel[9];
jtf = new JTextField[9];
accept = new JButton("Create");
decline = new JButton("Decline");
jp1 = new JPanel();
jp2 = new JPanel(new GridBagLayout());
jp3 = new JPanel();
jp4 = new JPanel();
jp5 = new JPanel();
jp6 = new JPanel();
for(int i=0; (i<9); i++) {
txt[i] = new JLabel();
txt[i].setText(labeltxt[i]);
jp2.add(txt[i], firstCol);
jtf[i] = new JTextField();
jtf[i].setPreferredSize(new Dimension(300, 20));
jp2.add(jtf[i], lastCol);
}
jp1.add(titlePage);
jp3.add(accept);
jp3.add(decline);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp1);
content.add(jp2);
content.add(jp3);
String id = this.jtf[1].getText();
String pw = this.jtf[2].getText();
jtf[6].setText(id);
jtf[7].setText(pw);
jtf[6].setVisible(false);
jtf[7].setVisible(false);
jtf[8].setVisible(false);
jp2.add(textAlignment, lastCol);
decline.addActionListener(this);
accept.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String id = jtf[1].getText();
String pw = jtf[2].getText();
String checkID = jtf[6].getText();
String checkPW = jtf[7].getText();
String accountType = "";
String correctType = "Customer";
String chosenType = (String) textAlignment.getSelectedItem();
JPasswordField pField = new JPasswordField(10);
JPanel pPanel = new JPanel();
pPanel.add(new JLabel("Please Enter Password: "));
pPanel.add(pField);
if (e.getActionCommand().equals("Create") && (chosenType.equals("Customer"))){
JOptionPane.showMessageDialog(null, "Thank you for Joining!");
id = jtf[1].getText();
pw = jtf[2].getText();
titlePage.setText("Welcome to Final Sales!");
accept.setText("Login");
decline.setText("Cancel");
txt[6].setText("UserName");
txt[7].setText("Password");
jtf[0].setText("");
jtf[3].setText("");
jtf[4].setText("");
jtf[5].setText("");
txt[0].setVisible(false);
txt[1].setVisible(false);
txt[2].setVisible(false);
txt[3].setVisible(false);
txt[4].setVisible(false);
txt[5].setVisible(false);
textAlignment.setVisible(false);
txt[8].setVisible(false);
jtf[0].setVisible(false);
jtf[1].setVisible(false);
jtf[2].setVisible(false);
jtf[3].setVisible(false);
jtf[4].setVisible(false);
jtf[5].setVisible(false);
jtf[6].setVisible(true);
jtf[7].setVisible(true);
}
if (e.getActionCommand().equals("Create") && (chosenType.equals("Admin"))) {
JOptionPane.showMessageDialog(null, pPanel);
JOptionPane.showMessageDialog(null, "Wrong Admin Password");
}
if (e.getActionCommand().equals("Create") && (chosenType.equals("Select Account Type."))) {
JOptionPane.showMessageDialog(null, "You have selected wrong account type.");
}
if (e.getActionCommand().equals("Decline"))
System.exit(0);
if (e.getActionCommand().equals("Login")) {
if (id.equals(checkID) && pw.equals(checkPW)) {
JOptionPane.showMessageDialog(null, "Authenticated");
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
selectQty = new JComboBox[qty];
jp1.setVisible(false);
jp2.setVisible(false);
jp3.setVisible(false);
jp4.setVisible(true);
jp5.setVisible(true);
jp6.setVisible(true);
String[] itemText = {"White Snapback", "Silver Necklace", "Black T Shirt", "", "5"};
JLabel[] items = new JLabel[5];
JLabel purchasePage = new JLabel("Items for Purchase");
jp4.add(purchasePage);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp4);
jp4 = new JPanel();
jp5.setLayout(new GridBagLayout());
jp6 = new JPanel();
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel();
items[i].setText(itemText[i]);
jp5.add(items[i], firstCol);
selectQty[i] = new JComboBox<Object>();
selectQty[i].setPreferredSize(new Dimension(300, 20));
jp5.add(selectQty[i], lastCol);
}
}
else JOptionPane.showMessageDialog(null, "Wrong account information");}
if (e.getActionCommand().equals("Cancel")) {
System.exit(0);}
}
}

Unable to getText the value of string

I'm preparing a simple system as my assignment, And I'm facing a problem where I dont know how to getText the value of String. I know how to do it with integer, but not with string.
I use Integer.parseInt(t2.getText()); in my code if i want to get an integer value
I have added my code into this.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tollRate extends JFrame implements ActionListener {
JLabel L1 = new JLabel("Please insert your origin (in capital letter)");
JTextField t1 = new JTextField(20);
JLabel L2 = new JLabel("Please insert your destination (in capital letter)");
JTextField t2 = new JTextField(20);
JLabel L3 = new JLabel("Your vehicle class");
JTextField t3 = new JTextField(1);
JButton b1 = new JButton("Calculate");
JButton b2 = new JButton("Exit");
JLabel L4 = new JLabel("Class 0 : Motorcycles, bicycles, or vehicles with "
+ "2 or less wheels" + "\nClass 1 : Vehicles wit 2 axles and 3 "
+ "or 4 wheels excluding taxis" + "\nClass 2 : Vehicles with 2 "
+ "axles and 5 or 6 wheels excluding busses" + "\n Class 3 : "
+ "Vehicles with 3 or more axles" + "\nClass 4 : Taxis"
+ "\nClass 5 : Buses");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
String i, j, k;
tollRate() {
JFrame a = new JFrame();
setTitle("Highway Toll Rates System");
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
p1.setLayout(new GridLayout(1, 2));
p1.add(L1);
p1.add(t1);
p2.setLayout(new GridLayout(1, 2));
p2.add(L2);
p2.add(t2);
p3.setLayout(new GridLayout(1, 2));
p3.add(L3);
p3.add(t3);
p4.setLayout(new FlowLayout());
p4.add(b1);
p4.add(b2);
p5.setLayout(new FlowLayout());
p5.add(L4);
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a) {
Object source = a.getSource();
if (source == b2) {
this.dispose();
} else if (source == b1) {
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
}
}
public static void main(String[] args) {
tollRate a = new tollRate();
}
}
First of all String i, j, k;
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
This is wrong. You are assigning String for int. Correct them first. and if you want int values it is better to use
int i, j, k; and use trim() to avoid additional spaces.
i = Integer.parseInt(t1.getText().trim());
j = Integer.parseInt(t2.getText().trim());
k = Integer.parseInt(t3.getText().trim());
In your case use as follows
i = t1.getText();
j = t2.getText();
k = t3.getText();
to assign a string to a string all you need to do is
i = t1.getText();
j = t2.getText();
k = t3.getText();
as you have created them as strings already

Java Program error (TextField)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class NICCode extends JFrame {
NICCode() {
setSize(600, 250);
setResizable(false);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
// JPanel
JPanel labelPanel = new JPanel(new FlowLayout(1));
JPanel leftBodyPanel = new JPanel(new GridLayout(3, 1));
JPanel bodyPanel = new JPanel(new GridLayout(3, 1));
JPanel buttonPanel = new JPanel(new FlowLayout(2));
JPanel textFieldPanel = new JPanel(new FlowLayout(0));
// JLabel
JLabel titleLabel = new JLabel("Find Your Birthday By NIC");
titleLabel.setFont(new Font("", 1, 25));
JLabel myLabel = new JLabel("CSG");
myLabel.setFont(new Font("", 1, 10));
JLabel enterNicLabel = new JLabel("Enter Your NIC :");
JLabel yourBirthDayLabel = new JLabel("Your Birth Day :");
JLabel yourGenderLabel = new JLabel("Gender :");
JLabel printBirthDayLabel = new JLabel("Your Birth Day");
JLabel printGenderLabel = new JLabel("Your Gender");
// JTextField
JTextField nicText = new JTextField(25);
nicText.setText("920000000V");
// JButton
JButton searchAgainButton = new JButton("Search Again");
JButton exitButton = new JButton("Exit");
// adds
add("North", labelPanel);
add("West", leftBodyPanel);
add("South", buttonPanel);
add(bodyPanel);
labelPanel.add(titleLabel);
leftBodyPanel.add(enterNicLabel);
leftBodyPanel.add(yourBirthDayLabel);
leftBodyPanel.add(yourGenderLabel);
textFieldPanel.add(nicText);
bodyPanel.add(textFieldPanel);
bodyPanel.add(printBirthDayLabel);
bodyPanel.add(printGenderLabel);
buttonPanel.add(myLabel);
buttonPanel.add(searchAgainButton);
buttonPanel.add(exitButton);
setVisible(true);
// pack();
String yearText = nicText.substring(0, 2);
String dateText = nicText.substring(2, 5);
String sex = "";
int year = Integer.parseInt(yearText);
int date = Integer.parseInt(dateText);
int month = 0;
if (date > 500) {
sex = "Feamale";
date -= 500;
} else {
sex = "Male";
}
int datesOfMonths[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for (int i = 0; i < 12; i++) {
date = date - datesOfMonths[i];
month = i;
if (date < datesOfMonths[i + 1]) {
break;
}
}
if (month > 0) {
month += 1;
}
}
}
I just created a program for find birthday from nic. I couldn't fix this compile error.
I created a JTextField to get Nic, then I added substring methods to get the needed numbers to find nic. Unfortunately the substring methods can't find textField. It shows error as 'cannot find symbol'. It's a TextField. Why can't the method find that TextField.?
The message:
cannot find symbol
Is not referring to the text field, but the method substring(..) which does not exist for JTextField. But something like..
textField.getText().substring(...);
..probably will work, since getText() returns a String and String has that method.
Change
String yearText = nicText.substring(0, 2);
String dateText = nicText.substring(2, 5);
to
String yearText = nicText.getText().substring(0, 2);
String dateText = nicText.getText().substring(2, 5);

Categories