Trouble making basic java program to count your number of clicks - java

why doesn't this work correctly? i cant seem to find the problem
its suppose to increment the text display by one for each time the button is clicked
public class ClickerGame extends javax.swing.JFrame {
public ClickerGame() {
initComponents();
}
//declare
int clicks;
String clicksout = "" + clicks;
//Swing GUI netbeans code is here, removed because it is irrelevant
//click increments number by 1
private void clickActionPerformed(java.awt.event.ActionEvent evt) {
clicks++;
clickercounter.setText(clicksout);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ClickerGame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton click;
private javax.swing.JTextField clickercounter;
// End of variables declaration
}

You only set clicksout once:
String clicksout = "" + clicks;
The value isn't reset dynamically if clicks change. If you never change it, you'll always get the same result here:
clickercounter.setText(clicksout);
Try this instead:
clickercounter.setText("" + clicks);
You won't need clicksout as a separate variable.

Related

Is it possible to have a JLabel changing its Text depending on a variable value?

I'created a JLabel that should display "TextA" if the variable count == -1,
"Text B" if the variable count == 0 and "TextC" if the variable count == 1.
I've used Swing to create my interface, which you can see below
TempConverter
The red rectangle shows where the JLabel should be.
I have tried creating 3 JLabels and changing the setVisible(Boolean) whenever the variable count value condition applies. This didn't work because I got the following error:
Exception in thread "main" java.lang.NullPointerException
at tempconverterUI.TempConverter.main(TempConverter.java:354)
C:\Users\x\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
And the JLabels could not be placed in the same location in the GUI (overlapping was not possible).
I've tried using jLabel.setText() to change the Text displayed in the JLabel, whenever the variable condition applied. I got a similar error to the one above (if not the same).
I've read some other posts and researched further and found that some people suggested ActionListeners to be set but I am unsure that these will work with a simple variable, as opposed to a component in the GUI.
My Code is as follows:
package tempconverterUI;
import javax.swing.JOptionPane;
import messageBoxes.UserData;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.WString;
public class TempConverter extends javax.swing.JFrame {
public interface someLib extends Library
{
public int engStart();
public int endStop();
public int engCount();
public WString engGetLastError();
public int engSetAttribute(WString aszAttributeID, WString aszValue);
}
/**
* Creates new form TempConverter
*/
public TempConverter() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
The layout is created here, followed by the Temperature convertion methods and unrelated component's functionality (which I believe is not relevant in this case)
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/**This is where the Login form gets created*/
UserData.popUp();
/**After this the Library functions are called, which will return the variable count value*/
someLib lib = (someLib) Native.loadLibrary("someLib", someLib.class);
int startResult = lib.engStart();
System.out.println(startResult);
if (startResult < 0)
{
System.out.println(lib.engGetLastError());
}
System.out.println(UserData.getAcInput());
int setAtResult = lib.engSetAttribute(new WString("CODE"), UserData.getAcInput());
System.out.println(setAtResult);
if (setAtResult < 0)
{
System.out.println(lib.engGetLastError());
}
And next is the piece of code from where I should control the JLabel Text to display
int count = lib.engCount();
System.out.println(count);
if (count == -1)
{
System.out.println(lib.engGetLastError());
}
else if (count == 0)
{
}
else
{
}
new TempConverter().setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JPanel bottomPanel;
private javax.swing.JButton convertButton;
private static javax.swing.JButton button;
private javax.swing.JTextField from;
private javax.swing.JComboBox<String> fromCombo;
private javax.swing.JLabel fromLabel;
private javax.swing.JLabel title;
private javax.swing.JTextField to;
private javax.swing.JComboBox<String> toCombo;
private javax.swing.JLabel toLabel;
private javax.swing.JPanel topPanel;
// End of variables declaration
}
Any help with this would be much appreciated. If you could include a simple code example as well, this would be fantastic as I am new to Java (and programming, in general).
Issues:
Don't set the JLabel visible, but rather add it initially to the GUI, leave it visible by default, and simply set its text via setText(...).
Give the class that holds the JLabel public methods that allow outside classes the ability to set the label's text. Something like public void setLabelText(String text), and in the method call setText(text) on the JLabel.
Debug your NullPointerException as you would any other NPE -- look at the stacktrace, find the line that throws it, and then look back into the code to see why a key variable on that line is null.
When and how you change the JLabel will depend on what event you want to listen for. If it is user input, then you will want to respond to that input, be it an ActionListener added to a JButton or to a JTextField, or an itemListener added to a JRadioButton.
If you want instead to listen for the change in state of a variable, no matter how the variable is changed, then make it a "bound property" (tutorial) using PropertyChangeSupport and a PropertyChangeListener.
For an example of the latter:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
#SuppressWarnings("serial")
public class ShowCount extends JPanel {
private static final int TIMER_DELAY = 1000;
private JLabel countLabel = new JLabel(" ");
private CountModel model = new CountModel();
public ShowCount() {
model.addPropertyChangeListener(CountModel.COUNT, new ModelListener(this));
setPreferredSize(new Dimension(250, 50));
add(new JLabel("Count:"));
add(countLabel);
Timer timer = new Timer(TIMER_DELAY, new TimerListener(model));
timer.start();
}
public void setCountLabelText(String text) {
countLabel.setText(text);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
ShowCount mainPanel = new ShowCount();
JFrame frame = new JFrame("ShowCount");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class CountModel {
public static final String COUNT = "count"; // for count "property"
// support object that will notify listeners of change
private SwingPropertyChangeSupport support = new SwingPropertyChangeSupport(this);
private int count = 0;
public int getCount() {
return count;
}
public void setCount(int count) {
int oldValue = this.count;
int newValue = count;
this.count = count;
// notify listeners that count has changed
support.firePropertyChange(COUNT, oldValue, newValue);
}
// two methods to allow listeners to register with support object
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
support.addPropertyChangeListener(propertyName, listener);
}
}
class ModelListener implements PropertyChangeListener {
private ShowCount showCount;
public ModelListener(ShowCount showCount) {
super();
this.showCount = showCount;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
int newValue = (int) evt.getNewValue();
showCount.setCountLabelText(String.format("%03d", newValue));
}
}
class TimerListener implements ActionListener {
private CountModel model;
public TimerListener(CountModel model) {
super();
this.model = model;
}
#Override
public void actionPerformed(ActionEvent e) {
int oldCount = model.getCount();
int newCount = oldCount + 1;
model.setCount(newCount);
}
}

Setting the text in jTextField and then retrieving that text

package test2;
public class NewJFrame extends javax.swing.JFrame {
private static void valueGen(javax.swing.JTextField jTextField1) {
String x = jTextField1.getText();
System.out.println(x);
}
public NewJFrame() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
jTextField1.setText("Hello");
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
public javax.swing.JTextField getTextField() {
jTextField1.getText();
return this.jTextField1;
}
public static void main(String args[]) {
NewJFrame myFrame = new NewJFrame();
valueGen(myFrame.getTextField());
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;
}
I have a program as shown above. I need to set the text "hello" in a text field when the submit button is clicked. It works. But then i need to use that text in a function called valueGen where it is printed. But the text doesn't get printed by executing the above code. What is wrong with this code?
It's unorganized. Always put class variables at the top.
Like Cool Guy said, put myFrame instead of new NewJTest()
valueGen is actually being called before you can click the button. Put it in the jTextField1ActionPerformed; that might fix it.
In netbeans out put of the System.out.println(); will be displayed in the output window as shown in the bellow picture.
If you want to display it as a message replace the following method with your valueGen() method.
private static void valueGen(javax.swing.JTextField jTextField1) {
String x = jTextField1.getText();
System.out.println(x);
JOptionPane.showMessageDialog(null, x);
}
And use myFrame.setVisible(true); to make visible your JFrame.
public void run() {
NewJFrame myFrame = new NewJFrame();
myFrame.setVisible(true);
valueGen(myFrame.getTextField());
}

Text of JTextArea not being retrieved?

I want to get the text of private access JTextArea from another class in the same package and store/save the text into a String.
public class JTextAreaDemo extends javax.swing.JFrame {
public JTextAreaDemo() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
TxtArea_Class d = new TxtArea_Class();
d.readJtxtAreaText();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JTextAreaDemo().setVisible(true);
}
});
}
private javax.swing.JTextArea jTextArea1;
/**
* #return the jTextArea1
*/
public String getjTextArea1() {
return jTextArea1.getText();
}
/**
* #param jTextArea1 the jTextArea1 to set
*/
public void setjTextArea1(javax.swing.JTextArea jTextArea1) {
this.jTextArea1 = jTextArea1;
}
Now I want to save the text of JTextArea to string in below class
public class TxtArea_Class {
JTextAreaDemo demo;
String txt;
public TxtArea_Class(){
demo = new JTextAreaDemo();
txt = new String();
}
public void readJtxtAreaText(){
txt = demo.getjTextArea1();
if(txt.isEmpty()){
System.out.println("Failed To Get TextArea Contents ");
}
else{
System.out.println("Successfully Get TextArea Contents ");
}
}
Console Output :
Failed to Get TextArea Contents
Problem is in your TextArea_Calss's constructor
try the following.
public TextArea_class(TextAreaDemo demo) {
this.demo = demo;
this.str = new String();
}
and in button event. do this.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
TxtArea_Class d = new TxtArea_Class(this);
d.readJtxtAreaText();
}
In current implementation, Every-time you create an instance of TextArea-calss a new frame get created. because in TextArea_Class constructor you are creating an new instance of demo class.
and you are trying to get value from newly created demoFrame(that might be invisible for you but exist).
I'm hoping this will solve your issue.
You have two different instances of JTextAreaDemo!! One created in main and made visible, the other created in TxtArea_Class. The first one is the one on the screen, and the second is the one you read the string from. So the text you enter into the first doesn't show in the second.
I got the contents of JTxtArea from another class by updating my code by this.
TextArea_class
public TextArea_class(TextAreaDemo demo) {
this.demo = demo;
this.str = new String();
}
JTxtAreaDemo
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
TxtArea_Class d = new TxtArea_Class(this);
d.readJtxtAreaText();
}

