JLabel won't show the proper value of Getter - java

In my project, my problem is that the JLabel won't show the incremented value from the getter. It should be adding up everytime I choose the correct radiobutton.
This is the first JFrame
public class DifEasy extends javax.swing.JFrame {
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// jPanel1.setVisible(false);
if (q1a1.isSelected()){
ScoreStorage mehh = new ScoreStorage();
mehh.setRawscore(mehh.getRawscore()+1);
}
this.setVisible(false);
new DifEasy1().setVisible(true);
}
This is the 2nd JFrame
public class DifEasy1 extends javax.swing.JFrame {
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (q1a1.isSelected()){
ScoreStorage mehh = new ScoreStorage();
mehh.setRawscore(mehh.getRawscore()+1);
}
this.setVisible(false);
new DifEasy2().setVisible(true);
}
This is the 3rd JFrame
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (q1a1.isSelected()){
ScoreStorage mehh = new ScoreStorage();
mehh.setRawscore(mehh.getRawscore()+1);
jLabel1.setText(String.valueOf(mehh.getRawscore()));
}
}
btw I just put a JLabel there for testing. After clicking the JButton (Given that I choosed the q1a1 radiobutton), the JLabel should change into 3, but it shows up only 0.
Getters and Setters class
public class ScoreStorage {
private int Rawscore = 0;
public void setRawscore(int rawscore){
this.Rawscore = Rawscore;
}
public int getRawscore(){
return Rawscore;
}
public synchronized void increment(){
setRawscore(Rawscore);
}
public int reset(){
Rawscore = 0;
return Rawscore;
}
}

(Based on the comments from RubioRic and MadProgrammer)
The code has two problems:
the Setter in ScoreStorage doesn't work:
You've got a typo in ScoreStorage.setRawscore, you are assigning this.Rawscore = Raswcore instead of this.Rawscore = rawscore therefore the value of Rawscore is always 0.
(also note that ScoreStorage.increment() probably doesn't do what it should since it only reassign the value.)
You create multiply ScoreStorage objects.
Each time you select an option, you are creating a brand new instance of ScoreStorage, which is initialised to 0.
You can implement a method setScoreStorage or create a constructor that accepts that argument in your JFrames.
Here is a short example how to pass one ScoreStorage between the different JFrame with a constructor
public class DifEasy extends JFrame {
private ScoreStorage scoreStorage;
public DifEasy(ScoreStorage scoreStorage) {
this.scoreStorage = scoreStorage;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (q1a1.isSelected()){
scoreStorage.setRawscore(scoreStorage.getRawscore()+1);
}
this.setVisible(false);
new DifEasy1(scoreStorage).setVisible(true);
}

Related

Return a value for use in different class

I have the class BossInfo which extends JPanel and has a few components like JLabel, JTextField. My main method is in another file ("DamageCalculator").
Basically, a value is entered into a JTextField via an action listener and I'd like to pass that value to a different file (to use it in calculations). I'm having a lot of trouble with the logic. Here is my class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BossInfo extends JPanel {
private JLabel bossLabel, resultLabel;
private JTextField bossHp;
String bossHpText = new String("");
int valRecd = 0;
public BossInfo() {
//Labels
bossLabel = new JLabel("Boss HP: (Hit Enter to set)");
resultLabel = new JLabel("---");
//Text field for user input of boss hp
bossHp = new JTextField(15);
bossHp.addActionListener(new TempListener());
//add components
add(bossLabel);
add(bossHp);
add(resultLabel);
} //end BossInfo object
public void setVal(int valRecd) {
this.valRecd = valRecd;
}
private class TempListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
int hp;
bossHpText = bossHp.getText();
hp = Integer.valueOf(bossHpText);
dc.setVal(hp);
resultLabel.setText(bossHpText);
}//end action performed
}//end TempListener
} //end class BossInfo
How can I use bossHpText in another class? The "actionPerformed" gets mad if it's any return type other than void so I'm not sure it's meant to return anything.
EDIT: Code updated based on suggestions.
Have a variable valRecd in the MainClass.
On your actionPerformed, call the setter method for this valRecd, e.g,
MainClass obj = new MainClass(); //in your constructor.
public void actionPerformed(ActionEvent event) {
int hp;
bossHpText = bossHp.getText();
hp = Integer.parseInt(text);
obj.setVal(hp); //add this line.
resultLabel.setText(bossHpText);
}
where setVal might be something like this:
public void setVal(int valRecd) {
this.valRecd = valRecd;
}

How to reference the class fromasubclass

