How Do I get the buttons to work? Java Programming - java

I created an Address Book GUI, I just don't understand How to make the save and delete buttons to work, so when the user fills the text fields they can click save and it saves to the JList I have created and then they can also delete from it. How Do I Do this?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddressBook {
private JLabel lblFirstname,lblSurname, lblMiddlename, lblPhone,
lblEmail,lblAddressOne, lblAddressTwo, lblCity, lblPostCode, picture;
private JTextField txtFirstName, txtSurname, txtAddressOne, txtPhone,
txtMiddlename, txtAddressTwo, txtEmail, txtCity, txtPostCode;
private JButton btSave, btExit, btDelete;
private JList contacts;
private JPanel panel;
public static void main(String[] args) {
new AddressBook();
}
public AddressBook(){
JFrame frame = new JFrame("My Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.cyan);
lblFirstname = new JLabel("First name");
lblFirstname.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblFirstname.setFont(styleOne);
panel.add(lblFirstname);
txtFirstName = new JTextField();
txtFirstName.setBounds(210, 50, 150, 20);
panel.add(txtFirstName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(385,50,150,20);
Font styleTwo = new Font ("Arial",Font.BOLD,13);
lblSurname.setFont(styleTwo);
panel.add(lblSurname);
txtSurname = new JTextField();
txtSurname.setBounds(450,50,150,20);
panel.add(txtSurname);
lblMiddlename = new JLabel ("Middle Name");
lblMiddlename.setBounds(620,50,150,20);
Font styleThree = new Font ("Arial", Font.BOLD,13);
lblMiddlename.setFont(styleThree);
panel.add(lblMiddlename);
txtMiddlename = new JTextField();
txtMiddlename.setBounds(710,50,150,20);
panel.add(txtMiddlename);
lblPhone = new JLabel("Phone");
lblPhone.setBounds(160,100,100,20);
Font styleFour = new Font ("Arial", Font.BOLD,13);
lblPhone.setFont(styleFour);
panel.add(lblPhone);
txtPhone = new JTextField();
txtPhone.setBounds(210,100,150,20);
panel.add(txtPhone);
lblEmail = new JLabel("Email");
lblEmail.setBounds(410,100,100,20);
Font styleFive = new Font ("Arial", Font.BOLD,13);
lblEmail.setFont(styleFive);
panel.add(lblEmail);
txtEmail = new JTextField();
txtEmail.setBounds(450,100,150,20);
panel.add(txtEmail);
lblAddressOne = new JLabel("Address 1");
lblAddressOne.setBounds(145,150,100,20);
Font styleSix = new Font ("Arial", Font.BOLD,13);
lblAddressOne.setFont(styleSix);
panel.add(lblAddressOne);
txtAddressOne = new JTextField();
txtAddressOne.setBounds(210,150,150,20);
panel.add(txtAddressOne);
lblAddressTwo = new JLabel("Address 2");
lblAddressTwo.setBounds(145,200,100,20);
Font styleSeven = new Font ("Arial", Font.BOLD,13);
lblAddressTwo.setFont(styleSeven);
panel.add(lblAddressTwo);
txtAddressTwo = new JTextField();
txtAddressTwo.setBounds(210,200,150,20);
panel.add(txtAddressTwo);
lblCity = new JLabel("City");
lblCity.setBounds(180,250,100,20);
Font styleEight = new Font ("Arial", Font.BOLD,13);
lblCity.setFont(styleEight);
panel.add(lblCity);
txtCity = new JTextField();
txtCity.setBounds(210,250,150,20);
panel.add(txtCity);
lblPostCode = new JLabel("Post Code");
lblPostCode.setBounds(380,250,100,20);
Font styleNine = new Font ("Arial", Font.BOLD,13);
lblPostCode.setFont(styleNine);
panel.add(lblPostCode);
txtPostCode = new JTextField();
txtPostCode.setBounds(450,250,150,20);
panel.add(txtPostCode);
//image
ImageIcon image = new ImageIcon("C:\\Users\\Hassan\\Desktop\\icon.png");
picture = new JLabel(image);
picture.setBounds(600,90, 330, 270);
panel.add(picture);
//buttons
btSave = new JButton ("Save");
btSave.setBounds(380,325,100,20);
panel.add(btSave);
btDelete = new JButton ("Delete");
btDelete.setBounds(260,325,100,20);
panel.add(btDelete);
btExit = new JButton ("Exit");
btExit.setBounds(500,325,100,20);
panel.add(btExit);
btExit.addActionListener(new Action());
//list
contacts=new JList();
contacts.setBounds(0,10,125,350);
panel.add(contacts);
frame.add(panel);
frame.setVisible(true);
}
//button actions
static class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame option = new JFrame();
int n = JOptionPane.showConfirmDialog(option,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}

Buttons need Event Handlers to work. You have not added any Event Handlers to the Save and Delete buttons. You need to call the addActionListener on those buttons too.
I recommend anonymous inner classes:
mybutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});

