Multiple classes in single file - java

I'm having trouble putting multiple classes into a single file. For example, when my file looks like:
public class FirstClass() {}
public class SecondClass() {}
public class ThirdClass() {}
I get an error during compilation. I'm not quite sure what's causing this. Any ideas?

One Java file can consist of multiple classes with the restriction that only one of them can be public. As soon as you remove public keyword from your classes, you can combine them into a single Java file.

At the risk of spoon-feeding
Please read http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TheaterWindow extends JFrame
{
private JPanel pnlAdultTicketPrice, pnlAdultTicketsSold, pnlChildTicketPrice, pnlChildTicketsSold,
pnlCalculate, pnlMain;
private JLabel lblAdultTicketPrice, lblAdultTicketsSold, lblChildTicketPrice, lblChildTicketsSold;
private JTextField txtAdultTicketPrice, txtAdultTicketsSold, txtChildTicketPrice, txtChildTicketsSold;
private JButton btnCalculate;
public TheaterWindow()
{
// Sets window title
setTitle("Theater");
// Sets layout to BorderLayout
setLayout(new GridLayout(5,1));
// Specifies what happens when close button is clicked
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Builds the panels
buildPanels();
// Add the panels to the frame's content pane
add(pnlAdultTicketPrice);
add(pnlChildTicketPrice);
add(pnlAdultTicketsSold);
add(pnlChildTicketsSold);
add(pnlCalculate);
// Size the frame to fit all of the panels
pack();
// Display the window
setVisible(true);
}
private void buildPanels()
{
// Creates labels to display instructions
lblAdultTicketPrice = new JLabel("Adult ticket price");
lblChildTicketPrice = new JLabel("Child ticket price");
lblAdultTicketsSold = new JLabel("Adult tickets sold");
lblChildTicketsSold = new JLabel("Child tickets sold");
// Creates text fields that are 10 characters wide
txtAdultTicketPrice = new JTextField(10);
txtChildTicketPrice = new JTextField(10);
txtAdultTicketsSold = new JTextField(10);
txtChildTicketsSold = new JTextField(10);
// Creates button with caption
btnCalculate = new JButton("Calculate");
// Adds action listener to button
btnCalculate.addActionListener(new CalcButtonListener());
// Creates panels
pnlAdultTicketPrice = new JPanel();
pnlChildTicketPrice = new JPanel();
pnlAdultTicketsSold = new JPanel();
pnlChildTicketsSold = new JPanel();
pnlCalculate = new JPanel();
pnlMain = new JPanel();
// Adds elements to their proper panels
pnlAdultTicketPrice.add(lblAdultTicketPrice);
pnlAdultTicketPrice.add(txtAdultTicketPrice);
pnlChildTicketPrice.add(lblChildTicketPrice);
pnlChildTicketPrice.add(txtChildTicketPrice);
pnlAdultTicketsSold.add(lblAdultTicketsSold);
pnlAdultTicketsSold.add(txtAdultTicketsSold);
pnlChildTicketsSold.add(lblChildTicketsSold);
pnlChildTicketsSold.add(txtChildTicketsSold);
pnlCalculate.add(btnCalculate);
// Adds all of the above panels to a main panel
pnlMain.add(pnlAdultTicketPrice);
pnlMain.add(pnlChildTicketPrice);
pnlMain.add(pnlAdultTicketsSold);
pnlMain.add(pnlChildTicketsSold);
pnlMain.add(pnlCalculate);
}
private class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Creates object of Theater
Theater theater = new Theater();
// Sets the member variables of Theater to the user's input
theater.setAdultTicketPrice(Double.parseDouble(txtAdultTicketPrice.getText()));
theater.setChildTicketPrice(Double.parseDouble(txtChildTicketPrice.getText()));
theater.setAdultTicketsSold(Integer.parseInt(txtAdultTicketsSold.getText()));
theater.setChildTicketsSold(Integer.parseInt(txtChildTicketsSold.getText()));
// Creates DecimalFormat object for rounding
DecimalFormat dollar = new DecimalFormat("#.##");
// Display the charges.
JOptionPane.showMessageDialog(null, "Adult ticket gross: $" +
Double.valueOf(dollar.format(theater.getAdultGross())) + "\n" +
"Child ticket gross: $" + Double.valueOf(dollar.format(theater.getChildGross())) + "\n" +
"Adult ticket net: $" + Double.valueOf(dollar.format(theater.getAdultNet())) + "\n" +
"Child ticket net: $" + Double.valueOf(dollar.format(theater.getChildNet())) + "\n" +
"Total gross: $" + Double.valueOf(dollar.format(theater.getChildGross())) + "\n" +
"Total net: $" + Double.valueOf(dollar.format(theater.getTotalNet())));
}
}
public class Theater
{
private double PERCENTAGE_KEPT = 0.20;
private double adultTicketPrice, childTicketPrice;
private int adultTicketsSold, childTicketsSold;
public double getAdultGross()
{
return getAdultTicketPrice() * getAdultTicketsSold();
}
public double getAdultNet()
{
return PERCENTAGE_KEPT * getAdultGross();
}
public double getAdultTicketPrice()
{
return adultTicketPrice;
}
public int getAdultTicketsSold()
{
return adultTicketsSold;
}
public double getChildGross()
{
return getChildTicketPrice() * getChildTicketsSold();
}
public double getChildNet()
{
return PERCENTAGE_KEPT * getChildGross();
}
public double getChildTicketPrice()
{
return childTicketPrice;
}
public int getChildTicketsSold()
{
return childTicketsSold;
}
public double getTotalGross()
{
return getChildGross() + getAdultGross();
}
public double getTotalNet()
{
return getChildGross() + getChildNet();
}
public void setAdultTicketPrice(double adultTicketPrice)
{
this.adultTicketPrice = adultTicketPrice;
}
public void setAdultTicketsSold(int adultTicketsSold)
{
this.adultTicketsSold = adultTicketsSold;
}
public void setChildTicketPrice(double childTicketPrice)
{
this.childTicketPrice = childTicketPrice;
}
public void setChildTicketsSold(int childTicketsSold)
{
this.childTicketsSold = childTicketsSold;
}
}
}

