May be the Title isn't a specific one, I just don't know how to call it. I will explain you in detail
I have these classes:
public class ChannelComponent {
private String name;
private String mode; //(1P1C / XPXC / 1PXC)
private List<SourceProvidedPort> publishers = new ArrayList<SourceProvidedPort>();
private List<SinkRequiredPort> subscribers = new ArrayList<SinkRequiredPort>();
public ChannelComponent(String name, String mode) {
this.name = name;
this.mode = mode;
}
public boolean canISubscribe(SinkRequiredPort newPort) {
if ((mode.equals("1P1C") || mode.equals("1PXC")) && subscribers.size() < 1) {
subscribers.add(newPort);
return true;
} else if (mode.equals("XPXC")) {
subscribers.add(newPort);
return true;
}
return false;
}
public String getName() {
return name;
}
public String getMode() {
return mode;
}
public void printChannel() {
System.out.println("[" + name + "," + mode + "]" + "\n");
}
}
TestCentralRegistry
public class TestCentralRegistry {
private List<ChannelComponent> channels = new ArrayList<ChannelComponent>();
public void addChannelComponent(ChannelComponent c) {
channels.add(c);
}
public static void main(String... args) {
TestCentralRegistry demo = new TestCentralRegistry();
demo.addChannelComponent(new ChannelComponent("channel1", "1P1C"));
demo.addChannelComponent(new ChannelComponent("channel2", "XPXC"));
}
}
In the TestCentralRegistry class I created 2 channelComponents, these channels I would like to compare their mode value in the method canISubscribe (located in the ChannelComponent class). But how come, I could retrieve the values created in the TestCentralRegistry to read them in the ChannelComponent class?
what am I missing?
Because, from another class TestChannel I'm going to have a ChannelComponent reference, invoke the method canISubscribe
public class TestChannel {
ChannelComponent channelComponent;
public void callSubscribe(SinkRequiredPort newPort){
channelComponent.canISubscribe(newPort);
}
public static void main(String... args) {
TestChannel testChannel = new TestChannel();
SinkRequiredPort sinkPort = new SinkRequiredPort();
sinkPort.setWantsUse("channel1");
testChannel.callSubscribe(sinkPort);
}
}
And I need to compare the values, created in the TestCentralRegistry and TestChannel to see if there is a matching. I know that I still need to add some lines like getting the value from the newPort.getWantsUse(); and compare it with the channelComponent name ... but still I need the value created in the TestCentralRegistry
I hope my question is clear
Any suggestions?
Thank you in advance
Try holding a reference to TestCentralRegistry in ChannelComponent.
public class ChannelComponent {
private String name;
private String mode; //(1P1C / XPXC / 1PXC)
private List<SourceProvidedPort> publishers = new ArrayList<SourceProvidedPort>();
private List<SinkRequiredPort> subscribers = new ArrayList<SinkRequiredPort>();
private TestCentralRegistry testCentralRegistry;
public ChannelComponent(String name, String mode) {
this.name = name;
this.mode = mode;
}
public void registerTestCentralRegistry( TestCentralRegistry testCentralRegistry) {
this.testCentralRegistry = testCentralRegistry;
}
}
Register your TestCentralRegistry as shown below:
public class TestCentralRegistry {
private List<ChannelComponent> channels = new ArrayList<ChannelComponent>();
public void addChannelComponent(ChannelComponent c) {
channels.add(c);
}
public static void main(String... args) {
TestCentralRegistry demo = new TestCentralRegistry();
ChannelComponent cc1 = new ChannelComponent("channel1", "1P1C");
cc1.registerTestCentralRegistry( demo);
ChannelComponent cc2 = new ChannelComponent("channel2", "XPXC");
cc2.registerTestCentralRegistry( demo);
demo.addChannelComponent( cc1);
demo.addChannelComponent( cc2);
}
}
Then, you can retrieve the values created in the TestCentralRegistry by calling testCentralRegistry.getX() from ChannelComponent.
Related
I have read quite a few pages of stackoverflow but I wasn't able to get my ArrayList to get copied unto another class. Here's the scenario, I'm building a quick book saver app, similar to what you would have in a library but simpler (for school).
I have my main library class (with the main) that has the swing set up for the main menu/options.
I have the book class with the constructor for new books as follows:
public class Livre {
private String titre;
private String soustitre;
private String auteur;
private String editeur;
private String collection;
private String isbn;
private long cup;
private double prixDeVenteSuggere;
private double prixVente;
private int nbPages;
private boolean disponible;
public Livre(String titre, String soustitre, String auteur, String editeur, String collection, String isbn, long cup, double prixDeVenteSuggere, double prixVente, int nbPages, boolean disponible){
this.titre = titre;
this.soustitre = soustitre;
this.auteur = auteur;
this.editeur = editeur;
this.collection = collection;
this.isbn = isbn;
this.cup = cup;
this.prixDeVenteSuggere = prixDeVenteSuggere;
this.prixVente = prixVente;
this.nbPages = nbPages;
disponible = true;
}
public Livre() {
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getSoustitre() {
return soustitre;
}
public void setSoustitre(String soustitre) {
this.soustitre = soustitre;
}
public String getAuteur() {
return auteur;
}
public void setAuteur(String auteur) {
this.auteur = auteur;
}
public String getEditeur() {
return editeur;
}
public void setEditeur(String editeur) {
this.editeur = editeur;
}
public String getCollection() {
return collection;
}
public void setCollection(String collection) {
this.collection = collection;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public long getCup() {
return cup;
}
public void setCup(long cup) {
this.cup = cup;
}
public double getPrixDeVenteSuggere() {
return prixDeVenteSuggere;
}
public void setPrixDeVenteSuggere(double prixDeVenteSuggere) {
this.prixDeVenteSuggere = prixDeVenteSuggere;
}
public double getPrixVente() {
return prixVente;
}
public void setPrixVente(double prixVente) {
this.prixVente = prixVente;
}
public int getNbPages() {
return nbPages;
}
public void setNbPages(int nbPages) {
this.nbPages = nbPages;
}
public boolean isDisponible() {
return disponible;
}
public void setDisponible(boolean disponible) {
this.disponible = disponible;
}
}
Option #1 on the Library class (built with WindowBuilder) has the "New" button which opens a second JFrame to input all the info in regards to the book.
in this JFrame class, I've added an actionListener on the confirm button to confirm the input on the JTextFields to be added as an object as follows:
public void confirmerLivre(){
l = new Livre(txtTitre.getText(), txtSousTitre.getText(), txtAuteur.getText(),
txtEditeur.getText(), txtCollection.getText(), txtISBN.getText(),
Long.parseLong(txtCodebar.getText()), Double.parseDouble(txtPrixMSRP.getText()),
Double.parseDouble(txtPrix.getText()), Integer.parseInt(txtPages.getText()), true);
confirmerLivre.add(l); /// confirmerLivre is defined as an ArrayList
}
What I can't wrap my head around is being able to take the ArrayList confirmerLivre from the 2nd JFrame class and push it unto my main JFrame class to be manipulated further with other options.
Any help will be greatly appreciated.
Thank you
Probably the quickest fix is to create/expose these methods in your main JFrame class:
getBookList()
setBookList()
When you create your popup JFrame, you need to pass an instance of your main JFrame class to it in its constructor:
public PopupFrame extends JFrame {
private MainFrame main;
public PopupFrame(MainFrame main) {
this.main = main;
}
}
Now that you have access to your main JFrame class from your popup, you can just go main.getBookList() to get the list (I'd recommend reading this question also)
If you create your ArrayList as a public variable in the second JFrame class (outside any of the methods) then it can be used in the first class such as:
SecondJFramesName.confirmerLivre()
In this code SecondJFramesName is the name of your second JFrame class. Now that your ArrayList is a public variable it can be accessed outside the class.
Note: your second JFrame's name is the one you use to create it in a way such as this:
JFrame SecondJFramesName = new JFrame("My title");
If you need any more specific details please comment!
Hopefully this helps!
Maybe observer pattern could help you:
public interface ConfirmerLivreMonitor{
void onConfirmerLivreChange(List<...> confirmerLivre);
}
then
//...
private ConfirmerLivreMonitor confirmerLivreMonitor;
public void setConfirmerLivreMonitor(ConfirmerLivreMonitor confirmerLivreMonitor ){
this.confirmerLivreMonitor = confirmerLivreMonitor
}
//....
public void confirmerLivre(){
l = new Livre(txtTitre.getText(), txtSousTitre.getText(), txtAuteur.getText(),
txtEditeur.getText(), txtCollection.getText(), txtISBN.getText(),
Long.parseLong(txtCodebar.getText()), Double.parseDouble(txtPrixMSRP.getText()),
Double.parseDouble(txtPrix.getText()), Integer.parseInt(txtPages.getText()), true);
confirmerLivre.add(l); /// confirmerLivre is defined as an ArrayList
if(confirmerLivreMonitor != null){ //notify confirmerLivre change
confirmerLivreMonitor.onConfirmerLivreChange(confirmerLivre);
}
}
make the Main JFrame implemnents ConfirmerLivreMonitor,so you can:
sencondJFrame.setConfirmerLivreMonitor(this);
or just pass a anonymous class:
sencondJFrame.setConfirmerLivreMonitor(new ConfirmerLivreMonitor(){
public void onConfirmerLivreChange(List<...> confirmerLivre){
//display in Main JFrame,maybe
}
});
once the confirmerLivre change, the main frame can display(or something else)
the first time,very cool
Here is what I have so far so as you can see I made a class for the powerup but I just keep getting stuck over and over again and ended up getting frustrated cause I couldn't figure it out myself.
public class Superhero {
private int heroStr;
public int powerUp;
private String name;
public Superhero(String name, int heroStr) {
this.name = name;
this.heroStr = heroStr;
System.out.println(name + " Strength is " + heroStr);
}
public Superhero(String name) {
this.name = name;
heroStr = 10;
System.out.println(name + " Strength is " + heroStr);
}
public int getStr() {
return heroStr;
}
public int powerUp(int powerUp) {
}
public static void main (String[] args) {
Superhero Gambit = new Superhero("Gambit");
Superhero Groot = new Superhero("Groot", 79);
}
}
Here you are:
public void powerUp(int powerUp){
//this.powerUp is the powerUp in your class, the powerUp without "this" is the powerUp given to the method
this.powerUp+=powerUp;
}
All you need now is to change your powerUp method:
public void powerUp(int powerUp) {
this.heroStr += powerUp;
}
and since you instantiated the superheroes, all you need is to call their methods, ex:
public static void main(String args[]){
SuperHero gambit = new SuperHero("Gambit",10);
gambit.powerUp(10);
System.out.println(gambit.getStr()); //should be 20
}
Also, as a side note:
the correct naming convention for variable names is:
Class object = new Class();
I have asked this question here. I will try to make this one more specific.
class Example {
public static void main(String[] args) {
A a = null;
load(a);
System.out.println(a.toString());
// outcome is null pointer exception
}
private static void load(A a) {
a = new A();
}
}
class A {
public void String toString() {
return "Hello, world!"
}
}
So, does it possible to update a reference in a method? For some reason I need to do this. The reasons can be seen at above linked page.
Yes, it's possible if you define the parameter as A[] i.e. load(A[] a) and then in the method you update the element at position 0 in that array i.e. a[0] = new A(). Otherwise, it's not possible as Java is pass by value. I often use this workaround.
EXAMPLE 1:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = new A("outer");
System.out.println(a[0].toString());
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
EXAMPLE 2:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = null; // not needed, it is null anyway
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
NOTE: In fact, instead of an A[] you can use any wrapper object (an object which contains in itself a reference to an A object). The A[] a is just one such example. In this case a[0] is that reference to an A object. I just think that using an A[] is the easiest (most straightforward) way of achieving this.
As already pointed by other java is pass-by-value.You need something like pointer in C with the object location address so that you can modify that particular address value.As an alternate to pointer you can use array.Example
class Example {
public static void main(String[] args) {
A[] aArray=new A[1];
load(aArray);
System.out.println(aArray[0].toString());
// outcome is Hello, world!
}
private static void load(A[] aArray2) {
aArray2[0] = new A();
}
}
class A {
public String toString() {
return "Hello, world!";
}
}
You could just have:
public static void main(String[] args) {
A a = load();
}
private static A load() {
return new A();
}
No you can't.
In java everything is passed as value not as reference.
I came out with this. Perfectly satisfied my need and looks nice.
class A {
private A reference;
private String name;
public A() {
reference = this;
}
public void setReference(A ref) {
reference = ref;
}
public void setName(String name) {
reference.name = name;
}
public String getName() {
return reference.name;
}
}
so i am trying to compile this code and i get : ERROR : variable Laptop might not have been initiated.
public class Computer{
String modelName;
String motherboard;
String systemType;
int ram;
int cpu
int hdd;
public static void main(String[] args){
Computer Laptop;
Laptop.modelName = "M610";
Laptop.motherboard = "MSI";
Laptop.systemType = "Linux";
Laptop.ram = 2048;
Laptop.hdd = 50;
Laptop.cpu = 1500;
System.out.println("Model name:"+Laptop.modelName);
System.out.println("Motherboard:"+Laptop.motherboard);
System.out.println("System type: "+Laptop.systemType);
System.out.println("RAM :"+Laptop.ram);
System.out.println("HDD:"+Laptop.hdd);
System.out.println("CPU :"+Laptop.cpu);
}
}
Thank you very much in advance !
You need to do what the message says: Initialize Laptop.
Replace:
Computer Laptop;
With:
Computer Laptop = new Computer();
The former declares a new variable which the latter initializes it.
Yup as have been said, you need to instantiate the class so you have to do
Computer laptop = new Computer(); // Note lower case laptop as this is how you should define variable names
What you have wrote will do, but have a look at this example. Its more of a "correct way" in java
public class Laptop {
private String modelName;
private String motherboard;
private String systemType;
private int ram;
private int cpu;
private int hdd;
public static void main(String[] args) {
Laptop laptop = new Laptop();
laptop.setModelName("M610");
laptop.setMotherboard("MSI");
laptop.setSystemType("Linux");
laptop.setRam(2048);
laptop.setCpu(50);
laptop.setHdd(1500);
laptop.printResult();
}
public void printResult() {
System.out.println("Model name:" + getModelName());
System.out.println("Motherboard:" +getModelName());
System.out.println("System type: "+ getSystemType());
System.out.println("RAM :" + getRam());
System.out.println("HDD :" + getHdd());
System.out.println("CPU :" + getCpu());
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public String getMotherboard() {
return motherboard;
}
public void setMotherboard(String motherboard) {
this.motherboard = motherboard;
}
public String getSystemType() {
return systemType;
}
public void setSystemType(String systemType) {
this.systemType = systemType;
}
public int getRam() {
return ram;
}
public void setRam(int ram) {
this.ram = ram;
}
public int getCpu() {
return cpu;
}
public void setCpu(int cpu) {
this.cpu = cpu;
}
public int getHdd() {
return hdd;
}
public void setHdd(int hdd) {
this.hdd = hdd;
}
}
There are two ways to solve this problem.
Declare all your fields as static
public class Computer{
static String modelName;
static String motherboard;
.
.
.
In this case there is no need of initialization. Static members belong to a class rather than to a specific initialization or an instance of it.
Access them as Computer.your-filedname.
However if you want to declare an object.
You can just change this line
Computer Laptop;
to this
Computer Laptop = new Computer();
i.e. you initialize your object before assigning your fields' values in subsequent lines.
consider the below code:
public class Bid {
private double pe;
private List<ResChar> resourceList;
protected Map<Integer,Integer>scheduleOfSeller ;
public Map<Integer, Integer> getScheduleOfSeller() {
return scheduleOfSeller;
}
public void setScheduleOfSeller(Map<Integer, Integer> scheduleOfSeller) {
this.scheduleOfSeller = scheduleOfSeller;
}
private int bidId;
public int getBidId() {
return bidId;
}
public void setBidId(int bidId) {
this.bidId = bidId;
}
public double getPe() {
return pe;
}
public void setPe(double pe) {
this.pe = pe;
}
public List<ResChar> getResourceList() {
return resourceList;
}
public void setResourceList(List<ResChar> resourceList) {
this.resourceList = resourceList;
}
public Bid(int bidId,double pe, List<ResChar> resourceList){
setBidId(bidId);
setPe(pe);
setResourceList(resourceList);
this.scheduleOfSeller = new HashMap<Integer,Integer>();
}
}
I want to make a copy constructor of the bid like this :
public class BidCopy{
public Bid bid;
public BidCopy(Bid bidBuyer){
List<ResChar> resList = new LinkedList<ResChar>();
for (ResChar elt : bidBuyer.getResourceList()){
ResCharCopy eltCopy = new ResCharCopy(elt);
resList.add(eltCopy.elt);
}
this.bid = bidBuyer;
this.bid.setResourceList(resList);
}
}
The only solution that I know to make such copy is to proceed like follows :
public class BidCopy{
public Bid copy;
public BidCopy(Bid bid){
List<ResChar> resList = new LinkedList<ResChar>();
for (ResChar elt : bid.getResourceList()){
ResCharCopy eltCopy = new ResCharCopy(elt);
resList.add(eltCopy.elt);
}
this.copy = new Bid(bid.getBidId(), bid.getPe(), resList);
}
}
So I want to know if there is any other solution to make a copy of "Bid" Object more effectively ?
I would suggest making a copy constructor for your Bid object (and not a specific class for copying), a Bid is made out of its fields and not methods, like so:
public class Bid {
int ID;
String description;
Object bidStuff;
// ...as before
public Bid(Bid bid) {
this.ID = bid.ID;
this.description = bid.description;
this.bidStuff = bid.bidStuff;
}
public static void main(String[] args) {
List<Bid> original = new ArrayList<>();
// ..populate it
List<Bid> copy = new ArrayList<>(original.size());
for (Bid b : original) {
copy.add(new Bid(b));
}
}
}
You can even make the copy constructor protected or package-protected if you don't want anyone else to mess around with making multiple copies of bids.
There is not. Even though some collections have "copy constructors", these constructors will copy the elements' references, they will not create new elements for you.
You can however "optimize" the list creation itself by submitting the size of the initial list to the constructor:
List<X> newList = new LinkedList<X>(oldList.size());