You need to addActionListener to the buttons btSave and btDelete.
You could create a anonymous class like this and perform your work there.
btSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
btDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
Edit:
I have an example to which you can refer to and accordingly make changes by understanding it. I got it from a professor at our institute.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}
}
}
}

Related

Use of JButton array Java

I am not sure what I am doing wrong. I am trying to create 4 buttons using the arrays and passing the method to the Set Panel class. When I run it I only get one button. Any help would be great. Essentially what I want is a Panel with four buttons, through the use of Methods.
public class SetButtons extends JButton implements ActionListener {
JButton [] buttonArray = new JButton[4];
JButton exitBtn, newGameBtn, checkBtn, clearBtn;
Font myFont = new Font("ink free", Font.BOLD,22);
public SetButtons(){
this.exitBtn = new JButton("Exit");
this.newGameBtn = new JButton("New Game");
this.checkBtn = new JButton("Check Answer");
this.clearBtn = new JButton("Clear");
this.buttonArray[0] = exitBtn;
this.buttonArray[1] = newGameBtn;
this.buttonArray[2] = checkBtn;
this.buttonArray[3] = clearBtn;
for (int i = 0; i < 4; i++){
this.buttonArray[i].addActionListener(this);
this.buttonArray[i].setFont(myFont);
this.buttonArray[i].setFocusable(false);
this.buttonArray[i].setLayout(new FlowLayout());
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this){
System.exit(0);
}
}
}
import javax.swing.*;
import java.awt.*;
public class SetPanel extends JPanel {
Font myFont = new Font("ink free", Font.BOLD,22);
SetLabels labels;
SetButtons exitButton;
SetPanel(){
SetButtons btn = new SetButtons();
this.add(btn);
this.setBackground(Color.darkGray);
this.setLayout(new FlowLayout());
}
}

JLable not change after change the TextFiled and also the combox