Yes You can write your all classes in a single .java file, But you must have only one class public(if file name and class name same)
Example:
class A
{
}
class B
{
}
class C
{
}

I am assuming you are very beginner! Just copy paste all these contents in a single file TheaterDemo.java. And dont forget to remove all the public keyword in the beginning of class declaration.

One Java file can contain at most one top-level public class. That public top-level class can contain any number of public nested classes.
You can eliminate your compiler errors by any of the following approaches:
Moving the other classes into their own files. For example: FirstClass.java, SecondClass.java, and ThirdClass.java.
Nesting the classes whose name is not the file basename. For example:
public class FirstClass() {
public class SecondClass() {}
public class ThirdClass() {}
}
Removing the public qualifier from all but the one class whose name is the file basename. This approach has become less common after the introduction of nested classes in Java v1.1. For example, in file FirstClass.java, you could have:
public class FirstClass() {}
class SecondClass() {}
class ThirdClass() {}
From the Java Language Specification, section 7.6: Top Level Type Declarations:
If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
The type is referred to by code in other compilation units of the package in which the type is declared.
The type is declared public (and therefore is potentially accessible from code in other packages).

Just remove public from all other class definition and paste the code into TheaterDemo.java file
public class TheaterDemo
{
public static void main(String[] args)
{
TheaterWindow theaterWindow = new TheaterWindow();
}
}
//Here class code after removing public
// Here another class code

I see you have already done that kind of implementation. Please refer
private class CalcButtonListener implements ActionListener
in your TheaterWindow class.
By doing this, you are creating inner classes i.e. CalcButtonListener is an inner class of TheaterWindow class. Some concept you can extend to other classes.

There is no restriction on the number of class files in a java file.
But we can’t have more than one public class per source code file. Also the name of the file must match the name of the public class. Like, a class declared as public class Dog { } must be in a source code file named Dog.java.
And files with no public classes can have a name that does not match any of the classes in the file.

Related

Java : variable reuse

