I have a few frames in my program.I need to access a data from everywhere how can I do this?
public class Main{
public int aData;
public static void main(String[] args){
Frame1 f = new Frame1();
}
}
public Frame1 extends JFrame{
// ....
public void foo(){
// I need aData in here.
}
}
Edit 1 : I have more than one data and when one of them is updated the data in main class should be updated.
Just pass it in the Frame1 constructor
public class Main{
public int aData;
public static void main(String[] args){
Frame1 f = new Frame1(aData);
}
}
public Frame1 extends JFrame{
private int data;
public Frame1(int data) {
this.data = data;
}
// ....
public void foo(){
// use data here
}
}
The most important question is why you think you need to do this. If you truly want something accessible from anywhere, you can just make it a public static member somewhere, but this is horrible design practice.
Generally, you want to make your design modular, so each thing depends only on what it actually needs. Then you can pass it an object that provides the data it needs, such as configuration settings. This lets you mock things out easily for unit testing and the like, and reduces the amount of code you need to rewrite when making changes to the program.
Try making Fram1 instance static
Related
I'm trying to create some system with inner class. My code can be summarized to something like this.
public abstract class A {
public abstract void doSomething();
}
public class B {
public final ArrayList<A> list=new ArrayList<A>();
public B(){
}
}
public class C {
private int i;
public C(B b){
b.list.add(new A(){
public void doSomething(){
i++;
}
});
b.list.add(new A(){
public void doSomething(){
System.out.println(i);
}
});
}
}
public static void main (String[] arg) {
B manager=new B();
new C(manager);
new C(manager);
new C(manager);
}
A is abstract class that will be inherited as inner class (in my original code it is listener class), B is some kind of manager class that hold list of As, and C hold data it's data should be only modified or read by it's inner class and upon initialization it add A to the class B. Code itself works fine. But problem is as there will be various kinds of C something like C2, C3 that does different thing and this leads to my code overwhelmed with thousands of unassigned object new C(manager); this make debugging extra hard and code looks really ugly. So it seems to me my approach in the first place was wrong but have no idea how to avoid this. So how should I change my approach to not have thousands of unassigned objects?
My suggestion is: try not to use constructors to do operations that depend on state (i). Use static functions, and save the state in a separate class (we call it a “context”).
import java.util.ArrayList;
public class Demo {
// A
abstract static class InnerListener {
public abstract void onEvent();
}
// B
static class ListenerManager {
public final ArrayList<InnerListener> listeners = new ArrayList<InnerListener>();
}
static class SideEffectContext {
public int i = 0;
}
// C
static class ListenerUtil {
public static void setupListeners(ListenerManager manager, SideEffectContext context) {
manager.listeners.add(new InnerListener() {
public void onEvent() {
context.i++;
}
});
manager.listeners.add(new InnerListener() {
public void onEvent() {
System.out.println(context.i);
}
});
}
}
public static void main(String[] arg) {
var manager = new ListenerManager();
var ctxA = new SideEffectContext();
var ctxShared = new SideEffectContext();
ListenerUtil.setupListeners(manager, ctxA);
ListenerUtil.setupListeners(manager, ctxShared);
ListenerUtil.setupListeners(manager, ctxShared);
}
}
This seems really simple but I can't find a way to make this work in a program I'm making. I have two classes, and in one of them, I've created an array, that I want to access in another class.
This is the main class...
public class main {
public static void main(String[] args) {
boolean[] pixelValues;
pixelValues = [99];
}
}
Of course, I'm omitting a lot, but this is the code I'm having trouble with. There's a second class that goes a little like this...
public class pixelAssign {
public pixelAssign(posX, posY) {
main.pixelValues[ {some number} ] = {some value};
}
}
My problem is that I'm having trouble accessing the pixelValues array that I created in my main class from a function I made in the second bit of code. I've been getting an error in the second bit of code that say (1), says that variable can't be found, and (2), I'm missing an identifier (?). The code in this is a bit unfinished, but the function in the second bit would be called from the main class later.
Any help would be much appriciated!
Putting Paul's and SANM2009's answers together:
You should:
public class main {
static int[] pixelValues;
public static void main(String[] args) {
pixelValues = [99];
}
}
public class pixelAssign {
public pixelAssign(posX, posY) {
main.pixelValues[0] = 98;
}
}
That should work IF and only IF classes main and pixelAssign are in the same package! If not, pixelValues would not be visible.
If you want to hold with Java Good Practices:
First letter of classes are always Uppercase, so Main and PixelAssign
Often is a good practice to instante classes and use the objects. Otherwise you have to use static.
Set pixelValues as private or protected and create method:
public class Main {
private int[] pixelValues;
public Main() {
pixelValues = [99];
}
public void setPixelValue(int position, int value) {
pixelValues[position] = value;
}
public static void main(String[] args) {
Main main = new Main();
new PixelAssign(main);
}
}
public class PixelAssign {
public PixelAssign(Main main, posX, posY) {
main.setPixelValue(0, 98);
}
}
Why don't you create your function so that it accepts the array as a parameter. you can then send the array to classB from ClassA.
There seems to be another issue here.
pixelValues is meant to be an array of Boolean or some numbers (int)?
boolean[] pixelValues;
pixelValues = [99];
As for the function:
public pixelAssign(myArray, posX, posY) {
}
So when calling the function, use
pixelAssign(pixelValues, posX, posY)
Perhaps you have changed the code to make it more concise but it looks like you are simply declaring the array in the wrong scope. Could you change it to this;
public class main {
boolean[] pixelValues;
public static void main(String[] args) {
pixelValues = [99];
}
}
I'm having a Class and array of that class' objects and each object has its own values. Now I want to access all the details of that class from another class. Please help me solve this. I've to display the details of FirstClass' objects (say f[0] & f[1]) in SecondClass.
public class FirstClass{
int first,second,total;
public FirstClass(int first,int second) {
this.first=first;
this.second=second;
this.total=first+second;
}
}
public class SecondClass {
public void display() {
//Display all the details of FirstClass
}
}
public class MainClass {
public static void main(String args[]) {
FirstClass f[]=new FirstClass[2];
f[0]=new FirstClass(2,4);
f[1]=new FirstClass(6,4);
SecondClass sec = new SecondClass();
sec.display();
}
}
One way: by simply changing your display() method to something like:
public void display(FirstClass toDisplay) {
System.out.println(toDisplay.getFirst());
}
with:
public class FirstClass {
private int first;
public int getFirst() { return first };
The point is: you really do not want to directly expose fields of one class to other classes. Using a getter isn't so much better, but at least it gives you control about the fact that a "read access" took place.
I would like to access one variable that is a part of my GUI class. Should I instantiate my GUI class outside of that GUI class? Right now it is instantiated inside of main which I believe makes it inaccessible for me.
So is the best way to access variables in this class to instantiate this object in a different class and in that class create getters and setters for it?
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
new NormalDistributionUI().setVisible(true);
}
}
Should it be like e.g.
public class Main {
static NormalDistributionUI ndUI;
public NormalDistributionUI getndUI() {
return ndUI;
}
public static void main(String args[]){
ndUI = new NormalDistributionUI();
}
}
EDIT: a different idea
public class NormalDistributionUI extends JFrame {
static NormalDistributionUI ndUI;
public static void main(String args[]) {
ndUI = new NormalDistributionUI()
ndUI.setVisible(true);
}
}
Does that make more sense than creating a separate class?
It depends on what you want. The second alternative would work as well, assuming that you called the method setVisible somewhere else.
The difference between the two of them is that in the second case the GUI object will be named and, hence, accessible afterwards. In the first case, it is anonymous.
You don't need a whole separate class. The first one is fine. If you want to manipulate the NormalDistributionUI object, you can use a local variable.
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
NormalDistributionUI ndUI = new NormalDistributionUI();
ndUI.setSomeProperty(foobar);
ndUI.setVisible(true);
}
}
I have a public static class within another public class as follows:
public class Foo<A> {
public static class Bar<A>{
A firstBar;
Bar(A setBar){
this.firstBar=setBar;
}
}
public final Bar<A> instanceBar;
public Foo(A actualValue) {
instanceBar = new Bar<A>(actualValue);
}
public Bar<A> getBar() {
return instanceBar;
}
My objective is to access instanceBar's state from a separate class file without a get method and without changing the visibility of firstBar. How do I accomplish this?
For example, the following says not visible.
public class RetrieveFirstBar {
public static void main(String[] args) {
Foo z = new Foo(5l);
Foo.Bar<Long> z2 = z.getBar();
long k = z2.firstBar; //not visible!
}
}
I guess you mean
class Foo<A>
Since you write "A firstBar;" you give package access to the variable:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If you have the RetrieveFirstBar in the same package you will not have visibility problems. But, if you want to access it from everywhere you should write
public A firstBar;