Java Class Constructor Error - java

I am building my own GUI that will display a list of Friend's objects in list form. The first problem I ran into is that when I run the code without a constructor, everything works fine. But when I create a constructor for my GUI class, the error message displayed:
load: GUIapp.class is not public or has no public constructor.
java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a member of class GUIapp with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
at java.lang.Class.newInstance0(Class.java:349)
at java.lang.Class.newInstance(Class.java:308)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:807)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:714)
at sun.applet.AppletPanel.run(AppletPanel.java:368)
at java.lang.Thread.run(Thread.java:680)
My Code:
public class GUIapp extends JApplet{
/*
* Attributes
*/
//** Friends Objects**//
private FriendsGroup a;
private ArrayList<friends> friendList;
//** PANEL **//
private JPanel outerPanel;
//** Button **//
private JButton button1;
/*
* Constructor for Getting all the friends set up
*/
private GUIapp(){
a = null; //initialize variable
try {
a = new FriendsGroup("friends.txt"); //import friend list
} catch (IOException e) {
System.out.println("Fail Import.");
}
friendList = a.getFriendsGroup(); //return an arrayList of Friends Object
}
/*
* Create Stuff
*/
public void createStuff() {
outerPanel = new JPanel(); //create outer panel
button1 = new JButton("Click Me");
outerPanel.add(button1,BorderLayout.SOUTH);
}
/*
* Initialize Stuff
*
*/
public void init(){
createStuff(); //initialize create stuff
this.add (outerPanel);
}
}
In the Above Code, if you take out the constructor, it seems to work perfectly. My Question is, what is wrong with the code? Why can't I seem to create a constructor to load in data first?
My Second Question is how would I go about create a panel whereby it displays a list of friends names? Theses names are imported and stored in the arraylist of friends Object called friendList stored in the constructor.
Thanks,

when you are defining a constructor by yourself
compiler will not create the default constructor
since your defined constructor is private
you will not have a public constructor
so simply create a public constructor
public GUIapp(){
// your code
}

because you define constructor private change it to;
public GUIapp(){
a = null; //initialize variable
try {
a = new FriendsGroup("friends.txt"); //import friend list
} catch (IOException e) {
System.out.println("Fail Import.");
}
friendList = a.getFriendsGroup(); //return an arrayList of Friends Object
}