I'm writing a simple Java program.
First, the program asks user to input some info like name and id of the student and uses radio button for asking whether the student is present or absent. After finishing the inputs, then program validate whether predefined student names and inputs are match or not. And check id number again and spit out if input is over 4. Lastly check radio button is true or false. If one of the above two rules get error then program will quit without executing next method.
I have three .java files. One for UI. One for validation and one for storing data.
UI.java
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class UI extends JFrame {
JTextField name = new JTextField("Name", 10);
JTextField id = new JTextField("Id", 10);
JRadioButton attendance = new JRadioButton("Present");
JButton JB = new JButton("Check");
public UI() {
super("Test");
JPanel JP = new JPanel();
JP.add(name);
JP.add(id);
JP.add(attendance);
JP.add(JB);
add(JP);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void buttonAction(){
UI UIbutton = new UI();
UIbutton.JB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == UIbutton.JB) {
String nameInput = UIbutton.name.getText();
int idInt = Integer.parseInt(UIbutton.id.getText());
boolean attInput = UIbutton.attendance.isSelected();
Validate.nameChk(nameInput);
Validate.idChk(idInt);
Validate.attChk(attInput);
Student studentObj = new Student(UIbutton.name.getText(), idInt, UIbutton.attendance.isSelected());
System.out.println(studentObj.name + "'s ID number is : " + studentObj.id + ".");
System.out.println(studentObj.name + " is present: " + studentObj.attendance);
System.exit(0);
}}});
}
public static void main(String[] args) {
buttonAction();
}
}
Validate.java
public class Validate {
public static void nameChk (String nameInput) {
String n1 = "Matthew";
String n2 = "John";
String n3 = "Mark";
String n4 = "Luke";
if ((nameInput.equalsIgnoreCase(n1))||
(nameInput.equalsIgnoreCase(n2))||
(nameInput.equalsIgnoreCase(n3))||
(nameInput.equalsIgnoreCase(n4))){
System.out.println("Your data is okay.");
}
else {
System.out.println("Error, wrong student name.");
System.exit(0);
}
}
public static void idChk (int idInt) {
if (idInt > 4) {
System.out.println("Your id is not correct.");
System.exit(0);
}
else {
System.out.println("Your id is correct.");
}
}
public static void attChk (boolean attInput) {
if (attInput) {
System.out.println("The student is present.");
} else {
System.out.println("The student is absent.");
}
}
}
Student.java
public class Student {
String name;
int id;
boolean attendance;
Student(String name, int id, boolean attendance) {
this.name = name;
this.id = id;
this.attendance = attendance;
}
}
What I want to know is how can I reuse output of that actionlister method somewhere else. Let say I would create foo.java class and use that studentObj variable to give grades like
System.out.println(studentObj.name+"has B+.");
Sort of.
How can I do that? How to turn that variable into global?
This can be achieved in different ways.
Quite simple, but not a good practice would be to create a Singleton. It would contain Students objects and you'll be able to access them from anywhere. Here is example with eager singleton, but you can implement much better versions (check about singleton implementations i.e. here https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples)
public class StudentsSingleton {
private Map<Integer, Student> students = new HashMap<>();
public Student getStudent(int id) { return students.get(id);}
public void addStudent(Student s) { students.put(s.id, s);}
private static final StudentsSingleton instance = new StudentsSingleton();
//private constructor to avoid client applications to use constructor
private StudentsSingleton(){}
public static StudentsSingleton getInstance(){
return instance;
}
}
In that case, you can access it from anywhere by getting the instance :
StudentsSingleton.getInstance().getStudent(id);
A much better solution and a good practice would be to use some Dependency Injection framework i.e. Spring. In that case, you would create a Bean and inject it whenever it is needed to use.

Calling a Method That Takes a Parameter Within ActionListener