Hi I'm doing a program that firstly opens setting menu like in the picture
enter image description here
first I select the choices of the game I want from the jcombox and jdialog that open window to set the names .
this is the code of it :
public class SettingMenu extends JFrame {
boolean is3players = false, is4players = false;
BufferedImage settingImage;
String[] playersChoises = { "2", "3", "4" };
String[] sizeChoises = { "30", "50", "100" };
JComboBox comboBoxPlayers;
JComboBox comboBoxSizes;
static JButton startGame, writeNames;
public SettingMenu() {
JLabel howManyPlayersText = new JLabel("How many players ?");
comboBoxPlayers = new JComboBox(playersChoises);
if (comboBoxPlayers.getSelectedItem().equals("3")) {
is3players = true;
}
if (comboBoxPlayers.getSelectedItem().equals("4")) {
is3players = true;
is4players = true;
}
JLabel writeNamesText = new JLabel("Set names of playes");
writeNames = new JButton("set names");
JLabel sizeOfBoredText = new JLabel("What the size of the bored ?");
comboBoxSizes = new JComboBox(sizeChoises);
startGame = new JButton("Click to start the game!");
howManyPlayersText.setBounds(177, 200, 270, 100);
comboBoxPlayers.setBounds(230, 270, 100, 30);
writeNamesText.setBounds(230, 210, 380, 250);
writeNames.setBounds(240, 350, 100, 36);
sizeOfBoredText.setBounds(177, 376, 300, 100);
comboBoxSizes.setBounds(230, 450, 100, 30);
startGame.setBounds(200, 500, 200, 44);
add(howManyPlayersText);
add(comboBoxPlayers);
add(writeNamesText);
add(writeNames);
add(sizeOfBoredText);
add(comboBoxSizes);
add(startGame);
setVisible(true);
}
public static void main(String[] args) {
// open this class
new SettingMenu();
// when i click on startgame bottun open the class of the game
startGame.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new LeadersAndSnake_Project201();
}
});
// when i click on writeNames bottun open the class of dialog
writeNames.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new SetNames();
}
});
}
}
and this is Set Names class which open the set names window
enter image description here
class SetNames extends JDialog {
public JTextField setNamePlayer1, setNamePlayer2, setNamePlayer3, setNamePlayer4;
public SetNames() {
this.setSize(280, 151);
this.setLocationRelativeTo(null);
JLabel name1 = new JLabel("Set Player's 1 name : ");
setNamePlayer1 = new JTextField(7);
setNamePlayer1.setText("Player 1");
JLabel name2 = new JLabel("Set Player's 2 name : ");
setNamePlayer2 = new JTextField(7);
setNamePlayer2.setText("Player 2");
JPanel panelOfDialog_1 = new JPanel();
panelOfDialog_1.add(name1);
panelOfDialog_1.add(setNamePlayer1);
JPanel panelOfDialog_2 = new JPanel();
panelOfDialog_2.add(name2);
panelOfDialog_2.add(setNamePlayer2);
JPanel panelOfDialog_3 = new JPanel();
JButton okBotton = new JButton("OK");
add(okBotton);
okBotton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setNamePlayer1 = new JTextField(setNamePlayer1.getText());
setNamePlayer2 = new JTextField(setNamePlayer2.getText());
setVisible(false);
}
});
panelOfDialog_3.add(okBotton);
add(panelOfDialog_1, BorderLayout.NORTH);
add(panelOfDialog_2, BorderLayout.CENTER);
add(panelOfDialog_3, BorderLayout.AFTER_LAST_LINE);
this.setVisible(true);
}
}
and this is the large class for the game but I just put the imprtant thinga here :
class LeadersAndSnake_Project201 extends JFrame implements ActionListener{
// Here I made an object of Setting Menu class for use the varible that it has
SettingMenu obj1 = new SettingMenu();
// Here I made an object of Set Names class to take the name inside the textfiled
SetNames obj2 = new SetNames();
public LeadersAndSnake_Project201() {
// -----------------left panel------------------------------
JPanel leftPanel = new JPanel();
GroupLayout groupLayout = new GroupLayout(leftPanel);
leftPanel.setLayout(groupLayout);
//---------------------------panel 1 for information player 1 -------------------------------------
JPanel panel1 = new JPanel();
ImageIcon imageMan1 = new ImageIcon("man1.png");
JLabel imageMan11 = new JLabel("", imageMan1, JLabel.CENTER);
JLabel player1text = new JLabel(obj2.setNamePlayer1.getText());
panel1.add(imageMan11);
panel1.add(player1text);
//---------------------------panel 2 for information player 2------------------------------------
JPanel panel2 = new JPanel();
ImageIcon imageMan2 = new ImageIcon("man2.png");
JLabel imageMan22 = new JLabel("", imageMan2, JLabel.CENTER);
JLabel player2text = new JLabel(obj2.setNamePlayer2.getText());
panel2.add(imageMan22);
panel2.add(player2text);
//---------------------------panel 3 for information player 3-------------------------------------
JPanel panel3 = new JPanel();
if(obj.is3 == true){
ImageIcon imageMan3 = new ImageIcon("man3.png");
JLabel imageMan33 = new JLabel("", imageMan3, JLabel.CENTER);
JLabel player3text = new JLabel("Player 3");
player2text.setFont(fontText);
panel3.add(imageMan33);
panel3.add(player3text);
}
}
}
Here on left panel are my problems
the jlable of player 1 and player 2 didn't chang even if I try to change them in the textfiled and the second problem is that the panel of player 3 didn't apper even if I select the chois "3" from the combox .
enter image description here
Try to call .pack() on the Frame after altering the elements.
EDIT
You have no code changing the labels. What you need is store the labels in a variable, like you did with other components, and in the ActionListener on on the okButton in SetNames(), instead of doing whatever you do to the TextFields there (which looks wrong), update the Label text.
So, for example
class SetNames extends JDialog {
[...]
public JButton okButton; // save okButton so others can add listeners
}
class LeadersAndSnake_Project201 extends JFrame implements ActionListener{
// Here I made an object of Set Names class to take the name inside the textfiled
SetNames obj2 = new SetNames();
public LeadersAndSnake_Project201() {
[...]
obj2.okButton.addActionListener(new ActionListener(){/*update labels*/});
}}