I am trying to find the answer but I can't. In java, when I create a subclass, how can I reffer the first level class? Using "this" accesses the subclass so I can't. The other option is passing the argument to the subclass but I'm curious if there is a simpliest method.
//here there is my other 1st level class implementation, this is a JFrame
btnNewProject.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
VehicleScreen pp=new VehicleScreen(**here should go the top class reference**);
//v is a JPanel that I pass to allJframes
v.setContentPane(pp);
v.setVisible(true);
}
});
class Foo {
int x;
Foo() {
new Runnable() {
public void run() {
Foo.this.x = 1;
}
}
}
}
You have a couple choices:
Make the variable outside the anonymous class an instance variable:
public class AnonymousClass extends JFrame {
private JLabel label;
...
public AnonymousClass() {
...
btnOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText(textField.getText());
}
});
...
}
You can also access the instance variable as follows:
AnonymousClass.this.label.setText(textField.getText());
Use the final modifier on the local variable:
public class AnonymousClass extends JFrame {
...
public AnonymousClass() {
final JLabel label = new JLabel("Enter a new message!");
btnOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText(textField.getText());
}
});
...
}
Be aware that using the final modifier will mean you cannot re-assign the variable at a later point in your program.

How to set all of the values back to the original start values

I have a game that is similar to the game of life. the game deals with creating a house and rearranging the neighbors and such. I WANT to restart the game, simply need to set all of these values back to the original start values. How do I do that with a code. I understand the English of it but cant seem to convert it to a code.
This is some of my main program (If anyone want me to post the whole main program I can) but to make it simple and I dont want to confuse you guys.
So what I WANT: to restart the game, simply I want to set all of these values back to the original start values.
Some Of Main Program:
public class Ghetto extends JFrame implements ActionListener, MouseListener,MouseMotionListener
{
protected Grids theGrid;
JButton resetButton;
javax.swing.Timer timer; // generates ticks that drive the animation
public final static int SIZE = 5;
public final static int BLUE = 10;
public final static int RED = 8;
public final static int DIVERSITY_PERCENTAGE = 70;
public static void main(String[] args)
{
new Ghetto();
}
public Ghetto() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(this);
addMouseMotionListener(this);
setLayout(new FlowLayout());
theGrid = new Grids(SIZE, BLUE, RED, DIVERSITY_PERCENTAGE);
add(theGrid);
resetButton = new JButton("Reset");
add(resetButton);
resetButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
resetWithCurrent();
}
});
setSize(new Dimension(550, 600));
setVisible(true);
}
//public void resetWithCurrent()
//{
//}
#Override
public void actionPerformed(ActionEvent e)
{
timer.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
performStep();
}
});
}
}
Typically, the eaiest way to "reset" is not to. Just throw away the object and make a brand new one! The constructor will take care of everything for you, and you won't have to worry about missing something. If you really need to, you can make a reset method that performs all the necessary setting, and have the constructor call it. You have to be sure to catch everything, so in particular you can't use any field initializations that look like Foo x = bar and you can't use any initializer blocks.
The approach I suggest:
Ghetto ghetto = new Ghetto();
//Do stuff with the ghetto.
ghetto = new Ghetto();
//BLAM! The old ghetto is *gone*, and we have a new one to play with.
If these "values" are stored in a separate class, say class "GameProperties" then you just need to invoke the constructor by creating a new instance of the GameProperties.
The constructor should take care of assigning default values.
So, assuming you have an instance of GameProperties within Ghetto class named props:
Add new instance of GameProperties class and change resetWithCurrent in Ghetto class:
GameProperties props = new GameProperties();
public void resetWithCurrent(){
//This will reset the values to their defaults as defined in the constructor
props = new GameProperties();
}
Remove the values constants as you are using your GameProperties. Use the getters methods
to obtain the properties values.
Create new class:
public class GameProperties {
//assign initial default values
private int size= 5;
private int blue= 10;
private int red= 8;
private int diversity_percentage= 70;
//calling default constructor will set the properties default values
public GameProperties(){
}
public int getSize(){
return size;
}
public int getBlueValue(){
return size;
}
public int getRedValue(){
return size;
}
public int getDiversityPercentage(){
return diversity_percentage;
}
}
Hope it helps.

java temperature conversion in GUI