The problem is this: private GUIapp(){. That means that your constructor is available only to that class. Usually constructors are public, although there do exist exceptions, example of which could be the Singleton Pattern.
Removing the constructor works because each class, by default has a parameterless constructor. Take a look at this tutorial for more information on access modifiers.
Alternatively, you could have a method like so in your GUIapp class:
public static GUIapp getInstance() { return new GUIapp(); }
and you call that from your main class, but I think that in this case, changing your constructor from private to public should be enough.
Regarding your second question, this tutorial should be of help.

You ened to change syour constructor to public and debug into:
a.getFriendsGroup();
Its not clear what this methode does, and i assume for some reason (maby the list from the file is empt) the methode tries to access a non assigned object which causes null reference exception, try to debug into the methode to see where this happends or post the code of the methode.

Related

Why is the program throwing an error "cannot find symbol" at setVisible in my showPanel method?

Why is the setVisible method throwing an error saying symbol not found in my showPanel method?
It does not make sense as I am referencing a JPanel stored in an ArrayList so it should be able to use setVisible.
public class mainFrame extends javax.swing.JFrame {
/**
* Creates new form mainFrame
*/
private ArrayList list;
public mainFrame() {
initComponents();
this.setSize(500,500);
int h=this.getHeight();
int w=this.getWidth();
homePanel homePnl = new homePanel();
this.add(homePnl);
homePnl.setLocation(0,0);
homePnl.setSize(w,h);
homePnl.setVisible(true);
DeploymentInfoPanel infoPanel = new DeploymentInfoPanel();
this.add(infoPanel);
infoPanel.setLocation(0,0);
infoPanel.setSize(w,h);
atomServerPanel atomPnl = new atomServerPanel();
this.add(atomPnl);
atomPnl.setLocation(0,0);
atomPnl.setSize(w,h);
autoDeploymentPanel autoPnl = new autoDeploymentPanel();
this.add(autoPnl);
autoPnl.setLocation(0,0);
autoPnl.setSize(w,h);
list = new ArrayList<>();
list.add(homePnl);
list.add(infoPanel);
list.add(atomPnl);
list.add(autoPnl);
this.pack();
}
public void showPanel(int panelNum){
list.get(1).setVisible(true);
}
private ArrayList list;
You didn't specify the type of Object that will be added to the ArrayList. So by default get() method will return an instance of Object. There is no setVisible(…) method for an Object
When you define the ArrayList you should be using:
private ArrayList<Component> list;
Now the compiler knows you are adding Component instances to the ArrayList.
In fact, the compiler will check to make sure you only add Component.
It will also get rid of the warning messages when you compile.
Also class names should start with an upper case character. Sometimes you do and sometimes you don't:
DeploymentInfoPanel infoPanel = new DeploymentInfoPanel();
...
atomServerPanel atomPnl = new atomServerPanel();
...
autoDeploymentPanel autoPnl = new autoDeploymentPanel();
Notice how the forum highlights properly named classes making the code easier to read?
Follow Java conventions and be consistent.
Finally, to display multiple panels in the same area of the frame you should be using a Card Layout.

How to load Java Swing MainJFrame with classes instance and data from ANOTHER Java Class?

Hello Guys I have my swing application running but I need to create an "initialization class" where I create instances with data to populate the program when I run it
If I create an instance with data in the MainJFrame constructor it's working perfectly but I need to populate the MainJFrame that will send it through all the panels from ANOTHER CLASS
Here is my MainJFrame Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UserInterface;
import Business.Initialization;
import Business.Inventory;
import Business.InventoryList;
import Business.Product;
import Business.ProductCatalog;
import Business.Store;
import Business.StoreDirectory;
import UserInterface.StarMarketAdmin.MarketAdminWorkArea;
import UserInterface.StoreAdmin.LoginStoreAdmin;
import java.awt.CardLayout;
import java.util.Collections;
import javax.swing.SwingUtilities;
public class MainJFrame extends javax.swing.JFrame {
/**
* Creates new form MainJFrame
*/
private StoreDirectory storeDirectory;
private InventoryList inventoryList;
private ProductCatalog productCatalog;
private Store store;
public MainJFrame() {
initComponents();
this.storeDirectory = new StoreDirectory();
this.inventoryList = new InventoryList();
this.productCatalog = new ProductCatalog();
this.store = new Store();
}
private void btnMarketAdminActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MarketAdminWorkArea panel = new MarketAdminWorkArea(userProcessContainer,storeDirectory,inventoryList,productCatalog,store);
userProcessContainer.add("MarketAdminWorkArea", panel);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}
private void btnStoreAdminActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
LoginStoreAdmin panel = new LoginStoreAdmin(userProcessContainer,storeDirectory,inventoryList,productCatalog);
userProcessContainer.add("LoginStoreAdmin", panel);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}
}
Now if I create an instance like:
Store s = storeDirectory.addStore();
s.setStoreName("Eddie's Market");
s.setStreet("Plainfield Pike");
s.setCity("Johnston");
s.setState("RI");
s.setCountry("USA");
in the MainJFrame it's working 100% but I need to create it in another class and call it in the MainJFrame to send it from there to all the other pannels.
How can I do this ?
create public functions to acces the private class from outside
not sure what you want exactly, but the options are endless
like
public void initStore(){
}
or just get it
public Store getStore(){
retturn store;
}
or even create and return it from there:
public Store storeFactory(){
// code here
return store;
}
or if you want another store and return it
public Store storeFactory(){
// code here to create a new store
return store2;
}
* NOT ADVISED but also an option: static *
you can also create a static one, even make it public, however public access is not the nicest way. Better keep it private and work with function as above to get it. In normally would not advice static usage like this... but assuming the MainFrame is the main program... in this case there might be an exception on the not to use static ....
private static Store store;
or
public static Store store;
than you can access it from everywhere by:
MainJFrame.store
* end static remark *
but maybe you just meant this:
public putStore(Store store){
this.store=store;
}
so you can create it in other class, and get it from other classes
in the other class to create it you migth even first get it (init it in the mainFrame with null:
private Store store=null;
in the other class:
Store store = mainframe.getStore();
// code to create it
or only create it if not yet created:
if (store==null){
// Only create if still null
// code to create it here
}
// and here use it, just created or not
Migth be a weird and 'know it all' like advice, but:
all of the above is basic java knowledge about public, private, static and so on.... might look in to some tutorials, to understand the basic things.
Java can be a pain in the... in case you do not understand it (memory leaks and so on...) so please be sure you know what you do.... (in case you want to use it professionaly)
In java there is a big difference in declaring it, and initialising it:
this is a declaration:
private Store store:
this is the init:
store = // something, even putting it to null is an init
and the combination of declare and init:
private Store store=null;
the last one you need before you can call it from other classes, because you actually will not get the object, but a pointer tot the object.
To have a pointer, you need tot init it, than init to null is enough.... so there is at least a pointer.
Understanding the way of pointers and how things are passed in java, will save some memory issues in bigger programs.
Inject this Store instance into the MainJFrame constructor.
The Store class will hold the data and you can access it through get methods.
Have you thought about that?

Getting values from another frame

So I'm having these classes
public class Init {
...
JFrame addStream = new AddStream();
addStream.setVisible(true);
addStream.setLocationRelativeTo(null);
addStream.getData(); //not working
}
public class AddStream extends javax.swing.JFrame {
private String nameData, urlData, qualityData;
/** Creates new form AddStream */
public AddStream() {
initComponents();
}
private void initComponents() {
...
}
private void addActionPerformed(java.awt.event.ActionEvent evt) {
nameData = name.getText();
urlData = url.getText();
qualityData = quality.getSelectedItem().toString();
}
public String[] getData() {
return new String[]{nameData, urlData, qualityData};
}
}
Note the classes arent complete, just snippets.
When the user clicks on the Add button(addActionPerformed) the values get saved to local variables in the AddStream class and get returned by getData().
The problem I'm having is with addStream.getData();, I get "cannot find symbol"
Is there a way to get that data from AddStream JFrame to Init class?
Your problem can be easily fixed by changing this line:
JFrame addStream = new AddStream();
To this:
AddStream addStream = new AddStream();
What's happening in your code is that you're trying to call a method on a JFrame that doesn't exist on a JFrame, it only exists in an AddStream. Even though your JFrame is-a AddStream in this case, the compiler forbids this unless you tell the compiler that it is-a AddStream. And you do that with the code I've shown you.
Another way is to cast it in your call. Imagine you were using your code from above, you could then do this on your last line:
((AddStream) addStream).getData();
In runtime when you do
JFrame addstream = new AddStream();
the object is viewed as a simple JFrame (using the JFrame part of class AddStream).
getData() is only available for AddStream type objects. You could trick the JVM into using the assigned type
if( addstream instanceof AddStream ){
(AddStream) addstream.getData();
} else {
//TODO
}
this is sometime useful when switching between different implementations of the same Interface. Note that the cast is only there to pass the compiler. The runtime checks instanceof only and go aheads if the condition evaluate to true.

Object has null values when subclass attempts to use it. Why?

I'm a newbie Java guy so I'm probably doing this entire thing completely wrong. I have to do this giant project for software engineering class. The code is about 2,000 lines long so this is skeleton code
public class BookRental extends JFrame{
public Client currentClient = new Client(); // creating client object
//rest of declared variables.
public class Client{ //Client class containing all get/set methods for each variable
private username;
private void setUsername(String u){
username = u;
}
public String getUsername(){
return username;
}
public class LoginPanel extends JPanel{} //Panel to show and receive login info.
public class RegisterPanel extends JPanel{} //Panel to register.
public class MenuPanel extends JPanel{ //Panel showing main menu.
//At this point currentClient will contain values
public ClientInfoPanel(){
initComponents();
}
private void initComponents(){
infoPanelUserName = new JLabel();
infoPanelFullName.setText("Currently logged in as: " + currentClient.getUsername());
}
private JLabel infoPanelUserName;
}
public class ClientInfoPanel extends JPanel{} //Panel to print currentClient info to screen using JLabel objects
private void ViewClientInfoButtonActionPerformed(event){ // Using button in Menu Panel to setVisibility of clientInfoPanel to (true)
//At this point there will be a value for currentClient
clientInfoPanel = new ClientInfoPanel();
this.add(clientInfoPanel);
menuPanel.setVisible(false);
clientInfoPanel.setVisible(true);
}
public BookRental(){initComponents();} //Constructor
private void initComponents(){} // Creates all panels and sets visibility off, besides login
public static void main(String args[]){
new BookRental().setVisible(true);
}
}
I already am pretty sure I am doing this COMPLETELY wrong, however my question is why can't I access currentClient inside of ClientInfoPanel? Say for this JLabel:
infoPanelUserName.setText("Currently logged in as: " + currentClient.getUsername());
The ClientInfoPanel recognizes currentClient exists and that the getUsername() method exists, however it prints:
"Currently logged in as: "
The code you showed looks fine, so the problem is somewhere else, or this code is not representative of what you have. Also, you ARE accessing currentClient successfully, unless you're getting a NullPointerException or catching it somewhere, then the .getUsername() call IS resolving. So the problem is actually with .getUsername(), somehow username is uninitialized when you call .getUsername();
As a test, can you call .setUsername() on currentClient right before you call .getUsername()? That should help us narrow down the problem, isolate it to either the class access or the variable being initialized.
Also, do you know how to debug with breakpoints? You mentioned you're new, so you might not know this is possible. If you're using Eclipse (or another good IDE) you can set breakpoints and run the program in DEBUG build, then the program will freeze when it hits the line you set a breakpoint on, and you can watch as the program moves line by line, and see the variables as they are updated by the program. Google java debug tutorial. :)
I agree (not sure whether I should add since someone else already answered, what is the etiquette?). I ran this fine and it showed me a panel with the user logged in as Me as set in the BookRental constructor:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class BookRental extends JFrame{
public Client currentClient = new Client(); // creating client object
//rest of declared variables.
public class Client{ //Client class containing all get/set methods for each variable
private String username;
private void setUsername(String u){
username = u;
}
public String getUsername(){
return username;
}
}
public class ClientInfoPanel extends JPanel{ //Panel showing main menu.
//At this point currentClient will contain values
public ClientInfoPanel(){
initComponents();
}
private void initComponents(){
infoPanelUserName = new JLabel();
infoPanelUserName.setText("Currently logged in as: " + currentClient.getUsername());
this.add(infoPanelUserName);
}
private JLabel infoPanelUserName;
}
public ClientInfoPanel clientInfoPanel;
//Constructor
public BookRental(){
currentClient.setUsername("Me");
initComponents();
}
private void initComponents(){
clientInfoPanel = new ClientInfoPanel();
this.add(clientInfoPanel);
clientInfoPanel.setVisible(true);
}
public static void main(String args[]){
new BookRental().setVisible(true);
}
}

I can read but Can't edit Main class contents

I'm using netbeans to program something with a user interface...
I hava a main class that named "NewJFrame.java"(A) and one more class
that named "NewClass.java"(B). Class A is extended to class B like this:
public class NewClass extends NewJFrame{
...
}
Contents of ClassA are public static like this:
public static javax.swing.JTextField TextBox1;
I also has a button in classA .So when I click the button, it will call a function
from the classB and that function needs to edit TextBox1's text...
Here is whats going on when I click the button:
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String Str1;
NewClass nc = new NewClass();
Str1=nc.call();
}
Here is the funcion in ClassB:
public String call()
{
String Str;
Str = TextBox1.getText();
TextBox1.setText(Str + "1"); //This part isn't work.
JOptionPane.showConfirmDialog(null,Str,"22222222",JOptionPane.PLAIN_MESSAGE);
return Str;
}
So I can read the text of TextBox1 and show it in a messagebox but cannot edit his text.
If I put this code in main class it works perfectly but in another class it doesn't work.
Can someone help me to reslove this problem?
(I'm using netbeans 6.9.1)
I Just Trying to use some another class to add my code because I dont want all the codes stay in same file this is not usefull... Come on someone needs to know how to do that you can't be writing all the codes in a *.java file right?
The problem you are facing has nothing to do with NetBeans IDE,
you will face the same problem with any IDE for this code.
One way of achieving this is by aggregating the NewJFrame class in the NewClass
instead of extending it:
Let me exlplain with some code:
public class NewClass {
private NewJFrame frame = null;
public NewClass(NewJFrame frame) {
this.frame = frame;
}
public String call()
{
String text;
text = frame.TextBox1.getText();
frame.TextBox1.setText(text + "1"); //This will work now.
JOptionPane.showConfirmDialog(null,text,"22222222",JOptionPane.PLAIN_MESSAGE);
return text;
}
}
Here we will receive a reference to the calling JFrame class and will use fields
defined in that class.
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String Str1;
NewClass nc = new NewClass(this); // see the parameter we are passing here
Str1=nc.call();
}
When we create an object of class NewClass we will pass the reference of the
currently calling NewJFrame object
This will work check it.
Now coming to why your code is not working. When NewClass is extending NewJFrame
and when you create a new object of NewClass class it contains a separate
copy of the NewJFrame which is different from the calling NewJFrame reference hence
the field is getting set in another JFrame and not what you wanted.
with regards
Tushar Joshi, Nagpur
AFAIK Netbeans prevents you from editing by hand GUI's and behaves diferrently depending on strange issues like the one you have... but it was months ago, I dont know if current version sucks that much yet.
I really don't understand why you are forcing yourself to use a new class for this? Even if you NEED to, I don't understand why NewClass extends NewJFrame since you are only creating an instance to call a method that has nothing to do with GUI.
I think creating NewClass isn't necessary. Writing all the code in one class isn't bad by itself. This really depends on MANY factors: how much is "all the code"? Does it make sense to separate responsibilities? Etc, etc...
So make the JTextField and JButton NOT static and NOT public, and simply do everything in there:
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String str = TextBox1.getText();
TextBox1.setText(str + "1"); //This part isn't work.
JOptionPane.showConfirmDialog(null,Str,"22222222",JOptionPane.PLAIN_MESSAGE);
}
P.S.: variable names are start in lowercase: String str, not String Str.
I Found a solution. I'm throwing the contents whereever I'll use. Here is an Example:
Main class:
private void formWindowOpened(WindowEvent evt) {
Tab1Codes tc1 = new Tab1Codes();
if(!tc1.LockAll(TabMenu1))
System.exit(1);
tc1.dispose();
}
Another class where I added some of my codes:
public boolean LockAll(javax.swing.JTabbedPane TabMenu){
try
{
TabMenu.setEnabledAt(1, false);
TabMenu.setEnabledAt(2, false);
TabMenu.setEnabledAt(3, false);
TabMenu.setEnabledAt(4, false);
}catch(Exception e)
{
JOptionPane.showConfirmDialog(null, "I can't Lock the tabs!",
"Locking tabs...",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
So, I can edit the contents in another class but it's little useless to send every content I want to read and edit.
If someone knows any short way please write here.

Categories