java application freezes when writes to a file with fileWriter

I have a register button where when i press register it should write the values to details.txt that was typed in the textfield. When i register for the first time it works but if the file contains some values it will freeze if i try to register the second time. Anyone can help to debug this pls?
Main Class
package assignment;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assignment
{
JFrame mainFrame;
JPanel framePanel,leftPnl,topPnl,btmPnl;
JLabel welcomeLabel,studId,passwd;
JTextField studField,passField;
JButton logBtn,signBtn;
Color btnClr,btnTxtClr,backgroundClr,lblClr;
Font mainFont,labelFont;
public void mainPage()
{
mainFrame = new JFrame("CGPA Calculator");
framePanel = new JPanel();
//-------------------Creating Components/Setting Fonts/Color----------------
-------------------------------------------
//Color
btnClr = new Color(0, 179, 60);
btnTxtClr = new Color(255,255,255);
backgroundClr = new Color(26, 26, 26);
lblClr = new Color(255,255,255);
//Fonts
mainFont = new Font("Verdana",Font.PLAIN,40);
labelFont = new Font("Verdana",Font.PLAIN,20);
//Button
logBtn = new JButton("<html><font face=\"Verdana\">Login</font></html>");//Source from:https://stackoverflow.com/questions/21046164/jbutton-text-with-different-font-family-in-different-words
logBtn.setFocusPainted(false);
logBtn.setBackground(btnClr);
logBtn.setForeground(btnTxtClr);
signBtn = new JButton("<html><font face=\"Verdana\">Register</font></html>");
signBtn.setFocusPainted(false);
signBtn.setBackground(btnClr);
signBtn.setForeground(btnTxtClr);
//Label
welcomeLabel = new JLabel("CGPA Calculator");
welcomeLabel.setForeground(lblClr);
studId = new JLabel("Student ID :");
studId.setForeground(lblClr);
passwd = new JLabel("Password :");
passwd.setForeground(lblClr);
//TextField
studField = new JTextField(8);
studField.setBorder(javax.swing.BorderFactory.createEmptyBorder());//Sourced From:https://stackoverflow.com/questions/2281937/swing-jtextfield-how-to-remove-the-border
passField = new JTextField(8);
passField.setBorder(BorderFactory.createEmptyBorder());
//Adding Fonts to Components
welcomeLabel.setFont(mainFont);
studId.setFont(labelFont);
passwd.setFont(labelFont);
//Panel
leftPnl = new JPanel();
topPnl = new JPanel();
btmPnl = new JPanel();
//----------------------Adding of panels/layout/components--------------------------------------------------------
//Seting up layouts to panel
leftPnl.setLayout(new FlowLayout());
btmPnl.setLayout(new BoxLayout(btmPnl,BoxLayout.X_AXIS));
//TOPPANEL(Adjustments)
topPnl.setBackground(backgroundClr);
topPnl.add(welcomeLabel);
topPnl.add(Box.createRigidArea(new Dimension(0,150)));
//LEFTPANEL(Adjustements)
leftPnl.setBackground(backgroundClr);
leftPnl.add(Box.createRigidArea(new Dimension(0,70)));
leftPnl.add(studId);
leftPnl.add(studField);
leftPnl.add(passwd);
leftPnl.add(passField);
//BOTTOMPANEL
btmPnl.setBackground(backgroundClr);
btmPnl.add(Box.createRigidArea(new Dimension(130,0)));
btmPnl.add(logBtn);
btmPnl.add(Box.createRigidArea(new Dimension(40,0)));
btmPnl.add(signBtn);
btmPnl.add(Box.createRigidArea(new Dimension(200,200)));
//Action Listeners(lambda expression)
signBtn.addActionListener((ActionEvent e) -> {
SignUpPage sign = new SignUpPage();
sign.SecondPage();
sign.getFrame().setVisible(true);
//mainFrame.setVisible(false);
});
mainFrame.getContentPane().setBackground(backgroundClr);
mainFrame.add(topPnl,BorderLayout.NORTH);
mainFrame.add(leftPnl,BorderLayout.WEST);
mainFrame.add(btmPnl,BorderLayout.SOUTH);
mainFrame.setVisible(true);
mainFrame.setSize(450,450);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
Assignment display = new Assignment();
display.mainPage();
new SignUpPage();
}
}
register class
package assignment;
import javax.swing.*;
import java.awt.*;
import java.lang.*;
import java.awt.event.*;
import java.io.*;
public class SignUpPage
{
private JFrame signFrame;
JTextField idField,passwdField;
JButton registerBtn,cancelBtn,resetBtn;
JLabel studIdLbl,passwdLbl,schoolLbl,label;
JComboBox schoolBox;
String [] school = {"School Of Computing & Creative Media","School Of
Communication & Creative Arts","School Of Engineering","School Of Business"
,"School of Hospiality Tourism & Culinary Arts"};
Font labelFont;
Color btnClr,btnTxtClr,lblClr,backgroundClr;
String selectSchool;
BufferedReader validateFile;
String details;
String detailsArray[];
int detailsExists = 0;
public void SecondPage()
{
//ComboBox(Class)
label = new JLabel("");
//Color
btnClr = new Color(0, 179, 60);
btnTxtClr = new Color(255,255,255);
backgroundClr = new Color(26, 26, 26);
lblClr = new Color(255,255,255);
//Font
labelFont = new Font("Verdana",Font.PLAIN,13);
//JTextField
idField = new JTextField("Student ID",4);
idField.setMinimumSize(new Dimension(300,30));
idField.setMaximumSize(new Dimension(300,30));
idField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
passwdField = new JTextField("Password",4);
passwdField.setMinimumSize(new Dimension(300,30));
passwdField.setMaximumSize(new Dimension(300,30));
passwdField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
//JComboBox
schoolBox = new JComboBox(school);
schoolBox.setFont(labelFont);
schoolBox.setMinimumSize(new Dimension(300,30));
schoolBox.setMaximumSize(new Dimension(300,30));
schoolBox.addActionListener((ActionEvent e)->{
JComboBox <String> schoolCombo = (JComboBox<String>) e.getSource();
selectSchool = (String) schoolCombo.getSelectedItem();
});
//Panel
JPanel fieldPnl = new JPanel();
JPanel btnPnl = new JPanel();
//Button
registerBtn = new JButton("<html><font face=\"Verdana\">Register</font></html>");
registerBtn.setBackground(btnClr);
registerBtn.setForeground(lblClr);
cancelBtn = new JButton("<html><font face=\"Verdana\">Cancel</font></html>");
cancelBtn.setBackground(btnClr);
cancelBtn.setForeground(lblClr);
resetBtn = new JButton("<html><font face=\"Verdana\">Reset</font></html>");
resetBtn.setBackground(btnClr);
resetBtn.setForeground(lblClr);
//Label
studIdLbl = new JLabel("Student ID:");
passwdLbl = new JLabel("Password");
schoolLbl = new JLabel("School:");
//Adding Components to Panel
fieldPnl.add(Box.createRigidArea(new Dimension(0,100)));
fieldPnl.setBackground(backgroundClr);
fieldPnl.add(idField);
fieldPnl.add(Box.createRigidArea(new Dimension(0,10)));
fieldPnl.add(passwdField);
fieldPnl.add(Box.createRigidArea(new Dimension(0,10)));
fieldPnl.add(schoolBox);
fieldPnl.add(Box.createRigidArea(new Dimension(0,50)));
btnPnl.setBackground(backgroundClr);
btnPnl.add(registerBtn);
btnPnl.add(cancelBtn);
btnPnl.add(resetBtn);
btnPnl.add(label);
btnPnl.add(Box.createRigidArea(new Dimension(0,190)));
//Layout
fieldPnl.setLayout(new BoxLayout(fieldPnl,BoxLayout.Y_AXIS));
//Action Listener
registerBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BufferedWriter toFile;
try {
signUpValidation();
if(detailsExists==0)
{
toFile = new BufferedWriter(new FileWriter("details.txt",true));
toFile.write(idField.getText() + "," + passwdField.getText() + ","+selectSchool);
toFile.newLine();
toFile.flush();
}
else if(detailsExists==1)
{
//same values exists in file
}
} catch(FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
signFrame = new JFrame("Sign Up");
signFrame.add(btnPnl,BorderLayout.SOUTH);
signFrame.add(fieldPnl,BorderLayout.CENTER);
signFrame.setVisible(true);
signFrame.setSize(450,450);
signFrame.setResizable(false);
signFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
public Frame getFrame()
{
return signFrame;
}
public int signUpValidation() throws IOException
{
validateFile = new BufferedReader(new FileReader("details.txt"));
details = validateFile.readLine();
while(details!=null)
{
detailsArray=details.split(",");
if(idField.equals(detailsArray[0]) || passwdField.equals(detailsArray[1]))
{
detailsExists = 1;
}
else
detailsExists = 0;
}
return detailsExists;
}
}
while(details!=null) prevents the loop from ever exiting, because details is not updated with in the loop's context - it never becomes null
Something like...
String details = null;
while((details = validateFile.readLine()) !=null) {...
might be safer. But based on your code, you're only expecting a single line, so getting rid of the loop altogether might be a better solution

I need help figuring out why my clear button code does not work

I am working on a project for my Java class and cannot get my clear button to work. More specifically, I am having an issue implementing Action and ItemListeners. My understanding is that I need to use ActionListener for my clear button, but I need to use ItemListener for my ComboBoxes. I am very new to Java and this is an intro class. I haven't even begun to code the submit button and ComboBoxes and am a little overwhelmed. For now, I could use help figuring out why my clear function will not work. Any help is greatly appreciated. Thanks in advance.
Here is my updated code after suggestions:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class cousinsTree extends JApplet
{
Container Panel;
JButton submitButton;
JButton clearButton;
JTextField firstName;
JTextField lastName;
JTextField Address;
JTextField City;
JMenuBar menuBar;
JTextField Total;
JComboBox Service;
JComboBox howOften;
JComboBox numTrees;
LayoutManager setLayout;
String[] TreeList;
String[] numList;
String[] oftenList;
#Override
public void init()
{
Panel = getContentPane();
this.setLayout(new FlowLayout());
TreeList= new String[3];
TreeList [0] = "Trim";
TreeList [1] = "Chemical Spray";
TreeList [2] = "Injection";
numList = new String[3];
numList [0] = "0-5";
numList [1] = "6-10";
numList [2] = "11 >";
oftenList = new String[3];
oftenList [0] = "Monthly";
oftenList [1] = "Quarterly";
oftenList [2] = "Annually";
Panel.setBackground (Color.green);
submitButton = new JButton("Submit");
submitButton.setPreferredSize(new Dimension(100,30));
clearButton.addActionListener(new clrButton());
clearButton = new JButton("Clear");
clearButton.setPreferredSize(new Dimension(100,30));
firstName = new JTextField("", 10);
JLabel lblFirstName = new JLabel("First Name");
lastName = new JTextField("", 10);
JLabel lblLastName = new JLabel("Last Name");
Address = new JTextField("", 15);
JLabel lblAddress = new JLabel("Address");
City = new JTextField("Columbus", 10);
JLabel lblCity = new JLabel("City");
Total = new JTextField("", 10);
JLabel lblTotal = new JLabel("Total");
//Service = new TextField("Service (Trim, Chemical Spray, or Injection).", 20);
JLabel lblService = new JLabel("Service");
Service=new JComboBox(TreeList);
JLabel lblhowOften = new JLabel("How often?");
howOften = new JComboBox(oftenList);
JLabel lblnumTrees = new JLabel("Number of Trees");
numTrees = new JComboBox(numList);
/* Configuration */
//add items to panel
Panel.add(lblFirstName);
Panel.add(firstName);
Panel.add(lblLastName);
Panel.add(lastName);
Panel.add(lblAddress);
Panel.add(Address);
Panel.add(lblCity);
Panel.add(City);
Panel.add(lblnumTrees);
Panel.add(numTrees);
Panel.add(lblService);
Panel.add(Service);
Panel.add(lblhowOften);
Panel.add(howOften);
Panel.add(submitButton);
Panel.add(clearButton);
Panel.add(lblTotal);
Panel.add(Total);
this.setSize(new Dimension(375, 275));
this.setLocation(0,0);
Service.setSelectedIndex (1);
howOften.setSelectedIndex (1);
numTrees.setSelectedIndex (1);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menuFile = new JMenu("File", true);
menuFile.setMnemonic(KeyEvent.VK_F);
menuFile.setDisplayedMnemonicIndex(0);
menuBar.add(menuFile);
JMenu menuSave = new JMenu("Save", true);
menuSave.setMnemonic(KeyEvent.VK_S);
menuSave.setDisplayedMnemonicIndex(0);
menuBar.add(menuSave);
JMenu menuExit = new JMenu("Exit", true);
menuExit.setMnemonic(KeyEvent.VK_X);
menuExit.setDisplayedMnemonicIndex(0);
menuBar.add(menuExit);
}
class clrButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// clearButton.addActionListener(this);
firstName.setText("");
lastName.setText("");
Address.setText("");
City.setText("");
}
}
class subButton implements ItemListener {
public void itemStateChanged(ItemEvent e) {
submitButton.addItemListener(this);
Service.addItemListener(this);
numTrees.addItemListener(this);
howOften.addItemListener(this);
}
}
}
I was able to get it to work...Thank you all for your help. I removed the class and it worked.
Here is the working code:
[Code]
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class cousinsTree extends JApplet implements ActionListener
{
Container Panel;
JButton submitButton;
JButton clearButton;
JTextField firstName;
JTextField lastName;
JTextField Address;
JTextField City;
JMenuBar menuBar;
JTextField Total;
JComboBox Service;
JComboBox howOften;
JComboBox numTrees;
LayoutManager setLayout;
String[] TreeList;
String[] numList;
String[] oftenList;
public void init()
{
Panel = getContentPane();
this.setLayout(new FlowLayout());
TreeList= new String[3];
TreeList [0] = "Trim";
TreeList [1] = "Chemical Spray";
TreeList [2] = "Injection";
numList = new String[3];
numList [0] = "0-5";
numList [1] = "6-10";
numList [2] = "11 >";
oftenList = new String[3];
oftenList [0] = "Monthly";
oftenList [1] = "Quarterly";
oftenList [2] = "Annually";
Panel.setBackground (Color.green);
submitButton = new JButton("Submit");
submitButton.setPreferredSize(new Dimension(100,30));
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setPreferredSize(new Dimension(100,30));
firstName = new JTextField("", 10);
JLabel lblFirstName = new JLabel("First Name");
lastName = new JTextField("", 10);
JLabel lblLastName = new JLabel("Last Name");
Address = new JTextField("", 15);
JLabel lblAddress = new JLabel("Address");
City = new JTextField("Columbus", 10);
JLabel lblCity = new JLabel("City");
Total = new JTextField("", 10);
JLabel lblTotal = new JLabel("Total");
//Service = new TextField("Service (Trim, Chemical Spray, or Injection).", 20);
JLabel lblService = new JLabel("Service");
Service=new JComboBox(TreeList);
JLabel lblhowOften = new JLabel("How often?");
howOften = new JComboBox(oftenList);
JLabel lblnumTrees = new JLabel("Number of Trees");
numTrees = new JComboBox(numList);
/* Configuration */
//add items to panel
Panel.add(lblFirstName);
Panel.add(firstName);
Panel.add(lblLastName);
Panel.add(lastName);
Panel.add(lblAddress);
Panel.add(Address);
Panel.add(lblCity);
Panel.add(City);
Panel.add(lblnumTrees);
Panel.add(numTrees);
Panel.add(lblService);
Panel.add(Service);
Panel.add(lblhowOften);
Panel.add(howOften);
Panel.add(submitButton);
Panel.add(clearButton);
Panel.add(lblTotal);
Panel.add(Total);
this.setSize(new Dimension(375, 275));
this.setLocation(0,0);
Service.setSelectedIndex (1);
howOften.setSelectedIndex (1);
numTrees.setSelectedIndex (1);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menuFile = new JMenu("File", true);
menuFile.setMnemonic(KeyEvent.VK_F);
menuFile.setDisplayedMnemonicIndex(0);
menuBar.add(menuFile);
JMenu menuSave = new JMenu("Save", true);
menuSave.setMnemonic(KeyEvent.VK_S);
menuSave.setDisplayedMnemonicIndex(0);
menuBar.add(menuSave);
JMenu menuExit = new JMenu("Exit", true);
menuExit.setMnemonic(KeyEvent.VK_X);
menuExit.setDisplayedMnemonicIndex(0);
menuBar.add(menuExit);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == clearButton) {
firstName.setText("");
lastName.setText("");
Address.setText("");
City.setText("");
}
}
}
[/Code]
Add following line
clearButton.addActionListener(new clrButton());
class clrButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// clearButton.addActionListener(this); Comment it
// if(e.getSource() == clearButton){-> this line don't need.
firstName.setText("");
lastName.setText("");
Address.setText("");
City.setText("");
}
}
You are doing good. But just place the following code
clearButton.addActionListener(new clrButton());
Before and outside of class clrButton
Also try placing these statements outside of class subButton
submitButton.addItemListener(new subButton());
Service.addItemListener(new anotherClass());
numTrees.addItemListener(new anotherClass());
howOften.addItemListener(new anotherClass());
You need to add actionlistener to your buttons. so, the action events will be propogated to the listener where you do your logic of the action. so, you have to addActionListener to your button
clearButton.addActionListener(new clrButton());
i.e in your init() method
clearButton = new JButton("Clear");
clearButton.setPreferredSize(new Dimension(100,30));
//add this below line to add action listener to the button
clearButton.addActionListener(new clrButton());
Onemore line to be removed is clearButton.addActionListener(this); from your action performed method

