I'm trying to count the number of pushes on a button in my program.
I want it to change everytime I push the button, to show the number of pushes done by the user.
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // needed for listeners
public class PushCounter3 {
public static void main(String[] arg) {
PushGUI myGui = new PushGUI();
}
}
class PushGUI extends JPanel{
private JFrame theWindow;
private int nbPushes;
private JButton myButton;
private JLabel myLabel;
private JPanel myPanel;
PushGUI(){
theWindow = new JFrame("Push Counter that counts!");
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
nbPushes = 0;
myButton = new JButton("Push Me!");
myLabel = new JLabel("Pushes: " + Integer.toString(nbPushes));
// let's register the event listener
myButton.addActionListener(new ButtonListener());
myPanel = new JPanel();
theWindow.add(myPanel);
myPanel.add(myButton);
myPanel.add(myLabel);
theWindow.pack();
theWindow.setVisible(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
nbPushes++;
myLabel.setText("Pushes: " + Integer.toString(nbPushes));
}
}
}
Everything shows on the screen, but doesn't get updated everytime I click on the button.
make nbPushes variable static and see if it updates correctly
Related
This program is supposed to count mouse clicks but it only counts the first one. The code is nothing complicated but I don't get why it only counts the first click.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing {
private JLabel label;
public swing() {
JFrame frame = new JFrame("exemple");
frame.setBounds(200, 200, 200, 200);
JButton button = new JButton("clic clic");
button.addActionListener(new MyActionListener());
label = new JLabel("0");
JPanel pane = new JPanel();
pane.add(button);
pane.add(label);
frame.getContentPane().add(pane,
BorderLayout.CENTER);
frame.show();
}
private class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
int count = 0;
count++;
label.setText("Number of Mouse Clicks = "+ count);
}
}
public static void main(String[] args) {
new swing();
}
}
Thank you to user WJS who has commented with an answer, I had to simply Move count =0 outside the actionPerformed method but inside the listener class.
on every click you are setting the counter again to zero and then showing the incremented value and after each click value of counter is reset to zero.
you need to move the count outside of actionPerformed
int count = 0;
private class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
count++;
label.setText("Number of Mouse Clicks = " + count);
}
}
I have a class called Windows. The class extends JFrame and adds GUI components to the JFrame container. One of those components is a JTextfield. I am trying to set the text in the JTextfield through the actionPerformed() when generator JButton is clicked. The actionPerformed() is a class called EvenHandler. This is the eventHandler:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class EventHandler implements ActionListener {
int x = 0;
PassWordGenerator password;
Window Window; // It works only when static Window Window.
public void start() {
Window = new Window();
}
#Override
public void actionPerformed(ActionEvent e) {
password = new PassWordGenerator(3,3,3,3);
Window.setGeneratedPswd(password.getPswd());
x += 1;
System.out.println(x);
}
public static void main(String[] args) {
EventHandler x = new EventHandler();
x.start();
}
}
the window class if you want to know how the GUI looks like. The button is the one calling actionePerfome().
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
Label passwordLength;
Label labelGnPswd;
JTextField psdLength;
JCheckBox upperCase_letters;
JCheckBox lowerCase_letters;
JCheckBox numbers;
JCheckBox symbols;
JTextField generatedPswd;
EventHandler event = new EventHandler();
JButton generetor;
public Window() {
setLayout(new FlowLayout());
setTitle("PasswordGenerator");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
//Password Length
passwordLength = new Label("Password Length");
add(passwordLength);
//Input text
psdLength = new JTextField("0", 5);
add(psdLength);
//Create checkBoxes
createcheckbxs();
//Label Generated psw
labelGnPswd = new Label("Generated pswd");
add(labelGnPswd);
//Generated Password;
generatedPswd = new JTextField("****", 5);
generatedPswd.setEditable(false);
add(generatedPswd);
//Button
generetor = new JButton("Generate pswd!");
generetor.addActionListener(event);
add(generetor);
setSize(200, 400);
setVisible(true);
}
public String getpsdLength() {
return psdLength.getText();
}
public void setGeneratedPswd(String pswd) {
generatedPswd.setText(pswd);
}
private void createcheckbxs() {
upperCase_letters = new JCheckBox("Include uppercase");
add(upperCase_letters);
lowerCase_letters = new JCheckBox("Include lowercase");
add(lowerCase_letters);
numbers = new JCheckBox("Include numbers ");
add(numbers);
symbols = new JCheckBox("Include symbols ");
add(symbols);
}
}
My question is that When I clicked on the generator JButton I get an error message along the line, "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException..." I debugged the actionPerformed() and I found out that the Window Window is null when actionPefromed() is called after clicking genetor Jbutton. Why is Window null? Int x is working fine and it is not null. Isn't var x and window the same varaible scope. The only way I could keep the value of Window not null was to make Window a static variable.I hope my problem is a little more clear. Thanks in advance
Your problem seems in this line in Window.java:
generetor.addActionListener(event);
Variable event is declared in Window.java:
EventHandler event = new EventHandler();
The problem is that on event start() is not called so its instance variable Window Window remains null. The EventHandler you instantiate in main() is not used. What you might do is delete your start method and put its contents in the constructor.
So I'm new to programming and I've been making a program that uses multiple JPanels on a JFrame and other JPanels. I'm using CardLayout to go between different JPanels and I have it working on two different JButtons, but I can't get the last one to return to the main screen.
I've looked for answers, but it seems like most people just forget to use an ActionListener, something that I know I've done. Here's some of the involved classes in my code (There are a lot so I won't include them all, but I can provide any others that are needed).
Here's the JFrame class:
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.*;
public class ElephantCare extends JFrame {
private static final long serialVersionUID = 1L;
private final String MAIN_STRING = "Main";
public JPanel container, main;
private Staff1Panel staff1 = new Staff1Panel();
private Staff2Panel staff2 = new Staff2Panel();
private StaffConfirmPanel staffConfirm = new StaffConfirmPanel();
private WelcomePanel welcome = new WelcomePanel();
private StaffPanel staff = new StaffPanel();
private GallonsPanel gallons = new GallonsPanel();
private ToysPanel toys= new ToysPanel();
private ActionPanel action = new ActionPanel();
public CardLayout card = new CardLayout();
public ElephantCare() {
setSize(400,300);
setTitle("Elephant Care");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(container);
setVisible(true);
}
private void buildPanel() {
main = new JPanel();;
container = new JPanel(card);
container.add(main, MAIN_STRING);
container.add(staff1, "Staff 1");
container.add(staff2, "Staff 2");
main.setLayout(new BorderLayout());
main.add(welcome, BorderLayout.NORTH);
main.add(staff, BorderLayout.WEST);
main.add(gallons, BorderLayout.CENTER);
main.add(toys, BorderLayout.EAST);
main.add(action, BorderLayout.SOUTH);
staff.getStaff1Button().addActionListener(new Staff1Listener());
staff.getStaff2Button().addActionListener(new Staff2Listener());
staffConfirm.getConfirmButton().addActionListener(new ConfirmButtonListener());
}
private class Staff1Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
card.show(container, "Staff 1");
}
}
private class Staff2Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
card.show(container, "Staff 2");
}
}
private class ConfirmButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
card.show(container, MAIN_STRING);
}
}
}
Here's the JPanel with the Button:
import javax.swing.*;
public class StaffConfirmPanel extends JPanel{
private static final long serialVersionUID = 1L;
public JButton confirm;
public StaffConfirmPanel() {
confirm = new JButton("OK");
add(confirm);
}
public JButton getConfirmButton() {
return confirm;
}
}
And here's the JPanels where the button is used:
import java.awt.BorderLayout;
import javax.swing.*;
public class Staff1Panel extends JPanel{
private static final long serialVersionUID = 1L;
private Staff1NamePanel name = new Staff1NamePanel();
private Staff1JobPanel job = new Staff1JobPanel();
private StaffConfirmPanel confirm = new StaffConfirmPanel();
public Staff1Panel() {
setLayout(new BorderLayout());
add(name, BorderLayout.WEST);
add(job, BorderLayout.EAST);
add(confirm, BorderLayout.SOUTH);
}
}
And:
import java.awt.BorderLayout;
import javax.swing.*;
public class Staff2Panel extends JPanel{
private static final long serialVersionUID = 1L;
private Staff2NamePanel name = new Staff2NamePanel();
private Staff2JobPanel job = new Staff2JobPanel();
private StaffConfirmPanel confirm = new StaffConfirmPanel();
public Staff2Panel() {
setLayout(new BorderLayout());
add(name, BorderLayout.WEST);
add(job, BorderLayout.EAST);
add(confirm, BorderLayout.SOUTH);
}
}
Thanks for any help!
There are a lot of things happening in this code that are not quite right, and they contribute to your issue. So lets address the biggest issue and then you will need to do the rest yourself.
First edit this code to have some debug text:
private class ConfirmButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//NEW LINE OF CODE
System.out.println("ConfirmButtonListener was triggered");
card.show(container, MAIN_STRING);
}
}
Now when you run your code you will notice that the message "ConfirmButtonListener was triggered" will never be printed to the console, meaning that the code never runs, so you can never return to the main screen.
This happens because you create a StaffConfirmPanel named staffConfirm in your ElephantCare class. Then you add an action listener to staffConfirm. The problem is that you never use that staffconfirm panel anywhere because you create a new StaffConfirmPanel inside Staff1Panel and Staff2Panel so the action listener you have made will do nothing.
So the solution is to move the whole ConfirmButtonListener method and the staffConfirm.getConfirmButton().addActionListener line into the StaffConfirmPanel class like so:
import javax.swing.*;
public class StaffConfirmPanel extends JPanel{
private static final long serialVersionUID = 1L;
public JButton confirm;
public StaffConfirmPanel() {
confirm = new JButton("OK");
add(confirm);
//NEW LINE: SET THE ACTION LISTENER
confirm.addActionListener(new ConfirmButtonListener());
}
public JButton getConfirmButton() {
return confirm;
}
//NEW CODE, MOVE THE ACTION LISTENER METHOD HERE
//ACTION LISTENER MOVED HERE
private class ConfirmButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//NEW LINE OF CODE
System.out.println("ConfirmButtonListener was triggered");
card.show(ElephantCare.container, ElephantCare.MAIN_STRING);
}
}
}
Now it should work correctly and return to the main screen.
EDIT: you will need to make MAIN_STRING a public variable in the ElephantCare class.
I have written code to convert Fahrenheit to Celsius. My action listener is not closing the program when clicking on the X in the top right of the window. Any guidance is appreciated. It seems the main class is not recognizing the code for the defaultcloseopertion.
import java.awt.*;
import java.awt.event.*;
public class TemperatureConversion extends Frame implements ActionListener
{
private final Label lblInput;
private final Label lblOutput;
private final TextField tfInput;
private final TextField tfOutput;
private double farenheit;
private double celcius;
public TemperatureConversion()
{
setLayout(new FlowLayout());
lblInput = new Label ("Enter degrees in Farenheit: ");
add(lblInput);
tfInput = new TextField(10);
add(tfInput);
tfInput.addActionListener(this);
lblOutput = new Label("Degrees in celcius:");
add(lblOutput);
tfOutput = new TextField(10);
tfOutput.setEditable(false);
add(tfOutput);
setTitle("Farenheit to Celcius Conversion");
setSize(350, 120);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
farenheit = Integer.parseInt(tfInput.getText());
celcius = (5.0/9)*(farenheit -32);
tfInput.setText("");
tfOutput.setText(celcius + "");
}
}
2nd file includes main class
import javax.swing.JFrame;
public class TemperatureConversionTest {
public static void main(String[] args)
{
TemperatureConversion textFieldFrame = new TemperatureConversion();
textFieldFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textFieldFrame.setSize(350, 100);
textFieldFrame.setVisible(true);
}
}
setDefaultCloseOperation is a member method of JFrame not java.awt.Frame
public class TemperatureConversion extends JFrame implements ActionListener
You need to call the below method after the setVisible(true); method.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this needs to be done explicitly in swing. One more thing that you need to address would be change the class signature to extend JFrame instead of Frame. Since, Frame is an awt library where as JFrame comes from swing.
public class TemperatureConversion extends JFrame implements ActionListener
Every time i click a button a new button is suppose appear, but it's not appearing after i press it unless i minimize the window and then open it again. heres my code for the GUI:
P.S. i was playing around with the code just in case your wondering about the variables.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Gui extends JFrame{
private Label Count;
private JTextField tfCount;
private Button btnCount;
public Gui(){
super("counter Gui");
setLayout(new FlowLayout());
Count = new Label("Box Maker");
add(Count);
tfCount = new JTextField(10);
tfCount.setEditable(true);
add(tfCount);
btnCount = new Button("Enter");
add(btnCount);
potatoHandler handler = new potatoHandler();
btnCount.addActionListener(handler);
tfCount.addActionListener(handler);
}
private class potatoHandler implements ActionListener{
public void actionPerformed(ActionEvent event) {
String s = "";
if (event.getSource() == tfCount || event.getSource() == btnCount){
Button newButton = new Button("new Button");
add(newButton);
}
}
}
}
Call revalidate and repaint on the container you added the button to
private class potatoHandler implements ActionListener{
public void actionPerformed(ActionEvent event) {
String s = "";
if (event.getSource() == tfCount || event.getSource() == btnCount){
Button newButton = new Button("new Button");
add(newButton);
revalidate();
repaint();
}
}
}