Using a variable from one class to another
Hi !
I've a class called ModFam (file ModFam.java) where I define a variable as
protected Connection dbconn;
Inside ModFam constructor I said:
try
String url = "jdbc:odbc:baselocal";
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
dbconn = DriverManager.getConnection(url);
System.err.println("Connection successful");
} ..... rest of code
This class define a TabbedPane as follows:
tabbedPane.addTab("Welcome",null,new Familias(),"Familias");
As you can see it call a new instance of the Familias class (file Familias.java).
This constructor will try to connect with the DB to populate a combo box with some data retireved from the DB.
If I do
Statement stmt;
stmt = dbconn.createStatement();
inside Familias constructor I receive the message
Familias.java:50: cannot resolve symbol
symbol : variable dbconn
location: class fam.Familias
stmt = dbconn.createStatement();
at compile time.
While I can�t use a variable defined as "protected" in one class of my package on another class of the same package ?
How could I do ?
Thanks in advance
<jl>
Familias doesn't have a reference to ModFam or the Connection.
So change the constructor in Familias to be
public class Familias {
private ModFam modFam;
public Familias(ModFam m) {
modFam = m;
// ... somewhere else in the code
Statement stmt = modFam.dbconn.createStatement();
}or
public class Familias {
private Connection dbconn;
public Familias(Connection c) {
dbconn = c;
// ... somewhere else in the code
Statement stmt = dbconn.createStatement();
}And when you instantiate Familias it should then be
new Familias(this) // ModFam reference
or
new Familias(dbconn)
Similar Messages
-
Using a variable from one class in another
For learning purposes, I thought I'd have a stab at making a role-playing RPG.
The first class I made was the Player class;
public class Player
public static void main(String[] args)
// [0] being base points and [1] being skill points
int[] points = {50, 10};
// Elements in statNames are relevent to stats, so stats[0] is health, and so on
String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
int[] stats = new int[5];
public static String setName()
Scanner input = new Scanner(System.in);
System.out.print("Character name: ");
String name = input.nextLine();
return name;
public static void setHealth(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Health (" + points[0] + " base points remanining): ");
stats[0] = input.nextInt();
points[0] -= stats[0];
public static void setMana(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Mana (" + points[0] + " base points remanining): ");
stats[1] = input.nextInt();
points[0] -= stats[1];
public static void setAttack(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Attack (" + points[1] + " skill points remanining): ");
stats[2] = input.nextInt();
points[1] -= stats[2];
public static void setMagic(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Magic (" + points[1] + " skill points remanining): ");
stats[3] = input.nextInt();
points[1] -= stats[3];
public static void setCraft(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Craft (" + points[1] + " skill points remanining): ");
stats[4] = input.nextInt();
points[1] -= stats[4];
public static void setStats(int[] points, int[] stats)
setHealth(points, stats);
setMana(points, stats);
setAttack(points, stats);
setMagic(points, stats);
setCraft(points, stats);
public static void charSummary(String name, String[] statNames, int[] stats)
System.out.println("\n------ " + name);
for(int index = 0; index < stats.length; index++)
System.out.println(statNames[index] + ":\t" + stats[index]);
}And that would be used in the Play class;
public class Play
public static void main(String[] args)
Player player = new Player();
String name = player.setName();
player.setStats(points, stats);
} But I'm not sure how the Play class will get the arrays from the Player class. I tried simply putting public in front of the them, for example;
public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};But I get an illegal start of expression error.
I may have taken the wrong approach to this all together, I'm completely new, so feel free to suggest anything else. Sorry for any ambiguity.
Edited by: xcd on Jan 6, 2010 8:12 AM
Edited by: xcd on Jan 6, 2010 8:12 AMHI XCD ,
what about making Player class as
public class Player
// [0] being base points and [1] being skill points
int[] points = {50, 10};
// Elements in statNames are relevent to stats, so stats[0] is health, and so on
public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
int[] stats = new int[5];
public String setName()
Scanner input = new Scanner(System.in);
System.out.print("Character name: ");
String name = input.nextLine();
return name;
public void setHealth(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Health (" + points[0] + " base points remanining): ");
stats[0] = input.nextInt();
points[0] -= stats[0];
public void setMana(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Mana (" + points[0] + " base points remanining): ");
stats[1] = input.nextInt();
points[0] -= stats[1];
public void setAttack(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Attack (" + points[1] + " skill points remanining): ");
stats[2] = input.nextInt();
points[1] -= stats[2];
public void setMagic(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Magic (" + points[1] + " skill points remanining): ");
stats[3] = input.nextInt();
points[1] -= stats[3];
public void setCraft(int[] points, int[] stats)
Scanner input = new Scanner(System.in);
System.out.print("Craft (" + points[1] + " skill points remanining): ");
stats[4] = input.nextInt();
points[1] -= stats[4];
public void setStats(int[] points, int[] stats)
setHealth(points, stats);
setMana(points, stats);
setAttack(points, stats);
setMagic(points, stats);
setCraft(points, stats);
public void charSummary(String name, String[] statNames, int[] stats)
System.out.println("\n------ " + name);
for(int index = 0; index < stats.length; index++)
System.out.println(statNames[index] + ":\t" + stats[index]);
}and Play class
public class Play
public static void main(String[] args)
Player player = new Player();
String name = player.setName();
player.setStats(points, stats);
}Now you can access names , you can't assign keyword to variable into method scope , make it class variable .
Hope it help :) -
How to pass a variable from one class to another class?
Hi,
Is it possible to pass a variable from one class to another? For e.g., I need the value of int a for calculation purpose in method doB() but I get an error <identifier> expected. What does the error mean? I know, it's a very, very simple question but once I learn this, I promise to remember it forever. Thank you.
class A {
int a;
int doA() {
a = a + 1;
return a;
class B {
int b;
A r = new A();
r.a; // error: <identifier> expected. What does that mean ?
int doB() {
int c = b/a; // error: operator / cannot be applied to a
}Thank you!elaine_g wrote:
I am wondering why does (r.a) give an error outside the method? What's the reason it only works when used inside the (b/r.a) maths function? This is illegal syntax:
class B {
int b;
A r = new A();
r.a; //syntax error
}Why? Class definition restricts what you can define within a class to a few things:
class X {
Y y = new Y(); //defining a field -- okay
public X() { //defining a constructor -- okay
void f() { //defining a method -- okay
}... and a few other things, but you can't just write "r.a" there. It also makes no sense -- that expression by itself just accesses a field and does nothing with it -- why bother?
This is also illegal syntax:
int doB() {
A r = new A();
r.a; // error: not a statement
}Again, all "r.a" does on its own is access a field and do nothing with it -- a "noop". Since it has no effect, writing this indicates confusion on the part of the coder, so it classified as a syntax error. There is no reason to write that. -
Moving Variable from one class to another.
I need to get a Variable from one class to another how would I do this?
Well this is a very tipical scehario for every enterprise application. You always create logger classes that generate log files for your application, as that is the only way to track errors in your system when its in the production enviorment.
Just create a simple class that acts as the Logger, and have a method in it that accepts a variable of the type that you are are trying to pass; most commonly a String; but can be overloaded to accept constom classes. e.g.
class Logger
public void log(String message)
writeToFile("< " + new Date() + " > " + message);
public void log(CustomClass queueEvent)
log("queue message was: " + queueEvent.getMessage() + " at: " + queueEven.getEventTime());
}Hope this makes things clearer
Regards
Omer -
Passing Variables from One Class to Another
Hello, I am new to Java Programming and I'm currently starting off by trying to build a simple application.
I need help to pass variables created in one class to another.
In my source package, I created 2 java classes.
1. Main.java
2. InputFileDeclared.java
InputFileDeclared reads numerical data from an external text file and store them as string variables within the main method while Main converts a text string into a number.
Hence, I would like to pass these strings variables from the InputFileDeclared class to the Main class so that they can be converted into numbers.
I hope somebody out there may enlighten me on this.
Thank you very much in advance!Values are passed from method to method, rather than from class to class. In a case such as you describe the code of a method in Main will probably call a method in InputFileDeclared which will return the String you want. The method in Main stores that in a local variable and processes it. It really doesn't matter here which class the method is in.
You InputFileDeclared object probably contains "state" information in its fields such as the details of the file it's reading and how far it's got, but generally the calling method in Main won't need to know about this state, just the last data read.
So the sequence in the method in Main will be:
1) Create an new instance of InputFileDeclared, probably passing it the file path etc..
2) Repeatedly call a method on that instance to return data values, until the method signals that it's reached the end of file, e.g. by returning a null String.
3) Probably call a "close()" method on the instance, which you should have written to close the file. -
Sending a variable from one class to another?
Dear Java Users - please can you help me out here... I know that what I am asking should be straight forward BUT I just don't understand any of the responses people have put on the web....
Here is what I am trying to do:
This piece of code - creates a window with a simple textbox on it to enter a word...
The button then calls another class file to open a new window...
All I want to do is to take the word from the text box and print it in the new window....
The first .java file I have is this:
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class FrontPageGUI extends JFrame implements ActionListener
//declare all instance variables for THIS per class
JLabel lblInfoOne;
JLabel lblButtonPopUp;
JTextField txtName;
JButton close;
JButton popUp;
public FrontPageGUI()
//set characteristics of the JFrame object
super("Title Bar");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//we need to define a Container to place objects onto the frame - this is inside the JFrame Object Above
Container ca = getContentPane( );
ca.setSize(600,600);
ca.setBackground(Color.white);
ca.setLayout(null);
//define all other objects and set thier characteristics
lblInfoOne = new JLabel("Enter a word in the box above to send:");
lblButtonPopUp = new JLabel("Click Here:");
txtName = new JTextField("");
//create Button components
close = new JButton("Close");
popUp = new JButton("Click Me");
//now add all objects to the container
//Labels
addXY(ca,lblInfoOne, 30, 160, 550,45);
addXY(ca,lblButtonPopUp, 30, 210, 550,45);
//TextField
addXY(ca,txtName, 120, 100, 200,30);
//Buttons
addButtonXY(ca, popUp, 30, 260, 200, 45);
addButtonXY(ca, close, 30, 310, 80, 30);
// add the Container to the Frame
setContentPane(ca);
void addButtonXY(Container c, JButton cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
cp.addActionListener(this);
c.add(cp);
void addXY(Container c, Component cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
c.add(cp);
public void actionPerformed(ActionEvent event)
if (event.getSource()== popUp)
//This is WHERE THE PROBLEM IS...
//Here I want to send to contents of the textfield - txtName
String temp = txtName.getText();
new PopUpGUI(temp);
if (event.getSource()==close)
closeUp();
void closeUp()
System.exit(0);
//dispose();
//we need a driver program - this is the only time MAIN is used.
public class FrontPage
//create an instance of the GUI and showit
public static void main(String args [])
new FrontPageGUI();
The second .java file I have is this:
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class PopUpGUI extends JFrame implements ActionListener
//declare all instance variables ie per class
JLabel headerLabel;
JLabel sentLabel;
JButton close;
public PopUpGUI(String Sent)
//set characteristics of the JFrame object
super("Pop Up Window");
setSize(320,450);
setVisible(true);
//need to define a Container to place objects onto the frame
Container ca = getContentPane( );
ca.setSize(320,450);
ca.setLayout(null);
//define all other objects and set characteristics
headerLabel = new JLabel("New Window!"); //heading label
sentLabel = new JLabel(Sent);
close = new JButton("Close");
//now add all objects to the container
addXY(ca,headerLabel,10,10,380,80);
addXY(ca,sentLabel,10,100,380,80);
addButtonXY(ca, close, 50, 200, 100, 30); //Bottom Left
// add the Container to the Frame
setContentPane(ca);
//We need these 2 methods - EVERY TIME
void addButtonXY(Container c, JButton cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
cp.addActionListener(this);
c.add(cp);
void addXY(Container c, Component cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
c.add(cp);
//What to do when the click happens
public void actionPerformed(ActionEvent event)
if (event.getSource()==close)
dispose();
//closeUp(); - Doesn't run CLOSEUP this time (i.e. exit program) - instead just DISPOSEs of the window
//Driver class is in FrontPage.javaThis seems to work... but is it the best way to do it????
Tony.Well,
Using the constructor is the way to go. Otherwise create a method that takes the string as parameter. -
Is there a way to reference a private variable from one class in another?
My first class starts off by declaring variables like so:
class tStudent {
// declare student name, id, grades 1 & 2, and gpa
private String fname, lname, g1, g2;
private int id;
private double gpa;
// define a constructor for a new student
tStudent () {fname=lname=g1=g2=null; id=-1; gpa=0.0;}
// define methods for manipulating the data members.
// readStudent: reads information for just one student
public void read (Scanner input) {
fname = input.next();
lname = input.next();
id = input.nextInt();
g1 = input.next();
g2 = input.next();
}And the second class:// tStudentList: for a list of students
class tStudentList {
private int nStudents;
private tStudent[] list;
// constructor for creating student list
tStudentList() {
list = new tStudent[36];
for (int i=0; i < 36; i++) list=new tStudent();
// read the individual students into the student list
public void read(Scanner scan) {
nStudents=0;
while (scan.hasNext()) {list[nStudents++].read(scan);}
// display the list of all students - fname, lname, id, g1, g2 and gpa
// with an appropriate header so the output matches my sample //output
public void print() {
Is there a way to reference the variables in the first class to use in the second? Specifically in the last section of code where I am going to print the list.Not without resorting to reflection hackery. If the fields are private (and are supposed to be), then that means "don't allow access to these to outsiders of this class" by design.
So if you really meant them to be accessible, then don't use private, or provide public accessors for them. -
How to send a variable from one class to another?
hello,
i have "One.as", which is the document class for one.swf.
i also have "two.swf", with "Two.swf" entered as its document
class...
One loads two into it. two is basically a 10 frame movieClip
with a variable at the beginning called "var endFrame:Boolean =
false", then on the last frame it says endFrame = true.
my question: how in the world do I communicate this back to
One.as??? i've tried ENTER_FRAME listeners, declaring the variable
here and there... and many other embarrassingly usuccessful
strategies.
i would just like to load in "three.swf" after two.swf
finishes... but One needs to know that it has indeed finished.
your help would be greatly appreciated. thanksyarkehsiow,
> David,
> thank you for responding.
Sure thing! :)
> so does what you are saying mean that endFrame is a
property of
> two (the movieClip), or Two (the Class)?
If you've written a property named endFrame for your Two
class, then
yes, Two.endFrame is a property of that class.
Looking back at your original post, I see that you wrote
this:
> One loads two into it. two is basically a 10 frame
movieClip
> with a variable at the beginning called "var
endFrame:Boolean = false",
> then on the last frame it says endFrame = true.
So it sounds like your Two class extends MovieClip. (I'm not
sure
that's true, but that's what it sounds like.) That means your
Two class
supports all the features of the MovieClip class, including a
play() method,
a currentFrame property, and so on. In addition, you've added
new
functionality that amounts to -- by the sound of it -- a
property named
endFrame. If you made your property public (i.e., public var
endFrame),
then it should be accessible by way of an object reference to
your Two
instance.
myTwoInstance.endFrame;
> so can i invoke that method in One.as? do I call it
Two.endFrame (if
> (Two.endFrame == true) {?
Methods are things an object can *do,* such as
gotoAndPlay(). What
you're describing is a property (a characteristic ... in this
case, a
Boolean characteristic). You wouldn't use the expression
Two.endFrame
unless that property was static. Static classes are those
that cannot have
an instance made of them. Think of the Math class. It
contains numerous
static properties in the form of constants, such as Math.PI,
Math.E,
Math.SQRT2, and so on. You can't create an instance of the
Math class -- it
wouldn't make sense to -- so Math is a static class.
On the other hand, you definitely create instances of the
MovieClip
class. Every movie clip symbol is an instance of MovieClip
class, which
means that each instance carries its own unique values for
MovieClip class
members. The MovieClip class defines x and y properties, but
each movie
clip symbol (that is, each instance of the MovieClip class)
configures its
own values of those properties, depending on where each
instance is located
on the Stage.
Assuming your Two class is not static, then somewhere along
the line,
your One class will have to make an instance of it. Somethine
like ...
// inside your One class ...
var myTwo:Two = new Two();
... at which point that myTwo variable because a reference to
that
particular instance of Two. You can invoke Two methods on
that instance.
You can invoke Two properties and events on that instance.
You can invoke
whatever functionality is defined by the Two class on that
myTwo instance.
If Two extends MovieClip, that means you can also invoke any
MovieClip class
member on that myTwo instance.
At some point in your One class, you can refer to that myTwo
instance
later and check if the value of myTwo.endFrame is true or
false.
David Stiller
Adobe Community Expert
Dev blog,
http://www.quip.net/blog/
"Luck is the residue of good design." -
Passing a variable from one class to another
Hello:
I am new to java programming. I am developing an application in Java
At a particular JTextField call it jtf3, I am invoking Calendar application by clikcing a jbutton.
I would like to set text in jtf by obtaining the date clicked by the user. I am storing complete date string in the Calendar application during ActionPerformed event at Calendar Application level.
I do not know how to pass this string to calling frame as it does not listen to the button event happening at the Calendar Application.
Much appreciated
Thanks a lot for your time
regardsThis is the application from which the I am calling the calendar application.
The method setDate set the date obtained from calendar class during actionperformed event.
The actionperfomed event from CalendarClass is pasted below as well.
Much appreciated
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
public class TestDrive
public static void main(String[] args) {
DatePanelFrame dpf = new DatePanelFrame();
dpf.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent we) { System.exit(0); }
dpf.pack();
dpf.setVisible(true);
class DatePanelFrame extends JFrame {
JTextField djtf;
String dateInput;
public DatePanelFrame() {
setTitle("Date Panel");
setSize(100, 800);
setLocation(300, 100);
Container content = getContentPane();
JPanel datePanel = new JPanel();
JButton calButton = new JButton(".....");
datePanel.add(calButton, BorderLayout.SOUTH);
djtf = new JTextField(" ");
datePanel.add(djtf, BorderLayout.NORTH);
content.setLayout(new BorderLayout());
content.add(datePanel, BorderLayout.CENTER);
calButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent event)
JFrame fr = new CalendarClass();
fr.setSize(400, 400);
fr.setLocation(600, 100);
ObjCal oc = new ObjCal();
fr.setVisible(true);
public void setDate(String d)
djtf.setText(d);
repaint();
System.out.println(djtf.getText());
The ActionPerformed event from CalendarClass
jbtArray.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent event)
if (event.getActionCommand() != " ")
daySelected = event.getActionCommand();
yearSelected = jtfYear.getText();
int intYearSelected = Integer.valueOf(yearSelected).intValue();
monthSelected = jtfMonth.getText();
intDaySelected = Integer.valueOf(daySelected).intValue();
int intMonthSelected = getMonthNum(monthSelected);
dateSelected = getDate(intYearSelected, intMonthSelected, intDaySelected);
TestDrive td = new TestDrive();
DatePanelFrame dpf = new DatePanelFrame();
dpf.setDate(dateSelected); -
Variable from one class to another
I have a Program that contains a JDesktop Pane, and when the program starts, it creates the "main" window as in JInternal Frame.
When a certain check box is checked, I call an external class that creates and returns a JInternalFrame. What I need to do is have the external class get a Vector from the main class (I pass it in when i create the object), edit the Vector, then return it to the main class. If i try to create a method in the main class like "returnVector()" or whatever to get the vector back to the main class, I get the error of "Non-static variable cannot be referenced from a non-static context". How can I get around that? The NEXT issue is this: I would like to cause the JInternalFrame that is created from the external class (on the JDesktopPane in the main class) to close itself when a button in it is clicked. I'm guess I'd need a Listener somewhere. Would that listener be in the Main class or in the external one. Does this make sense? Any help would be greatly appreciated.Sorry, This might be a bit lengthy, but it works and illustrates my problem. I created it in NetBeans. There are the two classes I'm jusing. The issue is illustrated in the button listener on the 2nd class:
The First:
package javaapplication3;
import java.beans.PropertyVetoException;
import java.util.Vector;
import javax.swing.JInternalFrame;
public class NewJFrame extends javax.swing.JFrame {
Vector <String> TestVector = new Vector <String> (0); //Vector to move around.
public NewJFrame() {
//add some test strings to the Vector
TestVector.add("String1");
TestVector.add("String2");
TestVector.add("String3");
initComponents();
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jDesktopPane1 = new javax.swing.JDesktopPane();
jInternalFrame1 = new javax.swing.JInternalFrame();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame1.getContentPane().setLayout(new java.awt.FlowLayout());
jInternalFrame1.setVisible(true);
jLabel1.setText("This is a VERY simple example");
jInternalFrame1.getContentPane().add(jLabel1);
jButton1.setText("Press this");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonListen(evt);
jInternalFrame1.getContentPane().add(jButton1);
jInternalFrame1.setBounds(10, 10, 350, 120);
jDesktopPane1.add(jInternalFrame1, javax.swing.JLayeredPane.DEFAULT_LAYER);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jDesktopPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jDesktopPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
pack();
}// </editor-fold>
private void ButtonListen(java.awt.event.ActionEvent evt) {
JInternalFrame newFrame;
NewJFrame2 roadframe = new NewJFrame2(TestVector);
newFrame= roadframe.getFrameBack();
newFrame.setVisible(true);
jDesktopPane1.add(newFrame);
try {
newFrame.setSelected(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
//created this in hopes of using it to return the vector from NewJFrame2
public void returnVector(Vector<String> vectorAgain){
this.TestVector=vectorAgain;
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}The 2nd:
package javaapplication3;
import java.util.Vector;
import javax.swing.DefaultListModel;
import javax.swing.JInternalFrame;
public class NewJFrame2 extends javax.swing.JFrame {
Vector <String> testVector=new Vector<String>(0);
DefaultListModel model;
public NewJFrame2(Vector <String> TestVector) {
this.testVector=TestVector;
initComponents();
public JInternalFrame getFrameBack(){
return jInternalFrame1;
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jInternalFrame1 = new javax.swing.JInternalFrame();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
model=new DefaultListModel();
for (int a=0; a<testVector.size();a++){
model.addElement(testVector.get(a));
jList1 = jList1=new javax.swing.JList(model);
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame1.setVisible(true);
jLabel1.setText("This is the 2nd class I was referencing I passed TestVector from NewFrame. It Contains:");
jInternalFrame1.getContentPane().add(jLabel1, java.awt.BorderLayout.NORTH);
jLabel2.setText("Now I want to Edit this list here, and then send it back to NewFrame1. The button will attemp.");
jInternalFrame1.getContentPane().add(jLabel2, java.awt.BorderLayout.SOUTH);
jScrollPane1.setViewportView(jList1);
jInternalFrame1.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
jButton1.setText("Return Vector");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ReturnVectorButtonListener(evt);
jInternalFrame1.getContentPane().add(jButton1, java.awt.BorderLayout.EAST);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jInternalFrame1)
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jInternalFrame1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
pack();
}// </editor-fold>
private void ReturnVectorButtonListener(java.awt.event.ActionEvent evt) {
NewJFrame.returnVector(testVector);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
} -
Using enum's from one class in another?
heya,
I have two classes, Predator and Simulation, and Predator has an public enum 'target' inside it.
Simulation needs to use a switch statement based on target (Simulation contains a list of Predators, and I'm returning type target to Simulation), but I am getting errors when compiling the two classes from the commandline (for some weird reason, it works fine in Eclipse - both classes are in a package 'lepidoptera', which I originally thoguht was the issue).
Errors are like (5 of these):
Simulation.java:64: an enum switch case label must be the unqualified name of an enumeration constant
case (mimic):Any ideas?
Thanks,
VictorThis works for moi:
public class Predator {
public enum Target {SEITAN, TOFU, TEMPEH}
public class Simulation {
public static String f(Predator.Target target) {
switch(target) {
case SEITAN:
return "yuck";
case TOFU:
return "ugh";
case TEMPEH:
return "crikey";
default:
return "nuts";
public static void main(String[] args) {
System.out.println(f(Predator.Target.SEITAN));
System.out.println(f(Predator.Target.TOFU));
System.out.println(f(Predator.Target.TEMPEH));
}And do you know that an enum can be a top level class? In other
words, that you can create the one-line file Target.java:
public enum Target {SEITAN, TOFU, TEMPEH} -
Use a counter from one class to another class of the same project
Hello!
In my class Book I have a variable, which is in fact a counter, counts the number of books. I need to use this same variable in another class Library, and I want to know if this is possible by any means!
Thank You very much for Your support!Read this carefully.
Regards, -
Variable from one class to another in a game
I am making a game in which a user can enter the speed of the initial velocity of a ball. My problem is that when i run the program and enter the speed of the ball in the JTextField, it doesn't actually change the speed of the ball. The ball just uses the speed that was set before the program ran
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.*;
import java.util.*;
/*Main Class*/
class Junaid_Java_ISU
public static void main(String[] args)
JFrame frame = new GameFrame();
frame.show();
/*GameFrame Class*/
class GameFrame extends JFrame implements ActionListener //got rid of BounceThreadFrame
public JTextField getHeight;
public JTextField velocityText;
private JTextField windSpeed;
private double dxUser = 5;
private int hyUser;
private JPanel canvas;
public GameFrame()
setSize(640, 480);
setTitle("Bounce");
addWindowListener(new WindowAdapter() //Need to replace this with one line
public void windowClosing(WindowEvent e)
System.exit(0);
Container contentPane = getContentPane();
canvas = new JPanel();
contentPane.add(canvas, "Center");
JPanel p = new JPanel();
getHeight = new JTextField(2);
getHeight.addActionListener(this);
velocityText = new JTextField(2);
velocityText.addActionListener(this);
windSpeed = new JTextField(2);
windSpeed.setEditable(false);
velocityText.setText("5");
/*Start Button*/
JButton start = new JButton("Start");
p.add(start);
start.addActionListener(this);
/*Close Button*/
JButton close = new JButton("Close");
p.add(close);
close.addActionListener(this);
contentPane.add(p, "South");
p.add(new JLabel ("Enter Height:"));
p.add(getHeight);
p.add(new JLabel ("Enter X Velocity:"));
p.add(velocityText);
p.add(new JLabel ("Velocity Test:")); //Change this to "Wind Speed:" after
p.add(windSpeed);
public void actionPerformed (ActionEvent e)
if (e.getActionCommand().equals("Start"))
Ball b = new Ball(canvas);
b.start();
windSpeed.setText("" + getVelocity());
else if (e.getActionCommand().equals("Close"))
canvas.setVisible(false);
System.exit(0);
public double getVelocity()
return Double.parseDouble(velocityText.getText().trim());
/*Ball Class*/
class Ball extends Thread
GameFrame vx = new GameFrame();
double getDx = vx.getVelocity();
public Ball(JPanel b)
box = b;
public void draw() //Draw ball
Graphics g = box.getGraphics();
g.fillOval(x, y, XSIZE, YSIZE);
g.dispose(); //Might not need this
/*This is how the ball will move Speed of ball*/
public void move()
if (!box.isVisible())
return;
Graphics g = box.getGraphics();
g.setXORMode(box.getBackground());
g.fillOval(x, y, XSIZE, YSIZE);
x += dx;
y += dy;
Dimension d = box.getSize();
/*Change velocity*/
dx = getDx;
if (x>= 615 || y>= 390)
dx = 0;
dy = 0;
else if(y<= 0)
dy = dy + 0.2;
else
if (x>=0)
long elapsed = System.currentTimeMillis() - start; //Current time
dx = (dx + windX + (0 * elapsed));
if (y >= 0)
long elapsed = System.currentTimeMillis() - start;
dy = ((dy + windY + (accelY * elapsed)) * 0.0005);
g.fillOval(x, y, XSIZE, YSIZE);
g.dispose(); //Possibly need to remove
public void run()
try
draw();
for (int i = 1; i <= 1000; i++) //Number of times the ball moves
move();
sleep(25); //Speed of ball
} catch (InterruptedException e)
private JPanel box;
/*Size of ball*/
private static final int XSIZE = 10;
private static final int YSIZE = 10;
/*Possition of ball*/
private int x = 0;
private int y = 300;
/*X and Y speed of ball*/
private double dx = 0; //Changed from int to double
private double dy = 0; //Vertical Distance
long start = System.currentTimeMillis(); //Computer Time
//Wind and acceleration
private static final double accelY = 9.8;
private double windX = (2 * Math.random()) + 0;
private double windY = (-7000 * Math.random()) + 0;
}Junaid wrote:
I am making a game in which a user can enter the speed of the initial velocity of a ball. My problem is that when i run the program and enter the speed of the ball in the JTextField, it doesn't actually change the speed of the ball. The ball just uses the speed that was set before the program ranFirst, from my experiences, use the JPanel's paint( Graphics ) method and the passed graphics rather than writing your own draw().
Second, and the reason your ball speed doesn't change, is that in the creation of the Ball, it makes its own GameFrame, rather than using the old one.
Change the start of Ball to:
class Ball extends Thread
GameFrame vx;
double getDx;
public Ball(JPanel b, GameFrame vx)
this.vx = vx;
getDx = vx.getVelocity()
box = b;
}and the creation of the Ball to:
public Ball makeBall() {
return new Ball( canvas, this );
public void actionPerformed (ActionEvent e)
if (e.getActionCommand().equals("Start"))
// the reason I don't say Ball( canvas, this ) here
// is that this statement is inside an ActionListener
// not a GameFrame.
// Calling a method in GameFrame will pass the right object
Ball b = makeBall();
. -
Using an int from one class in another class
I am a student writing a java program on renewable energy. Simply I have a power output which is a variable called PowerOutPut. declared as (public int PowerOutPut) I have another class which is a graphics class where I display the variable PowerOutPut on a graph, but i dont know how to call this variable in my graphics class.
if anyone can help, I would be very grateful.
ChrisBut bear in mind that it is good practice to declare your variables private (unless you need otherwise) and to provide get and set methods to access and change them.
private int myVariable = 0;
public int getMyVariable(){
return myVariable;
public void setMyVariable(int newValue){
myVariable = newValue;
}Also, class names should start with upper case and variables should start with lower case.
Good luck. -
How to transter contents of itab from one class to another...
Hello experts,
I am currently having problems on how to transfer the contents of an itab or even
the value of a variable from one class to another. For example, I have 10 records
in it_spfli in class 1 and when I loop at it_spfli in the method of class 2 it has no records!
This is an example:
class lcl_one definition.
public section.
data: gt_spfli type table of spfli.
methods get_data.
endclass.
class lcl_one implementation.
method get_data.
select * from spfli
into table gt_spfli.
endmethod.
endclass.
class lcl_two definition inheriting from lcl_one.
public section.
methods loop_at_itab.
endclass.
class lcl_two implementation.
method loop_at_itab.
field-symbols: <fs_spfli> like line of gt_spfli.
loop at gt_spfli assigning <fs_spfli>.
write: / <fs_spfli>-carrid.
endloop.
endmethod.
endclass.
start-of-selection.
data: one type ref to lcl_one,
two type ref to lcl_two.
create object: one, two.
call method one->get_data.
call method two->loop_at_itab.
In the example above, the contents of gt_spfli in class lcl_two is empty
even though it has records in class lcl_one. Help would be appreciated.
Thanks a lot guys and take care!Hi Uwe,
It is still the same. Here is my code:
REPORT zfi_ors_sms
NO STANDARD PAGE HEADING
LINE-SIZE 255
LINE-COUNT 65
MESSAGE-ID zz.
Include program/s *
INCLUDE zun_standard_routine. " Standard Routines
INCLUDE zun_header. " Interface Header Record
INCLUDE zun_footer. " Interface Footer Record
INCLUDE zun_interface_control. " Interface Control
INCLUDE zun_external_routine. " External Routines
INCLUDE zun_globe_header. " Report header
INCLUDE zun_bdc_routine. " BDC Routine
Data dictionary table/s *
TABLES: bkpf,
rf05a,
sxpgcolist.
Selection screen *
SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.
PARAMETERS: p_file TYPE sxpgcolist-parameters.
SELECTION-SCREEN END OF BLOCK b1.
*/ CLASS DEFINITIONS
CLASS lcl_main DEFINITION
CLASS lcl_main DEFINITION ABSTRACT.
PUBLIC SECTION.
Structure/s *
TYPES: BEGIN OF t_itab,
rec_content(100) TYPE c,
END OF t_itab.
TYPES: BEGIN OF t_upfile,
record_id(2) TYPE c, " Record ID
rec_date(10) TYPE c, " Record Date MM/DD/YYYY
prod_line(10) TYPE c, " Product Line
acc_code(40) TYPE c, " Acc Code
description(50) TYPE c, " Description
hits(13) TYPE c, " Hits
amount(15) TYPE c, " Amount
END OF t_upfile.
Internal table/s *
DATA: gt_bdcdata TYPE STANDARD TABLE OF bdcdata,
gt_bdcmsgcoll TYPE STANDARD TABLE OF bdcmsgcoll,
gt_itab TYPE STANDARD TABLE OF t_itab,
gt_header LIKE TABLE OF interface_header,
gt_footer LIKE TABLE OF interface_footer,
gt_upfile TYPE STANDARD TABLE OF t_upfile.
Global variable/s *
DATA: gv_target TYPE rfcdisplay-rfchost,
gv_err_flag(1) TYPE n VALUE 0,
gv_input_dir(100) TYPE c
VALUE '/gt/interface/FI/ORS/inbound/',
gv_inputfile_dir(255) TYPE c,
gv_eof_flag TYPE c VALUE 'N',
gv_string TYPE string,
gv_delimiter TYPE x VALUE '09',
gv_input_records(3) TYPE n,
gv_input_file_ctr(6) TYPE n,
gv_proc_tot_amt(14) TYPE p DECIMALS 2,
gv_prg_message TYPE string,
gv_gjahr TYPE bkpf-gjahr,
gv_monat TYPE bsis-monat.
Work area/s *
DATA: wa_itab LIKE LINE OF gt_itab,
wa_upfile LIKE LINE OF gt_upfile,
wa_footer LIKE LINE OF gt_footer,
wa_header LIKE LINE OF gt_header.
ENDCLASS.
CLASS lcl_read_app_server_file DEFINITION
CLASS lcl_read_app_server_file DEFINITION INHERITING FROM lcl_main.
PUBLIC SECTION.
METHODS: read_app_server_file,
read_input_file,
split_header,
process_upload_file,
split_string,
conv_num CHANGING value(amount) TYPE t_upfile-amount,
split_footer,
update_batch_control,
process_data.
ENDCLASS.
CLASS lcl_process_data DEFINITION
CLASS lcl_process_data DEFINITION INHERITING FROM
lcl_read_app_server_file.
PUBLIC SECTION.
METHODS process_data REDEFINITION.
ENDCLASS.
*/ CLASS IMPLEMENTATIONS
CLASS lcl_read_app_server_file IMPLEMENTATION
CLASS lcl_read_app_server_file IMPLEMENTATION.
*/ METHOD read_app_server_file - MAIN METHOD
METHOD read_app_server_file.
gv_target = sy-host.
PERFORM file_copy USING 'ZPPDCP' p_file 'HP-UX'
gv_target CHANGING gv_err_flag.
CONCATENATE gv_input_dir p_file INTO gv_inputfile_dir.
open application server file
PERFORM open_file USING gv_inputfile_dir 'INPUT'
CHANGING gv_err_flag.
WHILE gv_eof_flag = 'N'.
READ DATASET gv_inputfile_dir INTO wa_itab.
APPEND wa_itab TO gt_itab.
IF sy-subrc <> 0.
gv_eof_flag = 'Y'.
EXIT.
ENDIF.
CALL METHOD me->read_input_file.
ENDWHILE.
close application file server
PERFORM close_file USING gv_inputfile_dir.
IF wa_footer-total_no_rec <> gv_input_file_ctr.
MOVE 'Header Control on Number of Records is Invalid' TO
gv_prg_message.
PERFORM call_ws_message USING 'E' gv_prg_message 'Error'.
gv_err_flag = 1.
ELSEIF wa_footer-total_no_rec EQ 0 AND gv_input_file_ctr EQ 0.
MOVE 'Input File is Empty. Batch Control will be Updated' TO
gv_prg_message.
PERFORM call_ws_message USING 'I' gv_prg_message 'Information'.
CALL METHOD me->update_batch_control.
gv_err_flag = 1.
ENDIF.
IF gv_err_flag <> 1.
IF wa_footer-total_amount <> gv_proc_tot_amt.
MOVE 'Header Control on Amount is Invalid' TO gv_prg_message.
PERFORM call_ws_message USING 'E' gv_prg_message 'Error'.
gv_err_flag = 1.
ENDIF.
ENDIF.
ENDMETHOD.
*/ METHOD read_input_file
METHOD read_input_file.
CASE wa_itab-rec_content+0(2).
WHEN '00'.
CALL METHOD me->split_header.
WHEN '01'.
CALL METHOD me->process_upload_file.
ADD 1 TO gv_input_file_ctr.
ADD wa_upfile-amount TO gv_proc_tot_amt.
WHEN '99'.
CALL METHOD me->split_footer.
WHEN OTHERS.
gv_err_flag = 1.
ENDCASE.
ENDMETHOD.
*/ METHOD split_header
METHOD split_header.
CLEAR: wa_header,
gv_string.
MOVE wa_itab TO gv_string.
SPLIT gv_string AT gv_delimiter INTO
wa_header-record_id
wa_header-from_system
wa_header-to_system
wa_header-event
wa_header-batch_no
wa_header-date
wa_header-time.
APPEND wa_header TO gt_header.
ENDMETHOD.
*/ METHOD process_upload_file
METHOD process_upload_file.
CLEAR gv_string.
ADD 1 TO gv_input_records.
MOVE wa_itab-rec_content TO gv_string.
CALL METHOD me->split_string.
CALL METHOD me->conv_num CHANGING amount = wa_upfile-amount.
APPEND wa_upfile TO gt_upfile.
ENDMETHOD.
*/ METHOD split_string
METHOD split_string.
CLEAR wa_upfile.
SPLIT gv_string AT gv_delimiter INTO
wa_upfile-record_id
wa_upfile-rec_date
wa_upfile-prod_line
wa_upfile-acc_code
wa_upfile-description
wa_upfile-hits
wa_upfile-amount.
ENDMETHOD.
*/ METHOD conv_num
METHOD conv_num.
DO.
REPLACE gv_delimiter WITH ' ' INTO amount.
IF sy-subrc <> 0.
EXIT.
ENDIF.
ENDDO.
ENDMETHOD.
*/ METHOD split_footer
METHOD split_footer.
CLEAR: wa_footer,
gv_string.
MOVE wa_itab TO gv_string.
SPLIT gv_string AT gv_delimiter INTO
wa_footer-record_id
wa_footer-total_no_rec
wa_footer-total_amount.
CALL METHOD me->conv_num CHANGING amount = wa_footer-total_amount.
APPEND wa_footer TO gt_footer.
ENDMETHOD.
*/ METHOD update_batch_control
METHOD update_batch_control.
DATA: lv_sys_date TYPE sy-datum,
lv_sys_time TYPE sy-uzeit,
lv_temp_date(10) TYPE c.
CONCATENATE wa_header-date4(4) wa_header-date2(2)
wa_header-date+0(2)
INTO lv_temp_date.
MOVE lv_temp_date TO wa_header-date.
APPEND wa_header-date TO gt_header.
Update ZTF0001 Table
PERFORM check_interface_header USING wa_header 'U' 'GLOB'
CHANGING gv_err_flag.
Archive files
PERFORM archive_files USING 'ZPPDARC' gv_inputfile_dir 'HP-UX'
gv_target CHANGING gv_err_flag.
ENDMETHOD.
METHOD process_data.
SORT gt_upfile ASCENDING.
CLEAR wa_upfile.
READ TABLE gt_upfile INDEX 1 INTO wa_upfile.
IF sy-subrc = 0.
MOVE: wa_upfile-rec_date+6(4) TO gv_gjahr,
wa_upfile-rec_date+0(2) TO gv_monat.
ENDIF.
ENDMETHOD.
ENDCLASS.
CLASS lcl_process_data IMPLEMENTATION
CLASS lcl_process_data IMPLEMENTATION.
METHOD process_data.
CALL METHOD super->process_data.
IF NOT gt_upfile[] IS INITIAL.
ENDIF.
ENDMETHOD.
ENDCLASS.
Start of selection *
START-OF-SELECTION.
DATA: read TYPE REF TO lcl_read_app_server_file,
process TYPE REF TO lcl_process_data.
CREATE OBJECT: read, process.
CALL METHOD read->read_app_server_file.
CALL METHOD process->process_data.
Maybe you are looking for
-
Process order release reject.
Hi Experts, Question related to Make to order (MTO) I was created one sales order successfully. Then I run MRP and i got Planned sales order. After that I converted that planned sales order sa process order. When i click on release icon, my proble ar
-
How to include URL in email?
From Safari. how do I insert the current URL into an email? There's only an option to bookmark.
-
I've installed a purchased application on my second iPhone using same account. iTunes Store charged me twice for the cost of the Application. What is this?
-
Is there a scrabble game available in the mac store?
Is there a scrabble game available in the mac store?
-
Is it possible to email a song that can then be entered into iTunes on another computer? If so, how? I have an iMac with 10.8.3 and the latest iTunes. Thank you Carl