im struggling again, with doing a program in java that converts the temperature from celsius to fahrenhiet, but it must be done in a GUI so that the user may enter in a number for celsius and click a botton to convert it. ive been modeling it off of a example in my book however in the book it shows it working with out having a static main(), but my IDE gave me an error saying that it was needed, so ive added a static main() and ive tried calling the tempwindow() to see if that would work but still nothing and even if i comment out the call it doesnt give me a error but nothing happens.
im hopping someone can help show me what im doing wrong and how i should go about this.
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.event.*;
public class tempcon extends JFrame
{
private JPanel panel;
private JLabel messageLabel;
private JTextField tempC;
// private JRadioButton tempF;
// private ButtonGroup radioButtonGroup;
private JButton calcButton;
private final int WINDOW_WIDTH = 400;
private final int WINDOW_HEIGHT = 100;
public tempwindow()
{
setTitle("Temurture convertion");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
messageLabel = new JLabel("enter tempurture in celsius");
tempC = new JTextField(10);
calcButton = new JButton("convert");
calcButton.addActionListener(new CalcButtonListener());
panel = new JPanel();
panel.add(messageLabel);
panel.add(tempC);
panel.add(calcButton);
}
private class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String input;
double temp;
input = tempC.getText();
temp = Double.parseDouble(input) * 1.8 + 32;
JOptionPane.showMessageDialog(null, "that is " + temp + "degrees fehrenhiet");
}
}
public static void main(String[] args)
{
tempwindow();
}
}
You are doing a few things wrong:
Your constructor can't have a different name from your class name
You need to instantiate the object to call the constructor, rather instantiating an object does call the constructor but you can't just access it like a method.
You should use the Java naming conventions for class names.
The class:
public class TempCon extends JFrame
{
// Variable declarations
public TempCon() // Constructor should match the Class name
{
}
}
The main class:
public static void main(String[] args)
{
TempCon converter = new TempCon();
}
public static void main(String[] args)
{
tempcon myTempWindowInstance = new tempcon();
myTempWindowInstance.tempwindow();
}
You never initialize a tempcon. Your constructor must have the same name as the class, so I recommend the following changes instead:
Replace public tempwindow() with public tempcon() to correct the constructor.
public tempcon()
{
setTitle("Temurture convertion");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
create an instance of tempcon using new, which calls the constructor:
public static void main(String[] args)
{
tempcon myTempWindowInstance = new tempcon();
}
please write return type your function like.
public void tempwindow()
create object of class and call method.
public static void main(String[] args)
{
tempcon t=new tempcon();
t.tempwindow();
}
and learn java object java object oriented programming.

java Swing -- JPanel and PropertyChangeListener

My use case is that a List<String> is passed to a Jpanel and for each String in the List, the JPanel renders a UI component. This UI component consists of 3 buttons and my current code for my given use case is as follows. -- The code for the 'UI component' follows --
public class MacroEditorEntity implements ActionListener {
private String macro;
private JButton upButton;
private JButton downButton;
private JButton MacroDetailsButton;
public MacroEditorEntity(String macro) {
this.macro = macro;
upButton = new JButton("Up");
downButton = new JButton("Down");
MacroDetailsButton = new JButton(macro);
upButton.addActionListener(this);
downButton.addActionListener(this);
MacroDetailsButton.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent evt) {
if(evt.getSource().equals(MacroDetailsButton))
{
System.out.println(macro);
}
}
public JButton GetUpButton()
{
return upButton;
}
public JButton GetDownButton()
{
return downButton;
}
public JButton getMacroDetailsButton()
{
return MacroDetailsButton;
}
}
The code for my Panel is as follows --
public class MacroEditor extends JPanel implements PropertyChangeListener {
private static final long serialVersionUID = 1L;
private List<String> stringlist;
public MacroEditor(List<String> list) {
this.stringlist = list;
setupComponents();
validate();
setVisible(true);
}
public void setupComponents()
{
Box allButtons = Box.createVerticalBox();
for(String string : stringlist)
{
MacroEditorEntity entry = new MacroEditorEntity(string);
Box entryBox = Box.createHorizontalBox();
entryBox.add(entry.GetUpButton());
entryBox.add(Box.createHorizontalStrut(15));
entryBox.add(entry.getMacroDetailsButton());
entryBox.add(Box.createHorizontalStrut(15));
entryBox.add(entry.GetDownButton());
allButtons.add(entryBox);
}
add(allButtons);
}
#Override
public void propertyChange(PropertyChangeEvent arg0) {
revalidate();
repaint();
}
}
The code works fine for all Strings in the passed List. I want my Panel to pick up any change that may happen to the List like additions or deletions and add/remove relevant corresponding UI components accordingly. I think this can be done by using PropertyChangeListener but have not been able to account for that in my code.
Any ideas or suggestions on how i can make my Panel render/rerender stuff as soon as there are changes to the List would be of help.
What you need here is an observable collection. This should do it: http://commons.apache.org/dormant/events/apidocs/org/apache/commons/events/observable/ObservableCollection.html
Edit:
Here's the code snippet you requested:
public class ObservableListExample implements StandardPostModificationListener,
StandardPreModificationListener {
public static void main(String[] args) {
new ObservableListExample();
}
public ObservableListExample() {
ObservableList list = ObservableList.decorate(new ArrayList<>(),
new StandardModificationHandler());
list.getHandler().addPostModificationListener(this);
list.getHandler().addPreModificationListener(this);
//....
}
#Override
public void modificationOccurring(StandardPreModificationEvent event) {
// before modification
Collection changeCollection = event.getChangeCollection();
if (event.isTypeAdd()) {
// changeCollection contains added elements
} else if (event.isTypeReduce()) {
// changeCollection contains removed elements
}
}
#Override
public void modificationOccurred(StandardPostModificationEvent event) {
// after modification
Collection changeCollection = event.getChangeCollection();
if (event.isTypeAdd()) {
// changeCollection contains added elements
} else if (event.isTypeReduce()) {
// changeCollection contains removed elements
}
}
}
By the way: Another concept that helps to bind buisness objects to your GUI and react to modifications (bidirectionally) is Data Binding. Have a look at this, a Data Binding Library commonly used with Swing.

Categories

Resources