I've encountered a problem while trying to call a method within a class that implements actionListener. The method being called, DataCompiler, needs to use the integer wordCountWhole, which is returned in the wordCount class. The problem is that I can't pass the required parameter to the actionListener method.
import javax.swing.*;
import java.awt.*;
import java.awt.List;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.text.BreakIterator;
import java.util.*;
import java.util.stream.IntStream;
public class GUI extends JFrame {
public JTextArea textInput;
public JButton dataButton;
public String str;
public GUI() {
super("Text Miner");
pack();
setLayout(null);
dataButton = new JButton("View Data"); //Button to take user to data table
dataButton.setSize(new Dimension(120, 50));
dataButton.setLocation(5, 5);
Handler event = new Handler(); //Adds an action listener to each button
dataButton.addActionListener(event);
add(dataButton);
public class wordCount {
public int miner() {
//This returns an integer called wordCountWhole
}
}
public class Handler implements Action { //All the possible actions for when an action is observed
public void action(ActionEvent event, int wordCountWhole) {
if (event.getSource() == graphButton) {
Graphs g = new Graphs();
g.Graphs();
} else if (event.getSource() == dataButton) {
DataCompiler dc = new DataCompiler();
dc.Data(wordCountWhole);
} else if (event.getSource() == enterButton) {
wordCount wc = new wordCount();
sentenceCount sc = new sentenceCount();
wc.miner();
sc.miner();
}
}
}
}
And here's the code for the DataCompiler class:
public class DataCompiler{
public void Data(int wordCountWhole){
int m = wordCountWhole;
System.out.println(m);
}
}
You don't add the parameter there because you've invalidated the contract of the interface.
Use a constructor* (see note below, first)
public class Handler implements Action{ //All the possible actions for when an action is observed
private int wordCountWhole;
public Handler(int number) { this.wordCountWhole = number; }
#Override
public void actionPerformed(ActionEvent event) {
Although, it isn't entirely clear why you need that number. Your DataCompiler.Data method just prints the number passed into it, and that variable seemingly comes from nowhere in your code because it is not passed to the ActionListener.
* You should instead use Integer.parseInt(textInput.getText().trim()) inside Handler class / the listener code and not use a constructor. Otherwise, you'd always get the number value when you add the Handler, which would be an empty string and throw an error because the text area has no number in it.
Additionally, wc.miner(); returns a value, but calling it on its own without assigning it to a number just throws away that return value.

non-static JLabel cannot be referenced from static context while moving console println into GUI

Whatever I try to modify there's always a problem and the program won't run.
The thing is that my program works fine, when it's launched in the console, everything is ok, but when I try to make a GUI, and get text from console in the window, variables doesn't seem to work as they were.
The program is very simple, it has three packages like this:
//class SklepZoologiczny in package sklepzoologiczny
package sklepzoologiczny;
import javax.swing.JFrame;
import zwierzeta.*;
import magazyn.*;
public class SklepZoologiczny {
public static void main(String[] args) {
GUI GUI = new GUI();
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.pack();
GUI.setSize(300, 500);
GUI.setVisible(true);
GUI.setTitle("Appka Zaliczeniowa - Sklep Zoologiczny");
GUI.setResizable(false);
GUI.setLocationRelativeTo(null);
}
}
//class GUI in package sklepzoologiczny
package sklepzoologiczny;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import magazyn.*;
import zwierzeta.*;
public class GUI extends JFrame {
public JLabel l_imie, l_gatunek, l_rasa;
public JButton b_dodaj, b_usun, b_lista;
public JTextField tf_imie, tf_gatunek, tf_rasa;
public String imie, gatunek, rasa;
public ArrayList lista_psow, lista_kotow;
public String pies, kot, gatunek_zwierza;
public String imie_psa, rasa_psa;
public String imie_kota, rasa_kota;
public GUI() {
setLayout(new FlowLayout());
b_dodaj = new JButton("Uruchom Program");
add(b_dodaj);
l_imie = new JLabel("Text from console to GUI should go here");
add(l_imie);
event dodanie = new event();
b_dodaj.addActionListener(dodanie);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent dodanie) {
magazyn magazyn1 = new magazyn();
magazyn1.kasa = 0;
pies pies1 = new pies();
kot kot1 = new kot();
krolik krolik1 = new krolik();
pies1.ustawImie("Max");
kot1.ustawImie("Nuta");
krolik1.ustawImie("Filip");
pies1.ustawCene(200);
kot1.ustawCene(100);
krolik1.ustawCene(50);
pies1.ustawRase("Jamnik");
kot1.ustawRase("Perski");
krolik1.ustawRase("Mini_Lop");
pies1.ustawGatunek("pies");
kot1.ustawGatunek("kot");
krolik1.ustawGatunek("krolik");
System.out.println("Operacje Zakupu Zwierzat");
System.out.println("---");
magazyn1.dodajZwierza(pies1);
magazyn1.dodajZwierza(kot1);
magazyn1.dodajZwierza(krolik1);
magazyn1.StanSklepu();
System.out.println("Transkacje");
System.out.println("---");
magazyn1.sprzedajZwierza("Nuta");
magazyn1.StanSklepu();
}
}
}
//class magazyn in package magazyn
package magazyn;
import java.util.ArrayList;
import zwierzeta.*;
public class magazyn {
public float kasa;
ArrayList <zwierzeta> lista = new ArrayList(20);
public void dodajZwierza(zwierzeta i){
lista.add(i);
sklepzoologiczny.GUI.l_rasa.setText("Do sklepu dodano zwierza o imieniu: " + i.wezImie());
}
public void sprzedajZwierza(String i){
for(int j=0; j<lista.size(); j++){
if(lista.get(j).wezImie() == i){
kasa = kasa + lista.get(j).wezCene();
lista.remove(j);
System.out.println("Sprzedano: " + i);
}
}
}
public void StanSklepu(){
System.out.println("Aktualny stan sklepu:");
for(int i=0; i<lista.size(); i++){
System.out.println(lista.get(i).wezImie()+", " +lista.get(i).wezGatunek()+", " + lista.get(i).wezRase() + ", cena: " + lista.get(i).wezCene());
}
System.out.println("Stan kasy \t\t\t" + kasa);
}
}
//class zwierzeta in package zwierzeta
package zwierzeta;
public abstract class zwierzeta {
String imie, gatunek, rasa;
float cena;
/* public void checkProduct() throws ProductException{
if(isDamaged == true){
ProductException damaged = new ProductException();
damaged.setErrorMessage("Product is damaged:");
throw damaged;
}
}*/
public void ustawImie(String i){
imie = i;
}
public String wezImie(){
return imie;
}
public void ustawGatunek(String i){
gatunek = i;
}
public String wezGatunek(){
return gatunek;
}
public void ustawRase(String i){
rasa = i;
}
public String wezRase(){
return rasa;
}
public void ustawCene(float i){
cena = i;
}
public float wezCene(){
return cena;
}
}
There are also three classes in package zwierzeta which only extends zwierzeta with no code in it.
So the thing is, whatever I try to put in the dodajZwierza in magazyn.java, there's always an error which says that I can't use non-static variable l_rasa to reference in a static context. I don't know how to fix this, I tried to make class as static in GUI but it just gets worse with more errors.
How can I get the text to appear in the window instead of a console?
First of all - you better avoid using members with names identical to type names:
GUI GUI = new GUI();
You - and the JVM - are more than likely to get confused by this, not knowing whether you are trying to access the class type or the class instance when you later run something like:
GUI.setVisible(true);
Second, if you want to let one class access a member of another class, it is much better to provide a getter that returns (a reference to ) that member, instead of defining the member as static and let the other classes access it directly.
You seem to conflate classes and instances: you want to create an instance of class GUI and then pass this instance around to be able to use the instance rather than the class.
In your main method, you create an instance of class GUI:
GUI GUI = new GUI();
The variable which refers to this instance you call GUI, the same as the class. This is a very bad idea. Java naming conventions dictate that variable names start with a non-capital letter, so you should write:
GUI gui = new GUI();
and change the rest of the main method accordingly.
Now, this instance gui is what you want to use. You have to pass it to the methods where you use it, and then write for example
gui.l_rasa.setText(...);
By the way, your code becomes more maintainable if you make the member variables of a class private, and add getter and setter methods to access them.
You are trying to access non static variable defined in GUI class as:
public JLabel l_imie, l_gatunek, l_rasa;
Here:
sklepzoologiczny.GUI.l_rasa.setText
I dont see its being initialised, but you could define it as static in GUI class like:
public static JLabel l_rasa;//initialize it may be and that would resolve your issue.

Setting JLabel Text at Runtime

I am pretty new to Java(about 2 weeks in), and I am trying to set the text of a JLabel. The only problem is I am doing calculations in another class and I don't know how to reference the Jlabel I have already created. Here are the two classes in question.
package fightsim;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FightSimPane extends JPanel {
FightManager FightManager = new FightManager();
/**
* Create the panel.
*/
public FightSimPane() {
setLayout(new MigLayout("", "[][][][][][][][][][]", "[][][][]"));
JLabel lblChampionleft = new JLabel("ChampionLeft");
add(lblChampionleft, "cell 1 3");
JButton btnGo = new JButton("Go");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
FightManager.startFight();
FightManager.runTheFight();
}
});
add(btnGo, "cell 5 3");
JLabel lblChampionright = new JLabel("ChampionRight");
add(lblChampionright, "cell 9 3");
}
public void setLeftChampionLabel(String s){
//not able to reference Jlabel lblChampionLeft here???
System.out.println("Setting Left Champion text to"+s);
}
public void setRightChampionLabel(String s){
//not able to reference Jlabel lblChampionRight here???
System.out.println("Setting Right Champion text to"+s);
}
}
And the class that is trying to set the Label.
package fightsim;
public class FightManager {
Champion LeftChamp = new Champion();
Champion RightChamp = new Champion();
public FightManager() {
}
Thread LeftChampThread = new Thread(LeftChamp);
Thread RightChampThread = new Thread(RightChamp);
;
public void startFight() {
LeftChamp.setHealth(200);
RightChamp.setHealth(300);
LeftChamp.setATKsp(1000);
RightChamp.setATKsp(1000);
LeftChamp.setAD(20);
RightChamp.setAD(20);
}
public void runTheFight() {
System.out.println("Starting Threads");
LeftChampThread.start();
RightChampThread.start();
while ((LeftChamp.getHealth() > 0) && (RightChamp.getHealth() > 0)) {
if (RightChamp.isReadyToAttack()) {
LeftChamp.setHealth(LeftChamp.getHealth() - RightChamp.getAD());
RightChamp.setNotReady();
System.out.println("Setting Left Champion test to"
+ Integer.toString(LeftChamp.getHealth()));
// This is where I'd like to update the left Jlabel in
// FightSimPane
}
if (LeftChamp.isReadyToAttack()) {
RightChamp
.setHealth(RightChamp.getHealth() - LeftChamp.getAD());
LeftChamp.setNotReady();
System.out.println("Setting Right Champion test to"
+ Integer.toString(RightChamp.getHealth()));
// This is where I'd like to update the right Jlabel in
// FightSimPane
}
}
}
}
So, the question...How do I let my FightManager Class access and change the JLabel in my FightSimPane Class/Gui. Thanks in advance, and sorry if this is a stupid question. I am terribly new to programming and I'm still trying to take it all in. With that said, any other advice would be great. Thanks!
Pass references around so that classes can communicate with each other, and not only that but with the correct active instance of the class of the other type. For instance, you could give FlightManager a FlightSimPane field:
class FightManager {
private FightSimPane fightSimPane;
// and fill it in the constructor:
public FightManager(FightSimPane fightSimPane) {
this.fightSimPane = fightSimPane;
}
Then you'll be dealing with the actual visualized FightSimPane GUI object.
Note that you'll have to take care to pass in the correct instance:
public class FightSimPane extends JPanel {
FightManager FightManager = new FightManager(this);
Then you can call the public methods of FightSimPane in the FightManager class:
public void runTheFight() {
System.out.println("Starting Threads");
LeftChampThread.start();
RightChampThread.start();
while ((LeftChamp.getHealth() > 0) && (RightChamp.getHealth() > 0)) {
if (RightChamp.isReadyToAttack()) {
LeftChamp.setHealth(LeftChamp.getHealth() - RightChamp.getAD());
RightChamp.setNotReady();
System.out.println("Setting Left Champion test to"
+ Integer.toString(LeftChamp.getHealth()));
// !!! **** added this *************
fightSimPane.setRightChampionLabel("Setting Left Champion test to"
+ Integer.toString(LeftChamp.getHealth()));
}
EDIT 1
I see another potentially serious and unrelated problem here:
while ((LeftChamp.getHealth() > 0) && (RightChamp.getHealth() > 0)) {
//.........
}
This code appears to be called on the main Swing thread, the EDT and it's nature (while (true)) suggests that it has a very good chance of locking up the EDT bringing your Swing GUI's graphics processing and updating and all user interactions to a screeching halt. You may need to use a Swing Timer for this or a background thread so as to leave the EDT free to do its necessary work.
Declare the reference variable of FightSimPane class in FightManager class and pass the reference of FightSimPane object via the constructor of FightManager.
In FightManager class,
public class FightManager {
Champion LeftChamp = new Champion();
Champion RightChamp = new Champion();
private FightSimPane pane;
public FightManager(FightSimPane pane) { this.pane=pane;}
public FightManager() {
}
....
Using "pane" reference variable you can access accessible elements of FightSimPane class.
Modify the FightSimPane code,
public class FightSimPane extends JPanel {
FightManager fightManager;
public FightSimPane() {
fightManager= new FightManager(this);
...
}

Have com.l2fprod.common.propertysheet.PropertySheetPanel To Display Composited Class

In order to have a Netbeans liked property inspector windows, I am making use of the following class to help me achieve this.
com.l2fprod.common.propertysheet.PropertySheetPanel
So far, it works fine for class with simple properties like String, int...
However, when come to slightly complicated class with composited relationship, things get more complicated.
For example, I have two animals (interface). One is Cat (Simple class with name and age) and Dog (Another simple class with name and age).
It takes no effort to display them through GUI windows.
However, when come to class with composited relationship. A Zoo, which can contains multiple animals (A class with array list to hold animals), I have problem to display all the animals properties within a single window.
The following is the screen shoot
(source: googlepages.com)
Partial source code is shown here
ObjectInspectorJFrame objectInspectorJFrame0 = new ObjectInspectorJFrame(cat);
objectInspectorJFrame0.setVisible(true);
objectInspectorJFrame0.setState(java.awt.Frame.NORMAL);
ObjectInspectorJFrame objectInspectorJFrame1 = new ObjectInspectorJFrame(dog);
objectInspectorJFrame1.setVisible(true);
objectInspectorJFrame1.setState(java.awt.Frame.NORMAL);
// I wish to see all "animals" and their properties in this windows. :(
// How?
ObjectInspectorJFrame objectInspectorJFrame2 = new ObjectInspectorJFrame(zoo);
objectInspectorJFrame2.setVisible(true);
objectInspectorJFrame2.setState(java.awt.Frame.NORMAL);
Complete source code can be downloaded from
http://yancheng.cheok.googlepages.com/sandbox.zip
I wish within "Zoo" windows, it can display all the properties for all animals.
PropertySheetPanel as is only populates its table reading the properties for a given Java Bean.
You need to extend PropertySheetPanel behaviour and populate the properties from a given Collection. Iterate your collection and use addProperty(Property) to populate the table.
You can also use instrospection or beanutils lib to discover the collection elements.
EDIT: Example added.
package com.stackoverflow.swing.PropertySheetPanel;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import com.l2fprod.common.propertysheet.DefaultProperty;
import com.l2fprod.common.propertysheet.PropertySheetPanel;
/**
* An example that creates a l2fprod PropertySheetPanel that displays any
* Collection.
*/
public class CollectionPropertySheet<C> extends PropertySheetPanel {
// Choose some bean. An animal as example.
static class Animal {
private String name;
private String family;
public Animal(String name, String family) {
this.name = name;
this.family = family;
}
#Override public String toString() {
return name + " " + family;
}
}
/**
* #param simpleModel The input collection as data model.
*/
public CollectionPropertySheet(Collection<C> simpleModel) {
super();
populateCollectionProperties(simpleModel);
}
private void populateCollectionProperties(Collection<C> collection) {
int index = 0;
for (C entry : collection) {
// Define property properties
DefaultProperty property = new DefaultProperty();
property.setDisplayName(entry.getClass().getSimpleName() + "[" + index++ +"]");
property.setValue(entry.toString());
// Set any other properties ...
// and add.
addProperty(property);
}
}
// Start me here!
public static void main(String[] args) {
// Inside EDT
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
JFrame frame = new JFrame("A simple example...");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CollectionPropertySheet<Animal>(getAnimals()));
frame.pack();
frame.setVisible(true);
}
private Collection<Animal> getAnimals() {
Collection<Animal> animals = new ArrayList<Animal>();
animals.add(new Animal("Lion", "Felidae"));
animals.add(new Animal("Duck", "Anatidae"));
animals.add(new Animal("Cat", "Felidae"));
return animals;
}
});
}
}

Categories