Java Swing button actionEvent

sorry to bother everyone.
Overall problem: I'm trying to open a dialogue box let the user enter something then close it
Issue: - A function is not being called (i think)
- The main problem is when i use debug it works fine so Its difficult for me to track down the problem
I'm having trouble with JButtons,
it works in debug but not in normal run. this was probably because i was using an infinite loop. someone online suggested i used SwingUtilities but that didn't work (at least i don't think.
/**
*
* #author Deep_Net_Backup
*/
public class butonTest extends JFrame {
String name;
boolean hasValue;
//name things
private JLabel m_nameLabel;
private JTextField m_name;
//panel
private JPanel pane;
//button
private JButton m_submit;
//action listener for the button submit
class submitListen implements ActionListener {
public void actionPerformed(ActionEvent e) {
submit();
System.out.println("Test");
}
}
//constructor
public butonTest(){
//normal values
name = null;
hasValue = false;
//create the defauts
m_nameLabel = new JLabel("Name:");
m_name = new JTextField(25);
pane = new JPanel();
m_submit = new JButton("Submit");
m_submit.addActionListener(new submitListen());
//
setTitle("Create Cat");
setSize(300,200);
setResizable(false);
//add components
pane.add(m_nameLabel);
pane.add(m_name);
pane.add(m_submit);
add(pane);
//last things
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//submit
private void submit()
{
System.out.println("submit");
name = m_name.getText();
hasValue = true;
}
//hasValue
public boolean hasValue()
{
return(hasValue);
}
//get the text name
public String getName()
{
return(name);
}
public void close()
{
setVisible(false);
dispose();
}
public static void main(String[] args)
{
/* Test 1
boolean run = true;
String ret = new String();
butonTest lol = new butonTest();
while(run)
{
if(lol.hasValue())
{
System.out.println("Done");
run = false;
ret = new String(lol.getName());
lol.close();
}
}
System.out.println(ret);*/
//Tset 2
/*
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
butonTest lol = new butonTest();
if(lol.hasValue())
{
System.out.println(lol.getName());
}
}
});*/
}
}
Edit:
How its not working: When i run Test the program will print test and submit then it should change the hasValue to true. this will (hopefully) allow the if statement to run to print done. This does not happen.
Edit 2:
I have just added a few more lines for further testing 2 prints and this seems to have solved the issue (but this is bad)
System.out.println("hasValue " + hasValue); -> to the hasValue() function
System.out.println("set to true"); -> submit() function
You are doing something far too complicated than is necessary. Instead of having the listener as a seperate class, you could have it as an anonymous class. That way you can get a handle on the outer class (butonTest.this), and call any method you want on it.
m_submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
submit();
System.out.println("Test");
butonTest.this.close();
}
});
I'm not sure what you are trying to do with the infinite loop. It would have run to completion before you show the dialog anyway.
It would help to read up a bit on how Event-Handling works in Swing :)
I am afraid your constructor butonTest() and submit() method are out of your
class (public class butonTest extends JFrame).
you need to get them inside your class:

Access static variable from another class

I have two classes in same package. i have declared a static variable in one class and want to access that variable in another class.
Here is my code in which i have declared the static variable
public class wampusGUI extends javax.swing.JFrame {
static String userCommand;
public wampusGUI() {
initComponents();
}
public void setTextArea(String text) {
displayTextArea.append(text);
}
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
userCommand = commandText.getText();
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
wampusGUI w = new wampusGUI();
w.setVisible(true);
Game g = new Game(w);
g.play();
}
});
}
}
Here is the code in which i want to access variable
public class Game {
private wampusGUI gui;
public Game(wampusGUI w) {
world = new World();
world.start();
gui = w;
}
public void play() {
gui.setTextArea(welcome());
gui.setTextArea(describe());
for (;;) {
String s = userCommand; // here value should come should
System.out.println(userCommand);
Command c = Command.create(s);
String r = c.perform(world);
// is game over?
if (r == null) {
break;
}
System.out.println(r);
}
System.out.println("Game over");
}
}
However, i can pass the variable from first class as a argument. but the problem is that, when i will run program the value is going null first time, which i dont want. i want when i enter value in textfield then it should go to another class.
Thank you.
Looking at your code, it seems you want to show dialogs to your user with a certain text
gui.setTextArea(welcome());
gui.setTextArea(describe());
and sometimes, that dialog should capture user input which is handled afterwards.
Those setTextArea calls are not what you want to use. The user will never see the welcome message as it will immediately be replaced by the describe message.
Make sure you do not block the Event Dispatch Thread (EDT) or nothing will be shown at all. I do not know what your Command class will do, but I see an infinite loop on the Event Dispatch Thread which is never a good thing. Take a look at the Concurrency in Swing tutorial for more information
Thanks to that for loop, the user will simply not be capable to input any command as the EDT is busy handling your loop. What you need is a blocking call allowing the user to provide input (not blocking the EDT, but just blocking the execution of your code). The static methods in the JOptionPane class are perfectly suited for this (e.g. the JOptionPane#showInputDialog). These methods also have a mechanism to pass the user input back to the calling code without any static variables, which solves your problem.
I suggest that you use a listener of one sort or another to allow the Game object to listen for and respond to changes in the state of the GUI object. There are several ways to do this, but one of the most elegant and useful I've found is to use Swing's own innate PropertyChangeSupport to allow you to use PropertyChangeListeners. All Swing components will allow you to add a PropertyChangeListener to it. And so I suggest that you do this, that you have Game add one to your WampusGUI class (which should be capitalized) object like so:
public Game(WampusGUI w) {
gui = w;
gui.addPropertyChangeListener(new PropertyChangeListener() {
// ....
}
This will allow Game to listen for changes in the gui's state.
You'll then want to make the gui's userCommand String a "bound property" which means giving it a setter method that will fire the property change support notifying all listeners of change. I would do this like so:
public class WampusGUI extends JFrame {
public static final String USER_COMMAND = "user command";
// ....
private void setUserCommand(String userCommand) {
String oldValue = this.userCommand;
String newValue = userCommand;
this.userCommand = userCommand;
firePropertyChange(USER_COMMAND, oldValue, newValue);
}
Then you would only change this String's value via this setter method:
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
setUserCommand(commandText.getText());
}
The Game's property change listener would then respond like so:
gui.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
// is the property being changed the one we're interested in?
if (WampusGUI.USER_COMMAND.equals(pcEvt.getPropertyName())) {
// get user command:
String userCommand = pcEvt.getNewValue().toString();
// then we can do with it what we want
play(userCommand);
}
}
});
One of the beauties of this technique is that the observed class, the GUI, doesn't have to have any knowledge about the observer class (the Game). A small runnable example of this is like so:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
public class WampusGUI extends JFrame {
public static final String USER_COMMAND = "user command";
private String userCommand;
private JTextArea displayTextArea = new JTextArea(10, 30);
private JTextField commandText = new JTextField(10);
public WampusGUI() {
initComponents();
}
private void setUserCommand(String userCommand) {
String oldValue = this.userCommand;
String newValue = userCommand;
this.userCommand = userCommand;
firePropertyChange(USER_COMMAND, oldValue, newValue);
}
private void initComponents() {
displayTextArea.setEditable(false);
displayTextArea.setFocusable(false);
JButton enterButton = new JButton("Enter Command");
enterButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
enterButtonActionPerformed(evt);
}
});
JPanel commandPanel = new JPanel();
commandPanel.add(commandText);
commandPanel.add(Box.createHorizontalStrut(15));
commandPanel.add(enterButton);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(new JScrollPane(displayTextArea));
mainPanel.add(commandPanel, BorderLayout.SOUTH);
add(mainPanel);
}
public void setTextArea(String text) {
displayTextArea.append(text);
}
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
setUserCommand(commandText.getText());
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
WampusGUI w = new WampusGUI();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.pack();
w.setLocationRelativeTo(null);
w.setVisible(true);
Game g = new Game(w);
g.play();
}
});
}
}
class Game {
private WampusGUI gui;
public Game(WampusGUI w) {
gui = w;
gui.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
// is the property being changed the one we're interested in?
if (WampusGUI.USER_COMMAND.equals(pcEvt.getPropertyName())) {
// get user command:
String userCommand = pcEvt.getNewValue().toString();
// then we can do with it what we want
play(userCommand);
}
}
});
}
public void play() {
gui.setTextArea("Welcome!\n");
gui.setTextArea("Please enjoy the game!\n");
}
public void play(String userCommand) {
// here we can do what we want with the String. For instance we can display it in the gui:
gui.setTextArea("User entered: " + userCommand + "\n");
}
}
I agree with Jon Skeet that this is not a good solution...
But in case u want an dirty solution to ur problem then u can try this:
public class wampusGUI extends javax.swing.JFrame
{
private static wampusGUI myInstance;
public wampusGUI( )
{
myInstance = this;
initComponents();
}
public static void getUserCommand()
{
if(myInstance!=null)
{
return myInstance.commandText.getText();
}
else
{
return null;
}
}
......
......
}
in the other class use:
public void play()
{
.....
//String s = userCommand; // here value should come should
String s = wampusGUI.getUserCommand();
.....
}
This kind of code is there in some of our legacy projects... and I hate this.

Categories