Action Listener does not work on swing

I have a form , That when i click to save button, "Yes" String should display on my console!
(I use "Yes" String for test!)
But does not work when clicked.
My code:
public final class NewUserFrame1 extends JFrame implements ActionListener {
UserInformation userinfo;
JLabel fnamelbl;
JLabel lnamelbl;
JTextField fntf;
JTextField lntf;
JLabel gndlnl;
JRadioButton malerb;
JRadioButton femalerb;
ButtonGroup bgroup;
JLabel registnm;
JButton savebt;
JButton cancelbt;
JLabel showreglbl;
public NewUserFrame1() {
add(rowComponent(), BorderLayout.CENTER);
setLocation(200, 40);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public JPanel rowComponent() {
JPanel panel = new JPanel();
fnamelbl = new JLabel("First name");
lnamelbl = new JLabel("Last Name");
JLabel fntemp = new JLabel();
JLabel lntemp = new JLabel();
fntf = new JTextField(10);
lntf = new JTextField(10);
gndlnl = new JLabel("Gender");
malerb = new JRadioButton("Male");
femalerb = new JRadioButton("Female");
bgroup = new ButtonGroup();
bgroup.add(malerb);
bgroup.add(femalerb);
registnm = new JLabel("Registration ID is:");
showreglbl = new JLabel("");
JLabel regtemp = new JLabel();
savebt = new JButton("Save");
cancelbt = new JButton("Cancell");
JLabel buttontemp = new JLabel();
panel.add(fnamelbl);
panel.add(fntf);
panel.add(fntemp);
panel.add(lnamelbl);
panel.add(lntf);
panel.add(lntemp);
panel.add(gndlnl);
JPanel radiopanel = new JPanel();
radiopanel.setLayout(new FlowLayout(FlowLayout.LEFT));
radiopanel.add(malerb);
radiopanel.add(femalerb);
panel.add(radiopanel);
panel.add(new JLabel());
panel.add(registnm);
panel.add(showreglbl);
panel.add(regtemp);
panel.add(savebt);
panel.add(cancelbt);
panel.add(buttontemp);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 5, 3, 50, 10, 80, 60);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
NewUserFrame1 newUserFrame1 = new NewUserFrame1();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == savebt) {
System.out.print("Yes");
}
}
}
You need to add an ActionListener to your button like so:
savebt.addActionListener(this);
or with an anonymous class, like so:
savebt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code.
}
});
Using anonymous classes (or inner classes) is better because you can't have more than one actionPerformed() method in a given class.
You need to tell the button to invoke the ActionListener:
savebt = new JButton("Save");
savebt.addActionListener(this);
Note if you intend to use the same method for the save and cancel buttons, you'll need to differentiate, perhaps by comparing the source of the ActionEvent against the two buttons.

Categories

Resources