Access another class function
Hey,
I am trying to access another class function. I have 2 Classes and my main menu features are in my Main Class and I want to call that function from my Level Class
What is a good idea to approach this, some how I need to import it in a way but I don't know how I could do that.
Thanks,
McbainGames11
Fixed it myself
Answer:
public static var instance:Main;
public function Main()
instance = this;
And I called a function from Main Class in my Level Class using:
Main.instance.function();
Similar Messages
-
How can I access another class in a MembershipRule's Expression
Hello,
I want to create an InstanceGroup using Module Microsoft.SystemCenter.GroupPopulator.
I need to collect all Logical Disks which contain an MS SQL DB Log File.
I would start as follows:
<DataSource ID="DS" TypeID="SC!Microsoft.SystemCenter.GroupPopulator">
<RuleId>$MPElement$</RuleId>
<GroupInstanceId>$Target/Id$</GroupInstanceId>
<MembershipRules>
<MembershipRule>
<MonitoringClass>$MPElement[Name="Windows!Microsoft.Windows.LogicalDisk"]$</MonitoringClass>
<RelationshipClass>$MPElement[Name="MSIL!Microsoft.SystemCenter.InstanceGroupContainsEntities"]$</RelationshipClass>
<Expression>
<And>
<!--
First Expression
-->
<Expression>
<SimpleExpression>
<ValueExpression>
<Property>$MPElement[Name="Windows!Microsoft.Windows.LogicalDevice"]/Name$</Property>
</ValueExpression>
<Operator>Equal</Operator>
<ValueExpression>
<!--
How can I access another class's properties ?
-->
<GenericProperty>$MPElement[Name="SQL!Microsoft.SQLServer.2008.DBLogFile"]/Drive$</GenericProperty>
</ValueExpression>
</SimpleExpression>
</Expression>
<Expression>
<SimpleExpression>
<ValueExpression>
<HostProperty>
<MonitoringClass>$MPElement[Name="Windows!Microsoft.Windows.Computer"]</MonitoringClass>
<Property>PrincipalName</Property>
</HostProperty>
</ValueExpression>
<Operator>Equal</Operator>
<ValueExpression>
<GenericProperty>$MPElement[Name="SQL!Microsoft.SQLServer.2008.DBLogFile"]/Drive$</GenericProperty>
</ValueExpression>
</SimpleExpression>
</Expression>
</And>
</Expression>
</MembershipRule>
</MembershipRules>
</DataSource>
In the first expression you "see" my question:
I want to compare the LogicalDisk's Name Property with the DB Log File's Drive property.
But how can I access the DB Log File's Drive property in this MembershipRule ?
Furthermore LogicalDisk and DB Log File must be hosted on the same Windows Computer.
Would be great if somebody could help.
Thanks
SebastianHi Niki,
thanks for the idea, but that will not work. $Target/Id$ refers always to the group to be discovered.
On last week end I was given following idea, hope it will work:
Step 1
Collect all the DB SQL Logfile Objects and write computername (PrincipalName?) and Driveletter into a textfile, line by line. Shouldn't be a problem, PowerShell is your friend.
Step 2
Read the file from Step 1, build discovery data for each disk drive as object of class "Logical Disk (Server)",
and then discover the containment-relationships from those Logical Drive(Server) Objects to the InstanceGroup.
Perhaps I must do it for the OS-Version related Disks, because I need the target classes of the Logical Disk Freespace monitors. Some more work. "Risks": I donot know the discovery algorithm for the Logical Disk(Server) Objects, but a "deep
dive" into the MPs should help.
Thanks to all, who have read.
I will inform you about progress and success
sebastian -
A have my "main" class (a JPanel) and the thing I want to do is simply to access another class' data and methods through my main class (That class also extending JPanel and is added together with the main class to a JFrame in a third class). The thing is i have this JTextPane that i wished to edit from my main class. Like:
//Main class
public class Main extends JPanel {
private class Listener implements KeyListener{
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == foo){
//Do like:
Log.appendLogText(bar);
}//My JTextPane handling class
public class Log extends JPanel {
private JTextPane logText;
public Log(){
logText = new JTextPane();
logText.setContentType("text/html");
public void appendLogText(String str){
String text = str;
Document textDoc = tempLogText.getDocument();
int end = textDoc.getLength();
try {
textDoc.insertString(end, text, logText.getLogicalStyle());
logText.setText(textDoc.getText(0, textDoc.getLength()));
} catch (BadLocationException e) {}
}This is just scraps of code, if there is a better way to do it please tell me, what i want is (again) simply one JPanel displaying something where you can edit the JTextPane in another JPanel (and class).public class Main extends JPanel {
private Log log;
public void setLog(Log log) {
this.log = log;
log.appendLogText(bar);
}It's up to the builder code that instantiates Main and Log classes to call:
tehMain.setLog(tehLog);For an extra schmear of abstraction, you can do this variant:
public interface ILog {
void appendLogText(String s);
public class Main extends JPanel {
private ILog log;
public void setLog(ILog log) {
this.log = log;
log.appendLogText(bar);
public class Log extends JPanel implements ILog {...}That way, you can pass Main other ILogs -- for testing Main, for example. -
Access Another Class' Property Value That is Defined in the faces-config?
I have a private property "dataTransferType" with public getter and setter in the DataFile class. The initial value of the "dataTransferType" is defined in the faces-config.xml file. I want to get the "initial value" of the "dataTransferType" in another class and the compiler does not like the way I access this property.
Here is the snippet of the DataFile class, which shows the declaration and the getter and setter for the property:
public class DataFile implements java.io.Serializable
private String dataTransferType;
public DataFile(){}
public DataFile( String aDataTransferType )
this.dataTransferType = aDataTransferType;
public String getDataTransferType()
return dataTransferType;
public void setDataTransferType( String dataTransferType )
this.dataTransferType = dataTransferType;
}Here is the way that the initial value of the "dataTransferPropery" is set in the faces-config.xml file:
<managed-bean>
<managed-bean-name>dataFile</managed-bean-name>
<managed-bean-class>propertyBeans.DataFile</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>dataTransferType</property-name>
<property-class>java.lang.String</property-class>
<value>importFile</value>
</managed-property>
</managed-bean>Now, in another class FileManagementBean, I first instantiate the DataFile class
private DataFile datafile;and then in the constructor of the FileManagementBean I tried to access the initial value of the property "dataTransferType":
this.recordItems = this.getRecordsList( datafile.dataTransferType );The compiler did not like it at all.
But, if I arbitrary introduced a String in the FileManagementBean:
String defaultSelectedDataTransferType = "importFile";
this.recordItems = this.getRecordsList( defaultSelectedDataTransferType );My code worked as I had expected without any problem.Thanks for all your attention.
The runtime error is rather strange:
>
javax.servlet.ServletException: javax.faces.FacesException: javax.faces.FacesException: Can't instantiate class: 'actions.DataManagementBean'.. class actions.DataManagementBean : java.lang.NullPointerException
The DataManagementBean is the class that accesses the property "dataTransferType" in the DataFile class. And the initial value of the "dataTransferType" is defined in the faces-config.xml file.
If I arbitrarily introduced a String value in the DataManagementBean:
String defaultSelectedDataTransferType = "importFile"and in the DataManagementBean's constructor, I use this statement:
this.recordItems = this.getRecordsList( defaultSelectedDataTransferType );Things worked as I had expected without problem. But, I think this is not an elegant way of coding it. Because there is a pre-defined value of dataTransferType in the faces-config.xml file, I should access it from there.
But, when I specify:
this.recordItems = this.getRecordsList( datafile.getDataTransferType() );The DataManagementBean cannot even be instantiated!
In my faces-config.xml file, I have:
<managed-bean>
<managed-bean-name>dataManagementBean</managed-bean-name>
<managed-bean-class>actions.DataManagementBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>datafile</property-name>
<property-class>propertyBeans.DataFile</property-class>
<value>#{dataFile}</value>
</managed-property>
</managed-bean>
<managed-bean>
<managed-bean-name>dataFile</managed-bean-name>
<managed-bean-class>propertyBeans.DataFile</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>dataTransferType</property-name>
<property-class>java.lang.String</property-class>
<value>importFile</value>
</managed-property>
</managed-bean>
...... -
Accessing document class function within timeline
Hi have a very simple question,
(Bear with me I'm still quite new to as3 and some of my terminology may not be solid)
I want to access a function that is within my document class when a movie clip on the timeline has played to a specific point (being the end).
I have already been able to call another function from the document class at the top/root level (it is called to initialize all clips and buttons when you click on the "enter" button on the splash screen.
Problem is that I cannot call another function (in the document class) from a movie clip within a movie clip on the timeline. Is there an easy way to do this? I have considered writing a separate class for the movie clip and then adding it onto the movie clip (using the property panel). I don't really want to do it this way because I am already using a base class on that movie clip and 3 others that use a set of generic functions.>>I want to access a function that is within my document class when a movie clip on the timeline has played to a specific point (being the end).
Your document class should add a listener to the clip and the clip should dispatch an event when it's complete. You could dispatch your own event or use one of Flash's like Event.COMPLETE. Something like:
in clip
dispatchEvent(new Event(Event.COMPLETE));
and in your doc class
clipOnTimeline.addEventListener(Event.COMPLETE, classMethod);
>>I have already been able to call another function from the document class at the top/root level (it is called to initialize all clips and buttons when you click on the "enter" button on the splash screen.
You really should avoid mixing timeline and document class code. Better would be for your doc class to add a listener to the button and call a method within the class when it's clicked. -
How to call another class function in SharePoint?
Facing 'ConvertViewToHtml' does not exit in current context. Here is my code:
namespace ChangeControl3_Nov
class eGA_Utility
public static void SendmailwithTwo(string To, string subject, string Body, string frommail, byte[] docFile, byte[] docFile1, string fileName1, string fileName3)
string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;
string smtpReplyTo = SPAdministrationWebApplication.Local.OutboundMailReplyToAddress;
MailMessage mailMessage = new MailMessage();
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(frommail, "Quality Management");
mailMessage.From = from;
mailMessage.To.Add(new MailAddress(To));
mailMessage.Subject = subject;
mailMessage.IsBodyHtml = true;
mailMessage.Priority = MailPriority.High;
mailMessage.Body = ConvertViewToHtml();
MemoryStream stream = new MemoryStream(docFile);
string fileName2 = fileName1;
Attachment attachment = new Attachment(stream, fileName2);
mailMessage.Attachments.Add(attachment);
MemoryStream stream1 = new MemoryStream(docFile1);
string fileName4 = fileName3;
Attachment attachment1 = new Attachment(stream1, fileName4);
mailMessage.Attachments.Add(attachment1);
SmtpClient smtpClient = new SmtpClient(smtpServer);
NetworkCredential oCredential = new NetworkCredential("", "");
try
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = oCredential;
smtpClient.Send(mailMessage);
catch (Exception)
I would like to call "ConvertViewToHtml()" from FormCode.cs in this line:
mailMessage.Body = ConvertViewToHtml();
namespace ChangeControl3_Nov
public partial class FormCode
public string ConvertViewToHtml()
try
byte[] sourceFile = null;
XPathNavigator root = MainDataSource.CreateNavigator();
string myViewName = this.CurrentView.ViewInfo.Name.Replace(" ", string.Empty);
string myViewXslFile = myViewName + ".xsl";
// Create the xsl transformer
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(ExtractFromPackage(myViewXslFile));
// Generate a temporary HTML file
string fileName = Guid.NewGuid().ToString() + ".htm";
string filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), fileName);
using (XmlWriter writer = XmlWriter.Create(filePath))
// Convert the XML to HTML
transform.Transform(root, writer);
writer.Close();
// Return the HTML as a string
sourceFile = File.ReadAllBytes(filePath);
return System.Text.Encoding.UTF8.GetString(sourceFile);
catch (Exception ex)
return "<html><body>Unable to convert the view to HTML <p>" + ex.Message + "</p></body></html>";
How to do this? Thanks in advance!Hi Sam,
According to your description, you might want to call a function from other class.
Before calling this function, it will require to initialize a FormCode object and then we can call the functions of the FormCode class.
You can take a look at the code snippet provided by tompsonn in this similar thread:
http://www.overclock.net/t/1411342/calling-a-function-from-another-form-c
More information about working with Partial Classes and Methods:
http://msdn.microsoft.com/en-us/library/wa80x488.aspx
Thanks -
Help... dont know what's the problem.. accessing another class
(im new to java =c)
well i have a file named accessfiles.java as my main page and i have another java file named try1.java
i can access try1.java from accessfiles.java using a simple case..... but how come i cant return to accessfiles.java?
is it with the string[]args?? do i have to erase it?
please help me =c
accessfiles.java
import java.io.*;
public class accessfiles{
public static void main(String[]args)throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nMAIN MENU");
System.out.println("[1] for Prelim MP1");
System.out.print("CHOICE: ");
switch(c)
case 1:
try m1=new try1();
m1.try();
break;
default: System.out.println("Invalid Input!");
break;
try1.java
import java.io.*;
public class try1 {
public static void try()throws Exception
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int x=0;
int y=0;
int r=0;
System.out.println("1st Pattern");
for (x=1;x<=5;x++)
System.out.println(" ");
r=x;
for (y=1;y<=r;y++)
System.out.print(y);
System.out.println(" ");
System.out.println(" ");
System.out.println("2nd Pattern");
for (x=5;x>=1;x--)
System.out.println(" ");
r=x;
for (y=1;y<=r;y++)
System.out.print(y);
accessfiles m2=new accessfiles();
m2.main();
break;
}For starters, you don't seem to understand the difference between a static and non-static method. Here is an example of how to call a method in a different class.
public class MainClass {
public static void main(String[] args) {
MainClass app = new MainClass();
app.go();
public void go() {
System.out.println("start of go");
another.method();
System.out.println("end of go");
private AnotherClass another = new AnotherClass();
public class AnotherClass {
public void method() {
System.out.println("method");
} -
Pair, and also accessing another class's vars
Hi, two things:
1) If some variable was set equal to Pair(obj1, obj2) what exactly does this mean? Is Pair some specialized type of 2-element array? Can you use Pair[0] to get the first element?
2) If another Object has, in its definition, a public variable, should I use Objectname.variable to get access to it if they don't provide a get() method?2) If another Object has, in its definition, a public
variable, should I use Objectname.variable to get
access to it if they don't provide a get() method?Yes, you access all instance members the same way: reference.member -
Error won't let me access another class(has got me tearing my hair off)
Alright peeps, so basically i have 2 buttons in the mainfraime class. The first button leads to the contestant's page and the second to the voters page. The first button works and directs the user to the PasswordDemo page, but to the hell of me i cant figure out why it refuses to recognize the "Profile" class that its supposed to go to when the user clicks the second button. It keeps on telling me that "The method Profile() is undefined for the type Mainframe". Please help.
Mainframe class:
//The applications first or the main frame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Mainframe extends JFrame {
private JButton myFirstButton;
private JButton mySecondButton;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
// Constructor for a new frame
public Mainframe() {
super("Welcome Page");
myFirstButton = new JButton("Contestant");
myFirstButton.setFont(new Font( "Arial", Font.BOLD, 18));
myFirstButton.setBackground(Color.red);
mySecondButton = new JButton("Voter");
mySecondButton.setFont(new Font( "Arial", Font.BOLD, 18));
mySecondButton.setBackground(Color.ORANGE);
Container c = getContentPane();
FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
c.setLayout(fl);
c.add (myFirstButton);
c.add (mySecondButton);
ButtonHandler handler = new ButtonHandler(); //creation of a new Object
myFirstButton.addActionListener(handler); // Attach/register handler to myFirstButton
mySecondButton.addActionListener(handler); //Attach/register handler to mySecondButton
setSize(400, 300);
show();
public static void main(String [] args) {
// Make frame
Mainframe f = new Mainframe();
f.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// This closes the window and terminates the
// Java Virtual Machine in the event that the
// Frame is closed by clicking on X.
System.out.println("Exit via windowClosing.");
System.exit(0);
} // end of main
// inner class for button event handling
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myFirstButton) {
PasswordDemo inputForm = new PasswordDemo();
//inputForm.setVisible(true);
try
PasswordDemo.createAndShowGUI();
inputForm.setVisible(false);
catch(Exception d)
// new PasswordDemo();
if (e.getSource() == mySecondButton) {
// Profile p = Profile();
// p.setVisible(true);
public void actionPerformed (ActionEvent e)
String cmd = e.getActionCommand();
if (mySecondButton.equals(cmd)) {
boolean success=true;
if(success)
Profile p = Profile();
p.setVisible(true);
// private void mySecondButtonActionPerformed(java.awt.event.ActionEvent evt)
// Profile p = Profile();
// p.setVisible(true);
} // end of outer class
}Profile class:
import java.awt.event.ActionListener;
import java.sql.*;
public class Profile extends javax.swing.JFrame {
public Profile() {
initComponents();
@SuppressWarnings("unchecked")
private void initComponents() {
titleLabel = new javax.swing.JLabel();
nameAccess = new javax.swing.JLabel();
ageAccess = new javax.swing.JLabel();
heightAccess = new javax.swing.JLabel();
weightAccess = new javax.swing.JLabel();
lastNameAccess = new javax.swing.JLabel();
descriptionAccess = new javax.swing.JLabel();
nameLabel = new javax.swing.JLabel();
lastNameLabel = new javax.swing.JLabel();
ageLabel = new javax.swing.JLabel();
heightLabel = new javax.swing.JLabel();
weightLabel = new javax.swing.JLabel();
descriptionLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
titleLabel.setFont(new java.awt.Font("Gungsuh", 1, 18)); // NOI18N
titleLabel.setText("\"User\"'s Profile");
nameAccess.setText("Name: ");
nameLabel.setText("");
lastNameAccess.setText("Last Name: ");
lastNameLabel.setText("");
ageAccess.setText("Age: ");
ageLabel.setText("");
heightAccess.setText("Height: ");
heightLabel.setText("");
weightAccess.setText("Weight: ");
weightLabel.setText("");
descriptionAccess.setText("Description: ");
descriptionLabel.setText("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(nameAccess)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nameLabel))
.addGroup(layout.createSequentialGroup()
.addComponent(lastNameAccess)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lastNameLabel))
.addGroup(layout.createSequentialGroup()
.addComponent(ageAccess)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ageLabel))
.addGroup(layout.createSequentialGroup()
.addComponent(heightAccess)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(heightLabel))
.addGroup(layout.createSequentialGroup()
.addComponent(weightAccess)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(weightLabel))
.addGroup(layout.createSequentialGroup()
.addComponent(descriptionAccess)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(descriptionLabel)))
.addContainerGap(151, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nameAccess)
.addComponent(nameLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lastNameAccess)
.addComponent(lastNameLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ageAccess)
.addComponent(ageLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(heightAccess)
.addComponent(heightLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(weightAccess)
.addComponent(weightLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(descriptionAccess)
.addComponent(descriptionLabel))
.addContainerGap(139, Short.MAX_VALUE))
pack();
}// </editor-fold>
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Profile().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JLabel ageAccess;
private javax.swing.JLabel ageLabel;
private javax.swing.JLabel descriptionAccess;
private javax.swing.JLabel descriptionLabel;
private javax.swing.JLabel heightAccess;
private javax.swing.JLabel heightLabel;
private javax.swing.JLabel lastNameAccess;
private javax.swing.JLabel lastNameLabel;
private javax.swing.JLabel nameAccess;
private javax.swing.JLabel nameLabel;
private javax.swing.JLabel titleLabel;
private javax.swing.JLabel weightAccess;
private javax.swing.JLabel weightLabel;
// End of variables declaration
}PasswordDemo class:
import javax.swing.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class PasswordDemo extends JPanel
implements ActionListener {
private static String OK = "ok";
private static String HELP = "help";
private static String Register = "Register";
private JFrame controllingFrame; //needed for dialogs
private JTextField username;
private JPasswordField passreg;
private JTextField usernamefield;
private JPasswordField passwordField;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private JTextField name;
private JTextField age;
private JTextField height;
private JTextField weight;
private javax.swing.JPanel jPanel1;
private void gothere() {
JFrame f = new JFrame("This is a test");
f.setSize(400, 300);
Container content = f.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
// content.add(new JButton("Button 1"));
//content.add(new JButton("Button 2"));
name = new JTextField("Please put your name here", 20);
name.setFont(new Font("Serif", Font.PLAIN, 14));
content.add(name);
age = new JTextField("Please put your age here", 20);
age.setFont(new Font("Serif", Font.PLAIN, 14));
content.add(age);
height = new JTextField("Please indicate your height here", 20);
height.setFont(new Font("Serif", Font.PLAIN, 14));
content.add(height);
weight = new JTextField("Please indicate your weight here", 20);
weight.setFont(new Font("Serif", Font.PLAIN, 14));
content.add(weight);
content.add(new JButton("Submit"));
f.setVisible(true);
public PasswordDemo(JFrame f) throws Exception {
//Use the default FlowLayout.
controllingFrame = f;
//Create everything.
usernamefield = new JTextField(10);
usernamefield.setActionCommand(OK);
usernamefield.addActionListener(this);
passwordField = new JPasswordField(10);
passwordField.setActionCommand(OK);
passwordField.addActionListener(this);
passreg = new JPasswordField(10);
passreg.setActionCommand(Register);
passreg.addActionListener(this);
username = new JTextField("This is a sentence", 20);
username.setActionCommand(Register);
username.addActionListener(this);
JLabel reg = new JLabel("If you are a new contestant please register: \n");
JLabel user = new JLabel("Username: \n");
user.setLabelFor(username);
JLabel pass = new JLabel("Password: \n");
user.setLabelFor(passreg);
JLabel label = new JLabel("Enter your username and password to log in: ");
label.setLabelFor(usernamefield);
label.setLabelFor(passwordField);
JComponent buttonPane = createButtonPanel();
//Lay out everything.
JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
textPane.add(reg);
textPane.add(user);
textPane.add(pass);
textPane.add(username);
textPane.add(passreg);
textPane.add(label);
textPane.add(usernamefield);
textPane.add(passwordField);
add(textPane);
add(buttonPane);
public PasswordDemo() {
// TODO Auto-generated constructor stub
protected JComponent createButtonPanel() {
JPanel p = new JPanel(new GridLayout(0,1));
JButton okButton = new JButton("OK");
JButton helpButton = new JButton("Help");
JButton regButton = new JButton("Register");
okButton.setActionCommand(OK);
helpButton.setActionCommand(HELP);
regButton.setActionCommand(Register);
okButton.addActionListener(this);
helpButton.addActionListener(this);
regButton.addActionListener(this);
p.add(okButton);
p.add(helpButton);
p.add(regButton);
return p;
public void actionPerformed (ActionEvent e)
String cmd = e.getActionCommand();
if (OK.equals(cmd)) { //Process the password.
boolean success=true; //Sign In
String Username="";
String Password="";
Username = this.usernamefield.getText();
Password = this.passwordField.getText();
try
success=check2(Username,Password);
catch(Exception d)
System.out.println("Got out");
if(success)
JOptionPane.showMessageDialog(controllingFrame, "Sign in Successful");
Form F = new Form(Username);
F.setVisible(true);
else
JOptionPane.showMessageDialog(controllingFrame, "Sign in was unsuccessful");
else if(HELP.equals(cmd)) { //The user has asked for help.
JOptionPane.showMessageDialog(controllingFrame,
"You can get the password by searching this example's\n"
+ "source code for the string \"correctPassword\".\n"
+ "Or look at the section How to Use Password Fields in\n"
+ "the components section of The Java Tutorial.");
else if(Register.equals(cmd)) { //*****************************************************
boolean success=true;
String Username="";
String Password="";
Username = this.username.getText();
Password = this.passreg.getText();
try
success=check(Username,Password);
catch(Exception d)
System.out.println("Something bad happened");
if(success)
JOptionPane.showMessageDialog(controllingFrame, "Registration successful");
else
JOptionPane.showMessageDialog(controllingFrame, "Registration was unsuccessful");
//Must be called from the event dispatch thread.
protected void resetFocus() {
passwordField.requestFocusInWindow();
static void createAndShowGUI() throws Exception {
//Create and set up the window.
JFrame frame = new JFrame("Registration Page");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
final PasswordDemo newContentPane = new PasswordDemo(frame);
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Make sure the focus goes to the right component
//whenever the frame is initially given the focus.
frame.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
newContentPane.resetFocus();
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String args[]) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
try{
createAndShowGUI();
catch(Exception e)
public void sendUserPass(String user,String pass)throws Exception
//Send request
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","");
System.out.println("connected :D:D:D:D");
PreparedStatement state = con.prepareStatement("Insert Into Contestant (USERNAME,PASSWORD) values ('"+user+"','"+pass+"')");
state.executeUpdate();
/*while(Result.next())
System.out.println(Result.getString(1)+"\t"+Result.getString(2));
//server should reply by updating database
public boolean check(String user,String pass)throws Exception
//Send request
Socket Sock = new Socket ("LocalHost",5000);
DataOutputStream toServer = new DataOutputStream(Sock.getOutputStream());
BufferedReader buff = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
String sentence="";
toServer.writeBytes("1\n");
sentence=buff.readLine();
System.out.println(sentence+"\n");
toServer.writeBytes(user+" "+pass+"\n");
String answer="";
answer = buff.readLine();
if(answer.equals("No"))
return false;
return true;
/*Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","");
System.out.println("connected :D:D:D:D");
PreparedStatement state = con.prepareStatement("Select Username From Contestant where '"+user+"'= username");
ResultSet Result = state.executeQuery();
if(!Result.next())
return true;*/
//server should reply by updating database
public boolean check2(String user,String pass)throws Exception
Socket Sock = new Socket("localhost",5000);
DataOutputStream toServer = new DataOutputStream (Sock.getOutputStream());
BufferedReader buff = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
toServer.writeBytes("2\n");
System.out.println("Well I sent the message");
String sentence = buff.readLine();
toServer.writeBytes(user+" "+pass+"\n");
System.out.println(sentence);
sentence=buff.readLine();
System.out.println(sentence+"\n");
if(sentence.equals("No"))
return false;
return true;
}Profile p = Profile();That says "call a method name 'Profile' that's defined in the current class."
Perhaps what you meant was:
Profile p = new Profile();which says "create a new instance of the Profile class, and invoke its no-arg constructor." -
Please Help!!! Problems access other classes methods
I am having a problem accessing another classes methods varibles. I have tried a number of ways but with no success. Here is my problem:
I have the main(), from there it's calls the class GetVar(), GetVar stores info in Class HousingForVar(), and finially, I have a class TryinToTalkToHousing() that I use to access HousingForVar()'s methods. I know I can use the keyword new but if I do that then it erases over the data I put in. Please can anyone help, this has been driving me nutz all day. Thank you in advance.
Roman03
***EACH CLASS IS A DIFFERENT FILE****
public class TestMain
public static void main( String args[] )
GetVar getVarible = new GetVar();
getVarible.heroF();
import java.util.Scanner;
public class GetVar
public void heroF()
String someEntered;
Scanner input = new Scanner( System.in);
System.out.println("Enter a string: ");
someEntered = input.next();
HousingForVar houseForData = new HousingForVar(someEntered);
System.out.printf("Retieved from Class GetVar, you entered: %s\n", houseForData.getCollectVar() );
import java.util.Scanner;
public class HousingForVar
private String getData;
public HousingForVar(String enterInfo)
getData = enterInfo;
public void setGetVar(String enterInfo)
getData = enterInfo;
public String getCollectVar()
return getData;
import java.util.Scanner;
public class TryinToTalkToHousing
public void someMeth()
String getInfoFromHousing;
System.out.printf("Started out at TryinToTalkToHousing Class\n Retieved from Class GetVar from %s\n",
houseForData.getCollectVar() );
\* I know this doesn't work, but if I make a new object of the class HousingForVar it's going to write over my input, so what do I do? I am still learning, Please help*\I don't use 1.5, so you'll have to convert it back, but see if you can follow the flow of this
import java.io.*;
class TestMain
GetVar getVarible;
public TestMain()
getVarible = new GetVar();
getVarible.heroF();
System.out.println("******");
new TryinToTalkToHousing(this).someMeth();
public static void main(String[] args){new TestMain();}
class GetVar
HousingForVar houseForData;
public void heroF()
try
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string: ");
String someEntered = br.readLine();
houseForData = new HousingForVar(someEntered);
System.out.println("Retieved from Class GetVar, you entered: "+houseForData.getCollectVar()+"\n");
catch(Exception e){e.printStackTrace();}
class HousingForVar
private String getData;
public HousingForVar(String enterInfo)
getData = enterInfo;
public void setGetVar(String enterInfo)
getData = enterInfo;
public String getCollectVar()
return getData;
class TryinToTalkToHousing
TestMain parent;
public TryinToTalkToHousing(TestMain t){parent = t;}
public void someMeth()
System.out.println("Started out at TryinToTalkToHousing Class\n"+
"Retieved from Class GetVar, you entered: "+parent.getVarible.houseForData.getCollectVar()+"\n");
} -
Calling a function from another class - help!
I realize that this is probably a basic thing for people who have been working with JavaFX for a while, but it is eluding me, and I have been working on it for over a week.
I need to call a function that is in another class. Here's the deal. In EntryDisplayController.java, there are 2 possible passwords that can be accepted - one will give full access to the car, the second will limit functions on the car. So when a password is entered and verified as to which one it is, I need to call a function in MainDisplayController.java to set a variable that will let the system know which password is being used - full or restricted.
So in MainDisplayController.java I have this snippet to see
public class MainDisplayController implements Initializable, ControlledScreen {
ScreensController myController;
public static char restrict;
* Initializes the controller class.
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
public void setRestriction(){
restrict = 0;
restrictLabel.setText("RESTRICTED");
public void clearRestriction(){
restrict = 1;
restrictLabel.setText("");
And in EntryScreenDisplay.java I have this snippet:
public class EntryDisplayController implements Initializable, ControlledScreen {
@FXML
private Label passwordLabel ;
static String password = new String();
static String pwd = new String("");
ScreensController myController;
private MainDisplayController controller2;
* Initializes the controller class.
@Override
public void initialize(URL url, ResourceBundle rb) {
setPW(pwd); // TODO
@FXML
private void goToMainDisplay(ActionEvent event){
if(password.equals ("123456")){
controller2.clearRestriction();
myController.setScreen(ScreensFramework.MainDisplayID);
pwd = "";
password = "";
setPW(pwd);
else if(password.equals ("123457")){
controller2.setRestriction();
myController.setScreen(ScreensFramework.MainDisplayID);
pwd = "";
password = "";
setPW(pwd);
else{
password = "";
pwd = "";
setPW(pwd);
When I enter the restricted (or full) password, I get a long list of errors, ending with
Caused by: java.lang.NullPointerException
at velocesdisplay.EntryDisplayController.goToMainDisplay(EntryDisplayController.java:60)
Line 60 is where "controller2.setRestriction(); is.
As always, thanks for any help.
Kind regards,
DavidYou never set the controller2 variable to anything, which is why you get a null pointer exception when you try to reference it.
public static variables (and even singletons) are rarely a good idea as they introduce global state (sometimes they can be, but usually not).
If a static recorder like this can only have a binary value, use a boolean, if it can have multiple values, use an enum.
Some of the data sharing solutions in dependency injection - Passing Parameters JavaFX FXML - Stack Overflow might be more appropriate.
I also created a small framework for roll based solutions in JavaFX which perhaps might be useful:
http://stackoverflow.com/questions/19666982/is-there-a-way-to-implement-a-property-like-rendered-on-javafx
https://gist.github.com/jewelsea/7229260
It was just something I hacked together, so it's not a fully polished solution and you probably don't need something quite so complex.
What you need is a model class shared between the components of your application. Dependency injection frameworks such as afterburner.fx can help achieve this in a fairly simple to use way.
If you don't want to go with a dependency injection framework, then you could use either a static singleton model class for your settings or pass the model class using the mechanism in defined in the passing parameters link I provided. For a model class example, see the ClickCounter class from this example. That example doesn't use FXML, but to put it together with the passing parameters solution, for your restriction model, you would have something like the following:
private class Restricted {
private final ReadOnlyBooleanWrapper restricted;
public Restricted(boolen isRestricted) {
restricted = new ReadOnlyBooleanWrapper(isRestricted);
public boolean isRestricted() {
return restricted.get();
public ReadOnlyBooleanProperty restrictedProperty() {
return restricted.getReadOnlyProperty();
Then in your EntryDisplayController you have:
@FXML
public void goToMainDisplay(ActionEvent event) {
// determine the restriction model as per your original code...
RestictionModel restrictionModel = new RestrictionModel(<appropriate value>);
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"mainDisplay.fxml"
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(
new Scene(
(Pane) loader.load()
MainDisplayController controller =
loader.<MainDisplayController>getController();
controller.initRestrictionModel(restrictionModel);
stage.show();
class MainDisplayController() {
@FXML private RestrictionModel restrictionModel;
@FXML private RestrictLabel restrictLabel;
public void initialize() {}
// naming convention (if the restriction model should only be set once per controller, call the method init, otherwise call it set).
public void initRestrictionModel(RestrictionModel restrictionModel) {
this.restrictionModel = restrictionModel;
// take some action based on the new restriction model, for example
restrictLabel.textProperty.bind(
restrictionModel.restrictedProperty().asString()
If you have a centralized controller for your navigation and instantiation of your FXML (like in this small FXML navigation framework), then you can handle the setting of restrictions on new screens centrally within the framework at the point where it loads up FXML or navigates to a screen (it seems like you might already have something like this with your ScreensController class).
If you do this kind of stuff a lot, then you would probably benefit from a move to a framework like afterburner. If it is just a few times within your application, then perhaps something like the above outline will give you enough guidance to implement a custom solution. -
Accessing a variable defined in one class from another class..
Greetings,
I've only been programming in as3 for a couple months, and so far I've written several compositional classes that take MovieClips as inputs to handle behaviors and interactions in a simple game I'm creating. One problem I keep coming upon is that I'd love to access the custom variables I define within one class from another class. In the game I'm creating, Main.as is my document class, from which I invoke a class called 'Level1.as' which invokes all the other classes I've written.
Below I've pasted my class 'DieLikeThePhishes'. For example, I would love to know the syntax for accessing the boolean variable 'phish1BeenHit' (line 31) from another class. I've tried the dot syntax you would use to access a MovieClip inside another MovieClip and it doesn't seem to be working for me. Any ideas would be appreciated. Thanks,
- Jeremy
package jab.enemy
import flash.display.MovieClip;
import flash.events.Event;
import jab.enemy.MissleDisappear;
public class DieLikeThePhishes
private var _clip2:MovieClip; // player
private var _clip3:MovieClip; //phish1
private var _clip4:MovieClip; //phish2
private var _clip5:MovieClip; //phish3
private var _clip6:MovieClip; //phish4
private var _clip10:MovieClip; // background
private var _clip11:MovieClip // missle1
private var _clip12:MovieClip // missle2
private var _clip13:MovieClip // missle3
private var _clip14:MovieClip // missle4
private var _clip15:MovieClip // missle5
private var _clip16:MovieClip // missle6
private var _clip17:MovieClip // missle7
private var _clip18:MovieClip // missle8
private var _clip19:MovieClip // missle9
private var _clip20:MovieClip // missle10
private var _clip21:MovieClip // missle11
private var _clip22:MovieClip // missle12
var ay1 = 0;var ay2 = 0;var ay3 = 0;var ay4 = 0;
var vy1 = 0;var vy2 = 0;var vy3 = 0;var vy4 = 0;
var phish1BeenHit:Boolean = false;var phish2BeenHit:Boolean = false;
var phish3BeenHit:Boolean = false;var phish4BeenHit:Boolean = false;
public function DieLikeThePhishes(clip2:MovieClip,clip3:MovieClip,clip4:MovieClip,clip5:MovieClip,clip6:M ovieClip,clip10:MovieClip,clip11:MovieClip,clip12:MovieClip,clip13:MovieClip,clip14:MovieC lip,clip15:MovieClip,clip16:MovieClip,clip17:MovieClip,clip18:MovieClip,clip19:MovieClip,c lip20:MovieClip,clip21:MovieClip,clip22:MovieClip)
_clip2 = clip2;_clip3 = clip3;_clip4 = clip4;_clip5 = clip5;_clip6 = clip6;
_clip10 = clip10;_clip11 = clip11;_clip12 = clip12;_clip13 = clip13;_clip14 = clip14;
_clip15 = clip15;_clip16 = clip16;_clip17 = clip17;_clip18 = clip18;_clip19 = clip19;
_clip20 = clip20;_clip21 = clip21;_clip22= clip22;
_clip3.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame)
function onEnterFrame(event:Event):void
vy1+= ay1;_clip3.y += vy1; vy2+= ay2;_clip4.y += vy2;
vy3+= ay3;_clip5.y += vy3; vy4+= ay4;_clip6.y += vy4;
if (phish1BeenHit ==false)
if(_clip3.y >620)
{_clip3.y = 620;}
if (phish2BeenHit ==false)
if(_clip4.y >620)
{_clip4.y = 620;}
if (phish3BeenHit ==false)
if(_clip5.y >620)
{_clip5.y = 620;}
if (phish4BeenHit ==false)
if(_clip6.y >620)
{_clip6.y = 620;}
if (_clip11.hitTestObject(_clip3) ||_clip12.hitTestObject(_clip3)||_clip13.hitTestObject(_clip3)||_clip14.hitTestObject(_cl ip3)||_clip15.hitTestObject(_clip3)||_clip16.hitTestObject(_clip3)||_clip17.hitTestObject( _clip3)||_clip18.hitTestObject(_clip3)||_clip19.hitTestObject(_clip3)||_clip20.hitTestObje ct(_clip3)||_clip21.hitTestObject(_clip3)||_clip22.hitTestObject(_clip3))
_clip3.scaleY = -Math.abs(_clip3.scaleY);
_clip3.alpha = 0.4;
ay1 = 3
vy1= -2;
phish1BeenHit = true;
if (_clip11.hitTestObject(_clip4) ||_clip12.hitTestObject(_clip4)||_clip13.hitTestObject(_clip4)||_clip14.hitTestObject(_cl ip4)||_clip15.hitTestObject(_clip4)||_clip16.hitTestObject(_clip4)||_clip17.hitTestObject( _clip4)||_clip18.hitTestObject(_clip4)||_clip19.hitTestObject(_clip4)||_clip20.hitTestObje ct(_clip4)||_clip21.hitTestObject(_clip4)||_clip22.hitTestObject(_clip4))
_clip4.scaleY = -Math.abs(_clip4.scaleY);
_clip4.alpha = 0.4;
ay2 = 3
vy2= -2;
phish2BeenHit = true;
if (_clip11.hitTestObject(_clip5) ||_clip12.hitTestObject(_clip5)||_clip13.hitTestObject(_clip5)||_clip14.hitTestObject(_cl ip5)||_clip15.hitTestObject(_clip5)||_clip16.hitTestObject(_clip5)||_clip17.hitTestObject( _clip5)||_clip18.hitTestObject(_clip5)||_clip19.hitTestObject(_clip5)||_clip20.hitTestObje ct(_clip5)||_clip21.hitTestObject(_clip5)||_clip22.hitTestObject(_clip5))
_clip5.scaleY = -Math.abs(_clip5.scaleY);
_clip5.alpha = 0.4;
ay3 = 3
vy3= -2;
phish3BeenHit = true;
if (_clip11.hitTestObject(_clip6) ||_clip12.hitTestObject(_clip6)||_clip13.hitTestObject(_clip6)||_clip14.hitTestObject(_cl ip6)||_clip15.hitTestObject(_clip6)||_clip16.hitTestObject(_clip6)||_clip17.hitTestObject( _clip6)||_clip18.hitTestObject(_clip6)||_clip19.hitTestObject(_clip6)||_clip20.hitTestObje ct(_clip6)||_clip21.hitTestObject(_clip6)||_clip22.hitTestObject(_clip6))
_clip6.scaleY = -Math.abs(_clip6.scaleY);
_clip6.alpha = 0.4;
ay4 = 3
vy4= -2;
phish4BeenHit = true;
if (_clip3.y > 10000)
_clip3.x = 1000 +3000*Math.random()-_clip10.x;
_clip3.y = 300;
_clip3.alpha = 1;
_clip3.scaleY = Math.abs(_clip3.scaleY);
ay1 = vy1 = 0;
phish1BeenHit = false;
if (_clip4.y > 10000)
_clip4.x = 1000 +3000*Math.random()-_clip10.x;
_clip4.y = 300;
_clip4.alpha = 1;
_clip4.scaleY = Math.abs(_clip4.scaleY);
ay2 = vy2 = 0;
phish2BeenHit = false;
if (_clip5.y > 10000)
_clip5.x = 1000 +3000*Math.random()-_clip10.x;
_clip5.y = 300;
_clip5.alpha = 1;
_clip5.scaleY = Math.abs(_clip5.scaleY);
ay3 = vy3 = 0;
phish3BeenHit = false;
if (_clip6.y > 10000)
_clip6.x = 1000 +3000*Math.random()-_clip10.x;
_clip6.y = 300;
_clip6.alpha = 1;
_clip6.scaleY = Math.abs(_clip6.scaleY);
ay4 = vy4 = 0;
phish4BeenHit = false;
var missleDisappear1 = new MissleDisappear(_clip11,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear2 = new MissleDisappear(_clip12,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear3 = new MissleDisappear(_clip13,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear4 = new MissleDisappear(_clip14,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear5 = new MissleDisappear(_clip15,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear6 = new MissleDisappear(_clip16,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear7 = new MissleDisappear(_clip17,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear8 = new MissleDisappear(_clip18,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear9 = new MissleDisappear(_clip19,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear10 = new MissleDisappear(_clip20,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear11 = new MissleDisappear(_clip21,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear12 = new MissleDisappear(_clip22,_clip3,_clip4,_clip5,_clip6,_clip10);I would approach it in much the same way as you would in java, by making getters and setters for all of your class variables.
Getters being for returning the values, Setters being for setting them.
So you would make a get function for the variable you want to access ala:
function get1PhishBeenHit():boolean {
return this.phish1BeenHit;
Then to access the value of that variable from outwith the class:
var result:boolean = ClassInstanceName.get1PhishBeenHit(); -
Access data of one class from another class
Hi,
I am creating one class say ClassA with some data members,the same class has main() method on execution of which the data members will b assigned a value.
now i have another class say ClassB with main() method and i want to use the data in ClassA in ClassB do i have any way by which i can have access to that data.
The instance of ClassA created in ClassB is not showing any values in data members.
Can u help me find a solution for this.
Thank you.
Parag.I have tried by making one data member public so that it can have direct access from other class.But it shows null value.
The problem is that ClassA class data members are assigned values when it completes the execution of function main() so does it retains the values.
c sample code below.
public classA{
int a,b;
p s v m(String [] args)
setab();
public void setab()
//set values of a and b by doing some manipulations.
public classB{
p s v m(string []args)
classA aclass = new classA();
/* now what should i do to access the values of a & b in
aclass object*/
i strictly need to follow this way do i have a way out. -
Accessing an Array List from another class
Hi, I was a member on here before, but I forgot my password and my security question is wrong.
My question is how do I access a private arraylist from a different class in the same package?
What I am trying to do is the following (hard to explain).
Make a picking client for a shop, so that when an order is recieved, the picker can click on the orders button, and view all of the current orders that have not been completed. This Pick client has its own user interface, in a seperate class from where the BoughtList array is created, in the cashier client. The boughtlist is created when the cashier puts in the product number into the cashier client and clicks buy. I seem to be having trouble accessing the list from another class. Once the order is completed the cashier clicks bought and the list is reset. There is another class in a different pagage that processes some of the functions of the order, eg newOrder().
Yes it is for Uni so I dont need / want the full answers, jist something to get started. Also please dont flame me, I have done many other parts of this project, just having trouble getting started on this one.
Here is the code for the cashier client. The code for the Pick client is almost the same, I just need to make the code that displays the orders.
package Clients;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.NumberFormat;
import java.util.Locale;
import Catalogue.*;
import DBAccess.*;
import Processing.*;
import Middle.*;
class CashierGUI
class STATE // Cashier states
public static final int PROCESS = 0;
public static final int CHECKED = 1;
class NAME // Names of buttons
public static final String CHECK = "Check";
public static final String BUY = "Buy";
public static final String CANCEL = "Cancel";
public static final String BOUGHT = "Bought";
private static final int H = 300; // Height of window pixels
private static final int W = 400; // Width of window pixels
private JLabel theAction = new JLabel();
private JTextField theInput = new JTextField();
private JTextArea theOutput = new JTextArea();
private JScrollPane theSP = new JScrollPane();
private JButton theBtCheck = new JButton( NAME.CHECK );
private JButton theBtBuy = new JButton( NAME.BUY );
private JButton theBtCancel= new JButton( NAME.CANCEL );
private JButton theBtBought= new JButton( NAME.BOUGHT );
private int theState = STATE.PROCESS; // Current state
private Product theProduct = null; // Current product
private BoughtList theBought = null; // Bought items
private Transaction theCB = new Transaction();
private StockReadWriter theStock = null;
private OrderProcessing theOrder = null;
private NumberFormat theMoney =
NumberFormat.getCurrencyInstance( Locale.UK );
public CashierGUI( RootPaneContainer rpc, MiddleFactory mf )
try //
theStock = mf.getNewStockReadWriter(); // DataBase access
theOrder = mf.getNewOrderProcessing(); // Process order
} catch ( Exception e )
System.out.println("Exception: " + e.getMessage() );
Container cp = rpc.getContentPane(); // Content Pane
Container rootWindow = (Container) rpc; // Root Window
cp.setLayout(null); // No layout manager
rootWindow.setSize( W, H ); // Size of Window
Font f = new Font("Monospaced",Font.PLAIN,12); // Font f is
theBtCheck.setBounds( 16, 25+60*0, 80, 40 ); // Check Button
theBtCheck.addActionListener( theCB ); // Listener
cp.add( theBtCheck ); // Add to canvas
theBtBuy.setBounds( 16, 25+60*1, 80, 40 ); // Buy button
theBtBuy.addActionListener( theCB ); // Listener
cp.add( theBtBuy ); // Add to canvas
theBtCancel.setBounds( 16, 25+60*2, 80, 40 ); // Cancel Button
theBtCancel.addActionListener( theCB ); // Listener
cp.add( theBtCancel ); // Add to canvas
theBtBought.setBounds( 16, 25+60*3, 80, 40 ); // Clear Button
theBtBought.addActionListener( theCB ); // Listener
cp.add( theBtBought ); // Add to canvas
theAction.setBounds( 110, 25 , 270, 20 ); // Message area
theAction.setText( "" ); // Blank
cp.add( theAction ); // Add to canvas
theInput.setBounds( 110, 50, 270, 40 ); // Input Area
theInput.setText(""); // Blank
cp.add( theInput ); // Add to canvas
theSP.setBounds( 110, 100, 270, 160 ); // Scrolling pane
theOutput.setText( "" ); // Blank
theOutput.setFont( f ); // Uses font
cp.add( theSP ); // Add to canvas
theSP.getViewport().add( theOutput ); // In TextArea
rootWindow.setVisible( true ); // Make visible
class Transaction implements ActionListener // Listener
public void actionPerformed( ActionEvent ae ) // Interaction
if ( theStock == null )
theAction.setText("No conection");
return; // No connection
String actionIs = ae.getActionCommand(); // Button
try
if ( theBought == null )
int on = theOrder.uniqueNumber(); // Unique order no.
theBought = new BoughtList( on ); // Bought list
if ( actionIs.equals( NAME.CHECK ) ) // Button CHECK
theState = STATE.PROCESS; // State process
String pn = theInput.getText().trim(); // Product no.
int amount = 1; // & quantity
if ( theStock.exists( pn ) ) // Stock Exists?
{ // T
Product pr = theStock.getDetails(pn); // Get details
if ( pr.getQuantity() >= amount ) // In stock?
{ // T
theAction.setText( // Display
pr.getDescription() + " : " + // description
theMoney.format(pr.getPrice()) + // price
" (" + pr.getQuantity() + ")" // quantity
); // of product
theProduct = pr; // Remember prod.
theProduct.setQuantity( amount ); // & quantity
theState = STATE.CHECKED; // OK await BUY
} else { // F
theAction.setText( // Not in Stock
pr.getDescription() +" not in stock"
} else { // F Stock exists
theAction.setText( // Unknown
"Unknown product number " + pn // product no.
if ( actionIs.equals( NAME.BUY ) ) // Button BUY
if ( theState != STATE.CHECKED ) // Not checked
{ // with customer
theAction.setText("Check if OK with customer first");
return;
boolean stockBought = // Buy
theStock.buyStock( // however
theProduct.getProductNo(), // may fail
theProduct.getQuantity() ); //
if ( stockBought ) // Stock bought
{ // T
theBought.add( theProduct ); // Add to bought
theOutput.setText( "" ); // clear
theOutput.append( theBought.details()); // Display
theAction.setText("Purchased " + // details
theProduct.getDescription()); //
// theInput.setText( "" );
} else { // F
theAction.setText("!!! Not in stock"); // Now no stock
theState = STATE.PROCESS; // All Done
if ( actionIs.equals( NAME.CANCEL ) ) // Button CANCEL
if ( theBought.number() >= 1 ) // item to cancel
{ // T
Product dt = theBought.remove(); // Remove from list
theStock.addStock( dt.getProductNo(), // Re-stock
dt.getQuantity() ); // as not sold
theAction.setText(""); //
theOutput.setText(theBought.details()); // display sales
} else { // F
theOutput.setText( "" ); // Clear
theState = STATE.PROCESS;
if ( actionIs.equals( NAME.BOUGHT ) ) // Button Bought
if ( theBought.number() >= 1 ) // items > 1
{ // T
theOrder.newOrder( theBought ); // Process order
theBought = null; // reset
theOutput.setText( "" ); // Clear
theInput.setText( "" ); //
theAction.setText( "Next customer" ); // New Customer
theState = STATE.PROCESS; // All Done
theInput.requestFocus(); // theInput has Focus
catch ( StockException e ) // Error
{ // Of course
theOutput.append( "Fail Stock access:" + // Should not
e.getMessage() + "\n" ); // happen
catch ( OrderException e ) // Error
{ // Of course
theOutput.append( "Fail Order process:" + // Should not
e.getMessage() + "\n" ); // happen
}(disclaimer: I did not read through your Swing code, as I find that painful)
My question is how do I access a private arraylist from a different class in the same
package?Provide a public accessor method (getMyPrivateArrayList()) -
Easy question: Give access to a class in another class.
Stupid title, but dont know how to express myself :P Sorry for that.
To the problem. Never had this problem before, and I know its a really easy solution to this.
I have my Main class, which creates a MyView class. Inside this class, I make to new classes(or instances of classes i've already made), MyPanel and MyToolsPanel. Now I want to add buttons inside the MyToolsPanel class, and add actionlisteners to these buttons inside MyPanel.
What I'v always done to grant access to MyToolsPanel inside of MyTools, is to simply add a
//this is the MyPanel class
MyToolsPanel mtp;
public void setMtp(MyToolsPanel mtp){
this.mtp = mtp;
}and then in the MyView class which create these to classes, I put a command: mp.setMtp(mtp);
When I run this it doesnt work.. Why? Should be easy to solve, since it obviously is a stupid problem that I just dont see. :P Feeling kind of stupid to ask this question, but this is how it is...
EDIT: I might have to implement actionListener inside the MyToolsPanel class?
Edited by: Stianbl on Sep 28, 2008 4:59 PMone way:
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
* Subclasses JPanel, can send text out via the getText() method
* can hook into button press via addActionListener
* @author Pete
public class PanelCommSender extends JPanel
private JTextField sendingField = new JTextField(12);
private JButton sendButton = new JButton("Send");
public PanelCommSender()
add(sendingField);
add(sendButton);
public void addActionListener(ActionListener al)
// attach this listener to the button
sendButton.addActionListener(al);
* call this to get the text currently in the textfield
* @return String text
public String getText()
return sendingField.getText();
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
* Subclasses JPanel, receives text from another class
* @author Pete
public class PanelCommReceiver extends JPanel
private JTextField showResultsField = new JTextField(12);
public PanelCommReceiver()
showResultsField.setEditable(false);
add(new JLabel("Results from other panel: "));
add(showResultsField);
* call this to set text of textField
* @param text
public void setText(String text)
showResultsField.setText(text);
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class PanelCommControl
private static void createAndShowUI()
// create new instances of the receiving and sending panels:
final PanelCommReceiver receivePanel = new PanelCommReceiver();
final PanelCommSender sendPanel = new PanelCommSender();
// let the communicate w/ each other
sendPanel.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
receivePanel.setText(sendPanel.getText());
// place the receiving JPanel into a JFrame
JFrame frame = new JFrame("Receiving Panel");
frame.getContentPane().add(receivePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 300)); // make it bigger so it can be seen
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// place the sending JPanel into a JDialog
JDialog dialog = new JDialog(frame, "Sending Panel", false);
dialog.getContentPane().add(sendPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
public static void main(String[] args)
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
// run the whole show in a thread-safe manner
createAndShowUI();
}
Maybe you are looking for
-
After upgrade to 4.1 from 3.2, admin logon page error with "done error load
Hello all, Just upgraded 3.2 to 4.1. ran @apexins.sql sysaux sysaux temp /i/. Installation was successful and upgrade completed with no errors. When trying to log on to admin page, url changes to admin workarea but with IE we get "done error loading
-
Rowlevel secuirty in Crystal reports when integrated in Enterprise portal
I have a very simple crystal report which is developed against ECC data using the Open Sql Driver. Do I have to included some kind of code/logic in the report design for the SAP row-level security that already exists on SAP server to pass to the Crys
-
Obiee 11g RPD consistency check error after upgrade
Hi, got below error in RPD consistency check after upgrading from obiee 10g to obiee 11.1.1.6. *ERRORS: Business Model Core: [38028] Logical column Dim - Contact.Age Range does not have a valid data type.* logical column Age= CASE WHEN "Core"."Dim -
-
Looking for an external USB CD/DVD burner
Hello all, I just got my MacBook Air 13" and I'm in need of an external USB CD/DVD burner. I've read on Newegg and Amazon that certain drives require two USB plugs just to get sufficient power. With the MBA, however, this isn't really feasible beca
-
How does one integrate iPhoto/Aperture pics?
How does one integrate iPhoto/Aperture pics in iCloud Pages and Keynote when there is no longer a MEDIA BROWSER pop-up within this new update? Please advise.