Class fails to import another class in J2SE1.4?Why?
Dear experts,
I use JSDK1.4.2.
I havenot set any classpath.
I write the following two classes.
class1.java
public class1{
public class1(){
public void showMessage(){
System.out.println("Message from class1");
I have another class "class2.java" with the following code:
import class1;
public class2{
public static void main(String arg[]){
class1 clsObj = new class1();
clsobj.showMessage();
I have stored both the classes under c:\MyFolder.
I havenot used any package and i donot want to use packages.
when I compile "class1.java" in the C:\MyFolder> , Its compiled without any problem.
But when I try to compile the second class "class2.java",It shows the error at the line
"import class1", '. expected'
Though I can use the class1 as it is without importing it into class2.java, I used this as an example to solve some other problem.
What could be wrong? Should I set the classpath?
Please help me to resolve this.
Thankx in advance
This line does not look very pretty:
public class1 {Try this instead:
public class class1 {
Similar Messages
-
Calling a class's method from another class
Hi, i would like to know if it's possible to call a Class's method and get it's return from another Class. This first Class doesn't extend the second. I've got a Choice on this first class and depending on what is selected, i want to draw a image on the second class witch is a Panel extended. I put the control "if" on the paint() method of the second class witch is called from the first by the repaint() (first_class.repaint()) on itemStateChanged(). Thankx 4 your help. I'm stuck with this.This program is for my postgraduation final project and i'm very late....
import java.awt.*;
import java.sql.*;
* This type was generated by a SmartGuide.
class Test extends Frame {
private java.awt.Panel ivjComboPane = null;
private java.awt.Panel ivjContentsPane = null;
IvjEventHandler ivjEventHandler = new IvjEventHandler();
private Combobox ivjCombobox1 = null;
class IvjEventHandler implements java.awt.event.WindowListener {
public void windowActivated(java.awt.event.WindowEvent e) {};
public void windowClosed(java.awt.event.WindowEvent e) {};
public void windowClosing(java.awt.event.WindowEvent e) {
if (e.getSource() == Test.this)
connEtoC1(e);
public void windowDeactivated(java.awt.event.WindowEvent e) {};
public void windowDeiconified(java.awt.event.WindowEvent e) {};
public void windowIconified(java.awt.event.WindowEvent e) {};
public void windowOpened(java.awt.event.WindowEvent e) {};
private Panel ivjPanel1 = null;
* Combo constructor comment.
public Test() {
super();
initialize();
* Combo constructor comment.
* @param title java.lang.String
public Test(String title) {
super(title);
* Insert the method's description here.
* Creation date: (11/16/2001 7:48:51 PM)
* @param s java.lang.String
public void conexao(String s) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:system/[email protected]:1521:puc";
Connection db = DriverManager.getConnection(url);
//String sql_str = "SELECT * FROM referencia";
Statement sq_stmt = db.createStatement();
ResultSet rs = sq_stmt.executeQuery(s);
ivjCombobox1.addItem("");
while (rs.next()) {
String dt = rs.getString(1);
ivjCombobox1.addItem(dt);
db.close();
} catch (SQLException e) {
System.out.println("Erro sql" + e);
} catch (ClassNotFoundException cnf) {
* connEtoC1: (Combo.window.windowClosing(java.awt.event.WindowEvent) --> Combo.dispose()V)
* @param arg1 java.awt.event.WindowEvent
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC1(java.awt.event.WindowEvent arg1) {
try {
// user code begin {1}
// user code end
this.dispose();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
* Return the Combobox1 property value.
* @return Combobox
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private Combobox getCombobox1() {
if (ivjCombobox1 == null) {
try {
ivjCombobox1 = new Combobox();
ivjCombobox1.setName("Combobox1");
ivjCombobox1.setLocation(30, 30);
// user code begin {1}
this.conexao("select * from referencia");
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
return ivjCombobox1;
* Return the ComboPane property value.
* @return java.awt.Panel
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private java.awt.Panel getComboPane() {
if (ivjComboPane == null) {
try {
ivjComboPane = new java.awt.Panel();
ivjComboPane.setName("ComboPane");
ivjComboPane.setLayout(null);
getComboPane().add(getCombobox1(), getCombobox1().getName());
getComboPane().add(getPanel1(), getPanel1().getName());
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
return ivjComboPane;
* Return the ContentsPane property value.
* @return java.awt.Panel
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private java.awt.Panel getContentsPane() {
if (ivjContentsPane == null) {
try {
ivjContentsPane = new java.awt.Panel();
ivjContentsPane.setName("ContentsPane");
ivjContentsPane.setLayout(new java.awt.BorderLayout());
getContentsPane().add(getComboPane(), "Center");
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
return ivjContentsPane;
* Return the Panel1 property value.
* @return Panel
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private Panel getPanel1() {
if (ivjPanel1 == null) {
try {
ivjPanel1 = new Panel();
ivjPanel1.setName("Panel1");
ivjPanel1.setBackground(java.awt.SystemColor.scrollbar);
ivjPanel1.setBounds(24, 118, 244, 154);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
return ivjPanel1;
* Called whenever the part throws an exception.
* @param exception java.lang.Throwable
private void handleException(java.lang.Throwable exception) {
/* Uncomment the following lines to print uncaught exceptions to stdout */
// System.out.println("--------- UNCAUGHT EXCEPTION ---------");
// exception.printStackTrace(System.out);
* Initializes connections
* @exception java.lang.Exception The exception description.
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initConnections() throws java.lang.Exception {
// user code begin {1}
// user code end
this.addWindowListener(ivjEventHandler);
* Initialize the class.
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initialize() {
try {
// user code begin {1}
// user code end
setName("Combo");
setLayout(new java.awt.BorderLayout());
setSize(460, 300);
setTitle("Combo");
add(getContentsPane(), "Center");
initConnections();
} catch (java.lang.Throwable ivjExc) {
handleException(ivjExc);
// user code begin {2}
// user code end
* Insert the method's description here.
* Creation date: (11/17/2001 2:02:58 PM)
* @return java.lang.String
public String readCombo() {
String dado = ivjCombobox1.getSelectedItem();
return dado;
* Starts the application.
* @param args an array of command-line arguments
public static void main(java.lang.String[] args) {
try {
/* Create the frame */
Test aTest = new Test();
/* Add a windowListener for the windowClosedEvent */
aTest.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent e) {
System.exit(0);
aTest.setVisible(true);
} catch (Throwable exception) {
System.err.println("Exception occurred in main() of Test");
exception.printStackTrace(System.out);
* Insert the type's description here.
* Creation date: (11/17/2001 1:59:15 PM)
* @author:
class Combobox extends java.awt.Choice {
public java.lang.String dado;
* Combobox constructor comment.
public Combobox() {
super();
initialize();
* Called whenever the part throws an exception.
* @param exception java.lang.Throwable
private void handleException(java.lang.Throwable exception) {
/* Uncomment the following lines to print uncaught exceptions to stdout */
// System.out.println("--------- UNCAUGHT EXCEPTION ---------");
// exception.printStackTrace(System.out);
* Initialize the class.
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initialize() {
try {
// user code begin {1}
// user code end
setName("Combobox");
setSize(133, 23);
} catch (java.lang.Throwable ivjExc) {
handleException(ivjExc);
// user code begin {2}
// user code end
* main entrypoint - starts the part when it is run as an application
* @param args java.lang.String[]
public static void main(java.lang.String[] args) {
try {
java.awt.Frame frame = new java.awt.Frame();
Combobox aCombobox;
aCombobox = new Combobox();
frame.add("Center", aCombobox);
frame.setSize(aCombobox.getSize());
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
frame.setVisible(true);
} catch (Throwable exception) {
System.err.println("Exception occurred in main() of Combobox");
exception.printStackTrace(System.out);
* Insert the type's description here.
* Creation date: (11/17/2001 2:16:11 PM)
* @author:
class Panel extends java.awt.Panel {
* Panel constructor comment.
public Panel() {
super();
initialize();
* Panel constructor comment.
* @param layout java.awt.LayoutManager
public Panel(java.awt.LayoutManager layout) {
super(layout);
* Called whenever the part throws an exception.
* @param exception java.lang.Throwable
private void handleException(java.lang.Throwable exception) {
/* Uncomment the following lines to print uncaught exceptions to stdout */
// System.out.println("--------- UNCAUGHT EXCEPTION ---------");
// exception.printStackTrace(System.out);
* Initialize the class.
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initialize() {
try {
// user code begin {1}
// user code end
setName("Panel");
setLayout(null);
setSize(260, 127);
} catch (java.lang.Throwable ivjExc) {
handleException(ivjExc);
// user code begin {2}
// user code end
* main entrypoint - starts the part when it is run as an application
* @param args java.lang.String[]
public static void main(java.lang.String[] args) {
try {
java.awt.Frame frame = new java.awt.Frame();
Panel aPanel;
aPanel = new Panel();
frame.add("Center", aPanel);
frame.setSize(aPanel.getSize());
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
frame.setVisible(true);
} catch (Throwable exception) {
System.err.println("Exception occurred in main() of java.awt.Panel");
exception.printStackTrace(System.out);
* Insert the method's description here.
* Creation date: (11/17/2001 2:18:36 PM)
public void paint(Graphics g) {
/* Here's the error:
C:\Test.java:389: non-static method readCombo() cannot be referenced from a static context
System.out.println(Test.lerCombo());*/
System.out.println(Test.readCombo()); -
Assigning object of one class to object of another class.
Hi,
How will i assign an object of one class to an object of another class?
Ex:
ClassX A=some_method();
Now how will I assign the object A of class ClassX to the object 'B' of another class 'ClassY'.In java you can only assign a object reference of one class into object reference of another class if the first class is the Second class (in other words the first class is a subclass of second class).
for example if this is a inheritance chart
Car ==========>Mercedes
"===========>Audi
then you can use
Audi a1 = new Audi();
Car c1 = a1;
or Mercedes m1 = new Mercedes();
Car c1 = m1;
but not
a1 = m1;
before assigning a variable into another variable of different class, use:
if(variable1 instanceOf ToBeAssignedIn Class){
variable2 = variable1;
example:
Audi a1;
Car c1;
if(a1 instanceOf Car){
c1 = a1;
Edited by: gaurav.suse on Apr 10, 2012 1:14 PM
Edited by: gaurav.suse on Apr 10, 2012 1:15 PM -
Class can't find anothe class in same directory.
Hi
I'm using javac and appletviewer and I keep getting this strange reaction.
I've got a couple of classes, one extends the other. ie:
class a
class b extends a
Now when I compile b it says it cannot find class a. Both of these java files are in the same directory. Class a compiles fine on its own but I can't compil b.
Also, when compiling a with the statement:
package c
as the first statement and then trying to run the compiled class in the appletviewer, I get the following error:
java.lang.NoClassDefFoundError: a (wrong name: c/a)
The Applet window comes up but with applet not initialised.
Can anyone help with this? I purposely didn't put up the code because I figured it would be unnecessary.
Thanks
allanYep, that solved the compiling error. Thanks.
Any ideas about the applet viewer problem? Or where I can look for an answer?
allan -
How to import a class, which is not in a package?
Hi all,
I have the following problem:
A class A is not in a package. In another class B, which is in a package (let's say package X) I want to use the class A. Without importing the class A, I get the error "Cannot resolve symbol".
Using the import statement import A; gives the error ". expected".
How can I import that class?
Best wishes to all ...
Heiko> I have the following problem:
A class A is not in a package. In another class B,
which is in a package (let's say package X) I want to
use the class A. Without importing the class A, I get
the error "Cannot resolve symbol".
I think not putting a class in a package is a bad practice. Avoid that. -
ABAP Objects : calling one method from another class
Hi,
Can you please tell me how to call method from one class or interfce to another class.The scenario is
I have one class CL_WORKFLOW_TASK, this class have interface IF_WORKFLOW_TASK & this interface have method IF_WORKFLOW_TASK~CLOSE. Now my requirement is ,
There is another class CL_WORKFLOW_CHAIN ,this class have interface IF_WORKFLOW_CHAIN & this interface have method IF_WORKFLOW_CHAINCLOSE_ALL_PREDECESSORS. Now i have to write my code in this method but i have to use IF_WORKFLOW_TASKCLOSE method for closing the task.
Can you please give me the code for the above .
Please waiting for reply.Hi,
You can use the concept of INHERITANCE in this scenario.By using this concept, you can call all the public and protected methods of class CL_WORKFLOW_TASK in the required calss CL_WORKFLOW_CHAIN as per your requirement.
Go through the Introdctory(INHERITANCE) programming from this SAPHELP link.
http://help.sap.com/saphelp_nw70/helpdata/en/1d/df5f57127111d3b9390000e8353423/content.htm
I hope, it will help in you inresolving your problem.
by
Prasad GVK. -
Referencing a function in a class from another class
For example : I got the following situation
class main {
classOne one;
classTwo two;
public main {
one = new classOne();
two = new classTwo();
class classone {
private int i = 5;
public classone {
public count() {
System.out.println(i+ getJ());
class classtwo {
private int j = 15;
public classtwo {
public int getJ() {
return J;
Is this possible to reference a method from the same instance to which main is pointer, because when i do
classTwo two = new classTwo();
two.getJ();
in classOne, i'm referencing another instance.
I know there exist something like friends in java, but i'm seeking for a more "nice" solution
thxI wasn't sure if I understand what you're looking for. But if I understand well...
Well, that won't work that way. However, you may use nested classes. But that brings you to a development question. Nested classes are supposed to help the embedding class. Anyhow, here's a way it might work:
class MainClass {
ClassOne one = new ClassOne();
ClassOne two = new ClassTwo();
void methodOfMain() {
class ClassOne {
public void oneMethod() {
two.twoMethod();
methodOfMain();
class ClassTwo {
public void twoMethod() {
methodOfMain();
}Alternatively, you may consider passing the instance of ClassTwo to the method of ClassOne, which will use this instance to access the methods, if you cannot use nested classes.
But you cannot use the methods of another class directly, unless that another class is the embedding class (calling of methodOfMain in the code above). You must use an instance of the class (or the class name, in case of static methods) to reach the methods.
Is this what you're seeking for? -
Problem When Import Java Class -compilation error
Hi all
I made a java class that has methods to return Screen width and Height .
package tarek;
import java.awt.Dimension;
import java.awt.Toolkit;
public class Screen
Dimension dim ;
public Screen()
dim = Toolkit.getDefaultToolkit().getScreenSize();
public double getWidth()
double w = dim.getWidth();
return w;
public double getHeight()
double h=dim.getHeight();
return h;
I made the jar file " screen.jar" and make it ready to use in form builder
I opened form builder and make import java class (From program>import java class>choose the class anc click import)
The class now imported successfully and the PL/SQL package body is:
PACKAGE Screen /* tarek.Screen */ IS
-- DO NOT EDIT THIS FILE - it is machine generated!
-- Constructor for signature ()V
FUNCTION new RETURN ORA_JAVA.JOBJECT;
-- Method: getHeight ()D
FUNCTION getHeight(
obj ORA_JAVA.JOBJECT) RETURN NUMBER;
-- Method: getWidth ()D
FUNCTION getWidth(
obj ORA_JAVA.JOBJECT) RETURN NUMBER;
END;
Now I made a button on the form and i WRITE THIS CODE TO INVOKE THE CLASS on when_button_pressed
DECLARE
vScreen_Class ORA_JAVA.JOBJECT;
BEGIN
vScreen_Class := SCREEN.NEW;
END;
My problem is I have compilation error
error 306 AT LINE 5 , COLUMN 25
wrong number or types of argument in call to "NEW"
I do not know what is the reason of this compilation error?
Is it because the method in java return "double datatype" while in oracle return "number datatype"
Please help
Edited by: [email protected] on Dec 28, 2009 10:24 AMSarah, I ca not move my thread to JDeveloper because it is not java issue. The problem is with my PL/SQL code and the way I make Import Java class to forms Builder. The Java code is OK.
Andreas Thank you so much for replying. In fact I made a full compile "Ctrl+Alt+K". but still error
The following is the package Body
PACKAGE BODY Screen IS
-- DO NOT EDIT THIS FILE - it is machine generated!
args JNI.ARGLIST;
-- Constructor for signature ()V
FUNCTION new RETURN ORA_JAVA.JOBJECT IS
BEGIN
args := NULL;
RETURN (JNI.NEW_OBJECT('tarek/Screen', '()V', args));
END;
-- Method: getHeight ()D
FUNCTION getHeight(
obj ORA_JAVA.JOBJECT) RETURN NUMBER IS
BEGIN
args := NULL;
RETURN JNI.CALL_DOUBLE_METHOD(FALSE, obj, 'tarek/Screen', 'getHeight', '()D', args);
END;
-- Method: getWidth ()D
FUNCTION getWidth(
obj ORA_JAVA.JOBJECT) RETURN NUMBER IS
BEGIN
args := NULL;
RETURN JNI.CALL_DOUBLE_METHOD(FALSE, obj, 'tarek/Screen', 'getWidth', '()D', args);
END;
BEGIN
NULL;
END;
--------------------------------------------------------------------------------- -
Import other class from other class file
let say, i got class student in the file name "student.class".
my main program is school.class.
how to import student.class into school.class so i can use student class.?
what is the directory i had to store the 2 file?School.java:
class School {
Student a, b, c;
public static void main(String[] args) {
a = new Student("fred","foobar");
b = new Student("fred","barbaz");
c = new Student("fred","bazqux");
System.out.println("Student a is "+a.name+" "+a.surname);
System.out.println("Student b is "+b.name+" "+b.surname);
System.out.println("Student c is "+c.name+" "+c.surname);
class Student {
String name, surname;
public Student(String nam, String sur) {
name = name;
surname = sur;
} -
Importing a class from another context?
Hi JSP techies,
Im using RESIN and having a simple problem of figuring out how to import classes from another context, if Im using the right word.
ie.
My .jsp files are under $home/resin/doc/test dir. And in the jsp file, I would like to import a servlet class or a plain java class. But the servlet classes and all other classes are located under $home/resin/webapps/project/WEB-INF/classes/a/b/c
Hence when I say
<% page import="a.b.c.*" %>
I get an error saying "a" not found.
1. When I say "servlet classes are in a different CONTEXT", is that right? or is it just another directory?
2. How can I make the jsp file import the classes from the servlets class path?
Note: Ofcourse, when I copy the package to the
$home/resin/doc/WEB-INF/classes dir, everything works fine. But thats simply not an efficient way to get around. Could anyone clear my doubts on this regd.?
Thanks in advance.
ArunOh... I get it now. I'm sorry, I had you poorly misunderstood. You are trying to import servlets from another web app or servlet context. I would suggest you put servlets that are common to all web apps in the system classpath and not tie them to any particular web app. In other words create a package directory structure from the system's root directory or any where outside of any web apps and point the system classpath to the beginning of that directory structure. I have a similar thing going with Tomcat. I have a folder in my root called Java_Class which is in my classpath. I build all common utilities in this directory. So I have a com/craig/web structure that holds my AppServlet which is in package com.craig.web. This servlet is visible to all web apps via the Windows classpath. Servlets particular to an application like say an MusicOrderProcess servlet would reside in a package under the webserverhome/webapps/MusicStore/WEB-INF/classes directory where webserver home is the home directory of the webserver you are using. I've tested this across webservers as well (orionserver and Tomcat) and it works.
From the prompt you include in your posts I am guessing that you are running on UNIX. Move your common servlets out of their respective web apps and into a common directory structure. Configure the UNIX $CLASSPATH (or is it $classpath?) environment variable to point to this sturcture and you'll be on your way!
Post again if you have more questions! -
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()) -
this is the class that calls another class called cuboid
package WindowsApplication1;
* Summary description for Cuboid.
//Import the classes to allow the use of the array, iterator and listiterator
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class DisplayCuboidValues
public static void main(String args[])
//Create the array list
ArrayList VolumeList = new ArrayList();
//Create the counter to loop 4 times and get 4 different volumes. Modify the counter
//if you need a different values
int Counter = 1;
//Initialize the counter to loop 4 times in order to get the 4 objects
while (Counter < 5)
Cuboid mp = new Cuboid(2, 4, 3);
//Add the values to the array
VolumeList.add(mp);
// get the volume again via accessor method(Optional)
//int Volume = mp.Volume();
//System.out.println(Volume);
//Increment the counter to obtain a new value in the array
Counter = Counter + 1;
// Retrieve iterator to the radiuslist
Iterator itr1 = VolumeList.iterator();
while (itr1.hasNext())
// call Cuboid.toString()
System.out.print(itr1.next());
System.out.println();
}this is the cuboid class
package WindowsApplication1;
* Summary description for Cuboid.
public class Cuboid
private final int length, width, height;
//1st contructor with 3 arguments
public Cuboid(int length, int width, int height)
this.length = length;
this.width = width;
this.height = height;
//2nd constructor with no arguments
//I BELIEVE THIS PUBLIC CUBOID IS THE ONE THE PROVOKES THE ERROR. BUT I CAN NOT DELETE IT BECAUSE I NEED ANOTHER PUBLIC CUBOID. SO IDK WHAT TO DO......
public Cuboid()
this.length = length;
this.width = width;
this.height = height;
public String toString() {
return "This cuboid has length x, width y, height z, and has volume of v where X=" + length + " " + "Y=" + width + " " + "Z=" + height + " " + "Volume=" + length * width * height + ". -- ";
//Method to calculate the Volume
public int Volume()
return length * width * height;
}This is what i have done. I have created a project named ths(which i do not use it at all). Then, i created one file called DisplayCuboidValues under ths. Then i created the file Cuboid under ths too. But it gives me errors. like this one:
init:
deps-jar:
Created dir: C:\Documents and Settings\Owner\ths\build\classes
Compiling 1 source file to C:\Documents and Settings\Owner\ths\build\classes
C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\Cuboid.java:25: variable length might not have been initialized
this.length = length;
*^*
C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\Cuboid.java:26: variable width might not have been initialized
this.width = width;
*^*
C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\Cuboid.java:27: variable height might not have been initialized
this.height = height;
*^*
Note: C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\DisplayCuboidValues.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
*3 errors*
BUILD FAILED (total time: 0 seconds)
Any help you can give me will be appreciated. Thanks.yeah. you are right in that. so that means that i have to get rid of it??. because i will need it. and the values assigned to them is in the first class that calls the second class look:
package WindowsApplication1;
* Summary description for Cuboid.
//Import the classes to allow the use of the array, iterator and listiterator
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class DisplayCuboidValues
public static void main(String args[])
//Create the array list
ArrayList VolumeList = new ArrayList();
//Create the counter to loop 4 times and get 4 different volumes. Modify the counter
//if you need a different values
int Counter = 1;
//Initialize the counter to loop 4 times in order to get the 4 objects
while (Counter < 5)
*//HERE IS WHERE I AM PROVIDING THE OTHER CLASS WITH VALUES. THEREFORE IT SHOULD SENT THOSE VALUES TO MY CLASS CUBOID AND RETRIEVE THE ANSWER TO FOLLOW THE REST OF THIS CODE.*
Cuboid mp = new Cuboid(2, 4, 3);
//Add the values to the array
VolumeList.add(mp);
// get the volume again via accessor method(Optional)
//int Volume = mp.Volume();
//System.out.println(Volume);
//Increment the counter to obtain a new value in the array
Counter = Counter + 1;
// Retrieve iterator to the radiuslist
Iterator itr1 = VolumeList.iterator();
while (itr1.hasNext())
// call Cuboid.toString()
System.out.print(itr1.next());
System.out.println();
} -
Importing Java classes in Forms 6i
Hi
When I try to import java classes using the option available in forms 6i,I get the following error
PDE-UJI001 Failed to create the JVM.
ne clue?
Thanks
GangsYou have installer the JDK 1.2 (This software located in a Sun Microsystems Web Site), and you have a configure the your PATH:
PATH=%PATH%;< path your JDK installed >;
If you have Designer 6i installed in your machine, then your Enviromento Variable PATH = PATH=< path your JDK installed >;%PATH%;
After configure the PATH, you have a create another Enviroment Variable CLASSPATH with:
Example:
CLASSPATH=C:\oracle\designer\TOOLS\COMMON60\JAVA\IMPORTER.JAR;c:\jdk1.2.2;
Test your Forms 6i. -
Calling paintComponent(Graphics g) in another class
Dear Friends,
I have a class (Class Pee) where I implemented the paintComponent(Graphics g) and another class (Class Bee) where I generate some datas. My intention is to call the paintComponent(Graphics g) method in class Pee at class Bee to make use of the generated data to draw some figures.
I imported java.awt .Graphics, java.awt.Graphics2D, Polygon and geom and declared Graphics2D g2d = (Graphics2D) g; as well, but still when I call paintComponent (Graphics g) it fails to recognize the g. What is actually wrong.
See code:
Class Pee
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JPanel;
public class Pee extends JPanel{
private int offset;
public void paintComponent(Graphics g, int b[], int c[]){
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
this.setBackground(Color.white);
Class Bee
import java.io.*;
import java.util.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.*;
import java.awt.Polygon;
import Graphic.Pee; //importing Pee Class
public class Bee{
int x[];
int y[];
// other variable declaration
public Bee{
x = new int [5];
y = new int [5];
Pee dr = new Pee();
Graphics2D g2d = (Graphics2D) g;
//code to generate data
dr.paintComponent(g,x,y);
}It always say that "g" cannot be resolved. Please how do I get over this.
Thanks,
Jona_TSwing calls the paintComponent method when we ask a component to draw itself. We do this by
calling its repaint method. So the general approach is to change the data in the component
that does the graphics for us and then ask the component to repaint itself. Swing does the
rest. One benefit of this way of doing things is that the graphic component keeps the data
and can render all or any part of it at any time. Trying to get a reference to the
components graphics context from within another class and using it to draw graphics in the
graphics component prevents this and the foreign class event code can never know when the
graphics component needs to be re–rendered.
So the idea is to keep the graphics/rendering component independent from the event code. The
event code controls the state (member variables) in the graphics component and tells it when
to re–render itself.
There are a lot of (creative) ways of putting these things together. Here's an example.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Random;
import javax.swing.*;
public class CallingGraphics implements ActionListener {
GraphicComponentClass graphicComponent;
DataGenerationClass dataGenerator = new DataGenerationClass();
public void actionPerformed(ActionEvent e) {
Point2D.Double[] data = dataGenerator.getData();
graphicComponent.setData(data);
private JPanel getGraphicComponent() {
graphicComponent = new GraphicComponentClass();
return graphicComponent;
private JPanel getLast() {
JButton button = new JButton("send data to graphics");
button.addActionListener(this);
JPanel panel = new JPanel();
panel.add(button);
return panel;
public static void main(String[] args) {
CallingGraphics test = new CallingGraphics();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test.getGraphicComponent());
f.getContentPane().add(test.getLast(), "Last");
f.setSize(400,300);
f.setLocation(200,200);
f.setVisible(true);
class GraphicComponentClass extends JPanel {
Ellipse2D.Double[] circles = new Ellipse2D.Double[0];
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for(int j = 0; j < circles.length; j++) {
g2.draw(circles[j]);
public void setData(Point2D.Double[] p) {
double w = getWidth();
double h = getHeight();
double dia = 75.0;
circles = new Ellipse2D.Double[p.length];
for(int j = 0; j < circles.length; j++) {
double x = p[j].x*(w - dia);
double y = p[j].y*(h - dia);
circles[j] = new Ellipse2D.Double(x,y,dia,dia);
repaint();
class DataGenerationClass {
Random seed = new Random();
public Point2D.Double[] getData() {
int n = seed.nextInt(25);
Point2D.Double[] locs = new Point2D.Double[n];
for(int j = 0; j < n; j++) {
double x = seed.nextDouble();
double y = seed.nextDouble();
locs[j] = new Point2D.Double(x, y);
return locs;
} -
Getting values from a JTextField on a JPanel in another class
I have created a class which extends a JPanel and added a JTextField to it, which has an addActionListener for getting the values typed in the JTextField. I want to use the class created in another class and retrieve the values typed in the JTextField, so how do i go about that? I have the class created below so the problem is how to retrieve content of val[val] in another class?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TextFieldChooser extends JPanel{
int val;
public TextFieldChooser(String str){
val = 0;
setLayout(new FlowLayout());
add(new JLabel(str));
JTextField txtf = new JTextField(5);
txtf.addActionListener(new TextFieldListener());
add(txtf);
}//end constructor
private class TextFieldListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
val = Integer.parseInt(e.getActionCommand());
}//end text field listener
public int getValue(){
return val;
}//classThe problem is which listener can be programmed to handle the event performed on the class TextFieldChooser in the other class?
I have created a class which extends a JPanel and
added a JTextField to it, which has an
addActionListener for getting the values typed in the
JTextField. I want to use the class created in
another class and retrieve the values typed in the
JTextField, so how do i go about that? I have the
class created below so the problem is how to retrieve
content of val[val] in another class?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TextFieldChooser extends JPanel{
int val;
public TextFieldChooser(String str){
val = 0;
setLayout(new FlowLayout());
add(new JLabel(str));
JTextField txtf = new JTextField(5);
txtf.addActionListener(new TextFieldListener());
add(txtf);
}//end constructor
private class TextFieldListener implements
s ActionListener{
public void actionPerformed(ActionEvent e) {
val = Integer.parseInt(e.getActionCommand());
}//end text field listener
public int getValue(){
return val;
}//class
Maybe you are looking for
-
Cost budget report in local currency
Hello all, I would like to use a statistical project to link maintenance costs to a budget that is maintained in PS. The functionality is all there. i'm now trying to find a proper report. Currently I'm doubting between 2 options: Option 1: CJ30: bud
-
Deleting line items in sales order.
Hi All, I got as issue while creating the order. issue: I try creatin an order by deleting some of the line items and the customer got the credit check. when i tried chek in the debug mode the deleted line items are not reflecting in the internal tab
-
My data at the bottom. I never had issues with Flashplayer (e.g., I also run the entire CS4 suite w/o issue). After the newest, suggested upgrade (chosen after it was automatically offered) to the most recent version (see subject line), I notice on y
-
Unable to Delivery Special Stock Early
Please consider the following scenario: I am using a material that has a Planned Delivery time of 10 day in MM. When I put this item on a sales order, I am changing the Item Category to TAB so that the schedule line uses an Individual Purchase Order
-
I have recently burned loads of cds to itunes in readiness to transfer to ipod nano When sorting by albums I find some tracks have not been associated with the correct album How can I move tracks to the correct album>? Thanks