Changing a JButton on click event - java

I'm trying to do something very simple, change the text in a button when it has been clicked.
I can't seem to get it to work, can someone show me the correct place to add an ActionListener?
Main Class
public class ATM implements ActionListener{
public static void main(String[] args) {
atmGUI gui = new atmGUI();
gui.login();
}
}
atmGUI Class
public class atmGUI implements ActionListener {
public JTextField usernameField;
public JTextField pinField;
public String userName;
public int pin;
/**
* #wbp.parser.entryPoint
*/
public void login() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setTitle("Virtual Bank Account");
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(16, 88, 82, 16);
frame.getContentPane().add(lblUsername);
usernameField = new JTextField();
usernameField.setBounds(13, 107, 124, 28);
frame.getContentPane().add(usernameField);
usernameField.setColumns(10);
JLabel lblPin = new JLabel("PIN");
lblPin.setBounds(16, 140, 61, 16);
frame.getContentPane().add(lblPin);
pinField = new JTextField();
pinField.setBounds(13, 157, 124, 28);
frame.getContentPane().add(pinField);
pinField.setColumns(10);
JButton btnLogin = new JButton("Login");
btnLogin.setBounds(355, 232, 117, 29);
btnLogin.addActionListener(new ActionListener(){
btnLogin.setText("Clicked");
});
frame.getContentPane().add(btnLogin);
frame.setResizable(false);
frame.setAlwaysOnTop(true);
frame.setVisible(true);
}
}
EDIT :
Here is the error that is produced
The type new ActionListener(){} must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent)

add function anonymous
btnLogin.addActionListener(new ActionListener(){
//do something
//lblUsername.setText("blah blah");
});
Detail:
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do something
//lblUsername.setText("blah blah");
}
});

You should implement the actionperformed() method inside your atmGUI class to handle the clicked action.

You will need to add the onActionPerformed(ActionEvent) method to your atmgui class, do it like:
public void onActionPerformed(ActionEvent avt)
{
//code to handle the button click
}
OR
You can also use it while initializing the JButton:
JButton b=new JButton("Click Me!" );
b.addActionListener(new ActionListener() {
//handle the button click here
}

Related

Iterating through an array list from another class problem

This is the class where I store the data:
package entities;
import java.util.ArrayList;
public class EshopData {
private static ArrayList<User> users = new ArrayList<User>();
public ArrayList<User> getUsers() {
return users;
}
public static void setUsers( ArrayList<User> users) {
EshopData.users = users;
}
}
This is my main Frame:
package ui;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import entities.User;
public class Frame extends JFrame{
public static void main(String[] args) {
//FRAME
JFrame frame = new JFrame("My first Eshop");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
//frame.setVisible(true);
frame.setLayout(null);
//LABELS
JLabel l1 = new JLabel("Username:");
JLabel l2 = new JLabel("Password:");
l1.setBounds(35, 60, 80, 20);
l2.setBounds(35, 110, 80, 20);
//TEXTFIELDS
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
tf1.setBounds(150, 60, 90, 20);
tf2.setBounds(150, 110, 90, 20);
//BUTTONS
JButton b1 = new JButton("Register");
JButton b2 = new JButton("Login");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
RegisterFrame rframe = new RegisterFrame();
rframe.setVisible(true);
rframe.setSize(600, 600);
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
}
});
b1.setBounds(35, 150, 100, 20);
b2.setBounds(160, 150, 80, 20);
//ADDING TO FRAME
frame.add(l1);
frame.add(l2);
frame.add(tf1);
frame.add(tf2);
frame.add(b1);
frame.add(b2);
frame.setVisible(true);
}
}
In my main Frame I have a button "Login" (its the 'b2' button) and I want to create an actionListener that will iterate through the array list from above and search for the User.username, if the username exists it will search for the User.password afterwards.
I am not sure whether I am explaining it correctly or not but any kind of help will be appreciated.
If you need any other part of the code I am here to provide it for you. Thnak's in advance!
You can create a custom wrapper class for ActionListener. This custom class, let's call it EshopDataBasedActionListener will contain a field for EshopData object. When you create this Listener, you will pass in the actual Object of EshopData that has already been created and that contains the user list. Now you are able to access this object inside your listener.
The next part of your problem of binding the Listener to your Login button will now be easier to achieve. You can now provide the implementation of the actionPerformed method that will contain your logic. You can pass in the username and password in the same fashion.

Reload the JFrame or JLabel

Im developing an little "clicker" but, if i press the button, and i should get 1+ Score, it dont work! Is there any way to reload or anything else?
Heres my code: (ClickEvent)
public class event implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("PRESS");
game.timesClicked.add(1);
points.setText(game.seePoints);
}
}
And there is my JFrame:
public class game extends JFrame
{
public static JButton buttonStart;
JButton buttonCredits;
JButton buttonBack;
JButton buttonLeave;
public static JFrame panel = new game();
public static ArrayList<Integer> timesClicked = new ArrayList<Integer>();
public static JLabel label1;
public static JLabel points;
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
public game()
{
setLayout(null);
label1 = new JLabel("ButtonClicker");
points = new JLabel(seePoints);
points.setFont(new Font("Tahoma", Font.BOLD, 15));
points.setBounds(0, 0, 200, 200);
label1.setFont(new Font("Tahoma", Font.BOLD, 50));
label1.setBounds(315, 50, 500, 200);
event e1 = new event();
JButton b = new JButton("KNOPF");
b.setBackground(new Color(96, 140, 247));
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
b.setFont(new Font("Tahoma", Font.BOLD, 15));
b.setBounds( 402, 380, 180, 50 );
b.addActionListener(e1);
add(b);
add(label1);
add(points);
}
}
(Sorry For My Bad English)
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
This is only being called once at the start of your program. When you add to timesClicked, it does not recalculate seePoints.
You will need to set this variable to the correct value every time you click.

Java:Background Image add on JFrame

I'm making a gui program everything going right but add background image in frame so i take jpanel private variable.Also i add image in src which is
but how to use this jpanel variable to add background image in frame.
Code:
public class App extends JFrame{
private JPanel panel;
private JTextField field1;
private JTextField print;
private JLabel label;
private JLabel label2;
private JButton button;
public App(){
super();
getContentPane().setLayout(null);
label = new JLabel("Value");
label.setForeground(Color.RED);
label.setFont(new Font("SansSerif", Font.PLAIN, 18));
label.setBounds(178, 46, 51, 26);
getContentPane().add(label);
label2 = new JLabel("Print");
label2.setForeground(Color.RED);
label2.setFont(new Font("SansSerif", Font.PLAIN, 18));
label2.setBounds(178, 143, 42, 26);
getContentPane().add(label2);
field1 = new JTextField();
field1.setBounds(178, 72, 76, 26);
getContentPane().add(field1);
print = new JTextField();
print.setBounds(178, 181, 77, 26);
getContentPane().add(print);
button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String w= field1.getText();
print.setText(w);
}
});
button.setBounds(178, 219, 77, 26);
getContentPane().add(button);
}
}
Main Method:
public class Main {
public static void main(String[] args) {
App object = new App();
object.setSize(450, 400);
object.setDefaultCloseOperation(object.EXIT_ON_CLOSE);
object.setLocationRelativeTo(null);
object.setVisible(true);
}
}
You have set Layout to null which is making a problem. Whenever we make layout null we have to set bounds for it.
Folow this method:
first of all copy your background image and paste in src of code
than set layout to borderlayout like this:
setLayout(new BorderLayout());
now add this code:
setContentPane(new JLabel new ImageIcon(getClass().getResource("image.jpg"))));
Note: add your image name here "image.jpg"

The type TextFieldDemo must implement the inherited abstract method ActionListener?

I almost have this code working. I can launch the GUI, however, when I press any of the buttons, I get the following error message:
The type TextFieldDemo must implement the inherited abstract method ActionListener
I have looked around online and can't see any issues with the code. Can someone help me please?
Thanks :)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TextFieldDemo implements ActionListener{
private JLabel lblName, lblAddress, lblPhone;
private JTextField txtName, txtAddress, txtPhone;
private JButton btnUpper, btnLower, btnExit;
private JPanel panel;
private JFrame frame;
public static void main(String[] args){
new TextFieldDemo();
}
public TextFieldDemo(){
createForm();
addFields();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createForm(){
frame = new JFrame();
frame.setTitle("Student Form");
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
}
public void addFields(){
txtName = new JTextField("Fred Bloggs");
txtName.setBounds(110, 50, 150, 20);
panel.add(txtName);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
panel.add (lblAddress);
txtAddress = new JTextField ("Ashley Road");
txtAddress.setBounds(110, 70, 150, 20);
panel.add (txtAddress);
lblPhone = new JLabel ("Phone Number");
lblPhone.setBounds(10, 90, 100, 20);
panel.add (lblPhone);
txtPhone= new JTextField("01202 191 3333");
txtPhone.setBounds(110, 90, 150, 20);
panel.add (txtPhone);
lblName = new JLabel("Student Name");
lblName.setBounds(10, 50, 100, 20);
panel.add(lblName);
}
public void addButtons(){
btnUpper = new JButton ("UpperCase");
btnUpper.setBounds(50, 200, 100, 20);
btnUpper.addActionListener(this);
panel.add (btnUpper);
btnLower = new JButton ("LowerCase");
btnLower.setBounds(150, 200, 100, 20);
btnLower.addActionListener(this);
panel.add (btnLower);
btnExit = new JButton ("Exit");
btnExit.setBounds(250, 200, 100, 20);
btnExit.addActionListener(this);
panel.add (btnExit);
}
class UpperCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toUpperCase());
txtAddress.setText(txtAddress.getText().toUpperCase());
}
class LowerCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toLowerCase());
txtAddress.setText(txtAddress.getText().toLowerCase());
}
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
}
}
You say TextFieldDemo implements ActionListener, but it doesn't have an actionPerformed() method, so it's not actually implementing the interface.
Either implement the method or don't claim it implements the interface.
I didn't think it would compile like you have it, but there you go!
The error should make you check the documentation of ActionListener to find out what method(s) is missing. Sometimes eclipse will prompt you to add stubs for the missing methods.
The documentation shows the interface ActionListener has one method to be implemented, actionPerformed();
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
Strange, the compiler should throw an error on this.

GUI building and using different classes Java

So I'm starting a new project and I was wondering how can I setup multiple classes for my different JPanels. It looks very messy in one class. Let me show you the example. I would like the JPanel for a menu screen in it's own class.
import java.awt.EventQueue;
public class TakeAwayLogin {
private JFrame frmTakeAwaySystem;
private JTextField textFieldId;
private JPasswordField passwordField;
/**
* Launch the application.
* #return
*/
public void login() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TakeAwayLogin window = new TakeAwayLogin();
window.frmTakeAwaySystem.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TakeAwayLogin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTakeAwaySystem = new JFrame();
frmTakeAwaySystem.setTitle("Take Away System Alpha");
frmTakeAwaySystem.setBounds(100, 100, 450, 300);
frmTakeAwaySystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTakeAwaySystem.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panelLogin = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelLogin, "name_254735117500687");
panelLogin.setLayout(null);
panelLogin.setVisible(true);
final JLabel lblIncorrect = new JLabel("Incorrect login, try again");
lblIncorrect.setHorizontalAlignment(SwingConstants.CENTER);
lblIncorrect.setFont(new Font("Tahoma", Font.PLAIN, 9));
lblIncorrect.setForeground(Color.RED);
lblIncorrect.setBounds(148, 74, 139, 14);
panelLogin.add(lblIncorrect);
lblIncorrect.setVisible(false);
final JPanel panelPassword = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPassword, "name_254738265432897");
panelPassword.setLayout(null);
passwordField = new JPasswordField();
passwordField.setBounds(112, 157, 205, 41);
panelLogin.add(passwordField);
passwordField.setHorizontalAlignment(JPasswordField.CENTER);
JButton btnNewButton = new JButton("Lock Application");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelPassword.setVisible(false);
panelLogin.setVisible(true);
passwordField.setText("");
textFieldId.disable();
}
});
btnNewButton.setBounds(135, 155, 172, 50);
panelPassword.add(btnNewButton);
panelPassword.setVisible(false);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String login = textFieldId.getText();
char[] pass = passwordField.getPassword();
String p = new String(pass);
String password = "pass";
if (login.equalsIgnoreCase("milan") && p.equals(password)) {
panelPassword.setVisible(true);
panelLogin.setVisible(false);
}else {
lblIncorrect.setVisible(true);
}
}
});
btnLogin.setBounds(160, 209, 97, 41);
panelLogin.add(btnLogin);
textFieldId = new JTextField();
textFieldId.setBounds(112, 88, 205, 43);
panelLogin.add(textFieldId);
textFieldId.setColumns(10);
textFieldId.setHorizontalAlignment(JTextField.CENTER);
JLabel lblId = new JLabel("Enter the business login:");
lblId.setHorizontalAlignment(SwingConstants.CENTER);
lblId.setBounds(112, 63, 205, 14);
panelLogin.add(lblId);
JLabel lblEnterYourPassword = new JLabel("Enter your password");
lblEnterYourPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterYourPassword.setBounds(148, 142, 139, 14);
panelLogin.add(lblEnterYourPassword);
JPanel panelPizza = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPizza, "name_254741096954780");
}
}
So help would be great.
Thanks very much.
I don't know why creating a second class would be necessary. If you just want the code to look less messy, then add comment separators between Panels or something to that effect. I think that splitting up the Panels into their own classes would be just cause you to have to write more calls to be able to create the same functionality. But if you must, then make a class within your initiate class and work from there.
Simplifying, you want something like:
public class MyMainJFrame extends JFrame{
private JPanel panel1 = new MyFooPanel();
private JPanel panel2 = new MyBarPanel();
public MyMainPanel(){
initialize();
}
void initialize(){
//init the JFrame
this.setTitle("Take Away System Alpha");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new CardLayout(0, 0));
//and add the panels
this.add(panel1);
this.add(panel2);
}
}
// a file for each one
public class MyFooPanel extends JPanel{
private JButton button;
//... add components and logic
}
public class MyBarPanel extends JPanel{
private JTextField field;
//... add components and logic
}
If you want to use specific methods for each custom panel, then change the type of variable for the same name of the custom class.

Categories

Resources