Import class without package
hellow, i have a web aplication named test , and i have a class named conexion
when i import a package "pack" with the class conexion, not problem (test/WEB-INF/classes/pack/conexion.class) <% import="pack.* " %> but when i have only the class conexion WITHOUT package (test/WEB-INF/classes/conexion.class) and i import <%import ="conexion" %> i have problem ("The import conexion cannot be resolved") and when i not import the class i have problem (conexion cannot be resolved to a type) , my question is:
how to i import a class without package in JSP , and if the test/WEB-INF/classes is in the classpath when compile the servlet , why the tomcat not found the class conexion?
(tomcat 5.5.20 , jdk 1.5.09 , vim)
thank
(Sorry my english , i'm from Chile)
Hi I am hosting my JSP application with Resin 2.17 which uses classes directly in JSP code (not packages). To make this work I had to specify the classpath in Resin.conf and it worked.
My problem is getting this to work with TomCat or any other application server that will allow me to debug my project in Eclipse or NetBeans IDE. (I have yet to find an IDE that Supports debugging JSP/Java code running on Resin - so I want to switch my application server but I am not sure how to configure my classpath for the application servers to look for java classes in the specified directory just like I did with Resin.
Similar Messages
-
Not allowed to import classes without package names?
Hi,
I have a few questions on Packages and importing?
1. Is the following true that it is illegal to import classes in the same package as the current class, will this cause a comilation error? If this is the case where in the Java Language specification is this actually written as I could not find it?
2. This has probably been answered by question 1 but if I have 2 classes in the same package and if I import 1 of the classes into the other class, is it illegal to import it by just using the class name and not the package name as well, ie
if the package name is ie.tcd
and the 2 class names are exp1.class and exp2.class, can I do this in class 2
package ie.tcd;
import exp1;
public class exp2 {
3. Is it illegal to import classes that are not explicitly part of any package or must a class be part of a package to be imported. I read somewhere that while this was always illegal it is only after jdk 1.4.2 that this is being enforced? If this is the case where in the Java Language specification is this actually written as I could not find it either?
Thanks very much for any help,
JohnWas just also wondering, 1 other thing, I am looking
at someone elses code they have 2 classes (Class A
and Class B) in the same package (pkg). The person
imports class A into B:
package pkg;
import A;
public class B {
Is this legal code (or was it ever)?Not if A is really in pkg.A. If there is an A in the unnamed package it was legal, or at least it was understood by the compiler, and now it isn't (to both).
Can you import or is there a point in importing a class in the same
package?Only by naming the package in the import statement. If the current and the import statement are in the same package the import is redundant.
If there is a point would you import just be
using the class name (this would be illegal after jdk
1.4) or should you use the whole package name even
though it is in the package anyways?As I understand it you must always use the whole package name in imports. -
Classes without packages not accepted by ejbc compilation ?
Hey guys ...
I noticed something which I found unusual...I mite be missing something out here
When ejbc generates the Bean IMPL class , it does not put any import statements
in the generated java file but references all the classes in the Bean with their
absolute path ...
Now ..I have a 3rd-party jar which does not have certain classes in packages...and
I reference these classes within my Session Bean...the session bean compiles properly
..but when ejbc happens and the Impl class gets generated with the absolute path
and no imports...the compiler expects to find all these 3rd-party classes without
packages within the current session bean package itself which it will not..and
hence throws all sorts of "cannot resolve symbol" errors...
Does this mean that within my EJB beans I can never reference classes without
packages or is there something I am missing..?
Thanx,
KrishRob ,
I agree with u that giving classes without package is not a good practise..but
Itz got a history which believe it or not stems from another weblogic problem(related
to webservices..)
anywayz..that is another issue alltogether...
I don't think this bug is fixed...coz I checked a WLS70 Impl and it is still generating
the IMPL without the imports...
But can u clarify..what u wud mean by "fixing the bug" ..does it mean that the
Impl would start putting the imports..?
Thanx,
Krish
Rob Woollen <[email protected]> wrote:
I recall this bug being reported before. You might try the latest
service pack and see if it's been fixed already. Otherwise, you'll have
to contact [email protected]
FWIW, it's quite disturbing that a 3rd party would give you a jar
without a package.
-- Rob
Krishnan Venkataraman wrote:
Hey guys ...
I noticed something which I found unusual...I mite be missing
something out here
When ejbc generates the Bean IMPL class , it does not put any import
statements
in the generated java file but references all the classes in the Bean
with their
absolute path ...
Now ..I have a 3rd-party jar which does not have certain classes in
packages...and
I reference these classes within my Session Bean...the session bean
compiles properly
..but when ejbc happens and the Impl class gets generated with the
absolute path
and no imports...the compiler expects to find all these 3rd-party
classes without
packages within the current session bean package itself which it will
not..and
hence throws all sorts of "cannot resolve symbol" errors...
Does this mean that within my EJB beans I can never reference classes
without
packages or is there something I am missing..?
Thanx,
Krish -
import java.util.*;
import java.util.ArrayList,java.uitl.HashMap;
What difference it makes to the performance of a class
file when we import a specific class or an entire packageFor a great Q & A on this very question:
http://www.javaworld.com/javaworld/javaqa/2001-04/01-qa-0406-import.html?
Here is the quoted information:
"Q. Does importing an entire package cause any runtime or compile time overhead? For example, does:
import java.util.*
compared with:
import java.util.Vector
cause any added overhead?
A. In answering your questions a few definitions are helpful:
Imports of the type java.util.Vector; are referred to as single type import
Imports of the form java.util.*; are referred to as import on demand
Both import on demand and single type import are passive mechanisms. As passive mechanisms, import loads information about the package and types only when it is needed. Indeed, the compiler will load this information only when a type is actually used, not when it is simply imported. The import simply tells the compiler where to look when it actually needs a type.
So no, importing an entire package produces no more overhead than importing a specific type.
That being said, it is generally regarded as bad practice to import an entire package using import on demand. Sometimes the number of imports may be large. However, you can quickly look at the list and know what classes the importing class uses. Such a list of imports can provide important documentation to someone unfamiliar with the code. " -
How to import outer classes into package inner classes?
Hi, hope you all under stand my question. Sample as below:
import A.*;
public class ClassA{
public ClassA{
ClassB.CA = this;
package A;
public class ClassB{
public static ClassA CA; //Problem Here
}As the sample above, i cannot declare public static ClassA CA in ClassB. Any way I can solve this? Can I import ClassA into package A? Thanks.
Edited by: ocboon8 on Apr 6, 2008 6:50 AMA class that is in a package cannot access a class that is not in a package.
db -
Referencing classes outside package definition
Hi,
I have a strange problem, and I dont know if its a limitation of Java or my IDE (Intellij IDEA using java 1.4.1).
Basically I have a package structure
/classes/com/foo/MyClass.java
now from MyClass, I want to access another class file AnotherClass.java that has no package structure (and I can't change this). So I copied it to the /classes directory.
However, when I try to compile I get a "cannot resolve symbol" error. The IDE wont let me put "import AnotherClass" in the import section.
I'm confused! can anyone help? All I'm trying to do is reference a class "backwards" from the current package
cheersThe proprietry dll I have has already been compiled,
and has a reference to a Java class that performs the
appropriate JNI call. Thsi jva class has no package
structure.Well, then yes I'd suppose you are painted into a corner. Looks to me the no-package class should have been put into a package in the first place, as now you cannot reference that class from other classes that are in packages. Back to what I said earlier, writing classes without packages is a "bad" practice. -
Importing class from default package of a JAR
I want to create objects of a class contained in a JAR. The JAR has many classes in numerous packages, however the class that I want to use is in the default package. I'm using eclipse and have added the JAR to the build path, but eclipse complains that the class name cannot be resolved. Is there some way to specify an import statement to look in the default package of a particular JAR? Any advice is appreciated.
jg2009 wrote:
I was under the impression that classes without a defined package were technically considered to be part of the so-called default package. But, in answer to your question, yes this class does not appear to part of any package.
Just to provide so additional information, the class that I want to instantiate is an Applet, so it is designed to be called from an html object tag, and have access to all of the other classes in its JAR. There is a system that provides access to underlying data via the following components: html form <-> javascript <-> applet <-> serverlets <-> data
I want to automate certain data operations, but the only way to access the underlying data is via the applet. Am I out of luck, or is there some way that I can instantiate the applet?All jverd said is right, assuming it is your code and you can change it: basically move everything to a package. But I think your problem is that the jar is a 3rd party jar and you cannot change it. If this is the case, you can use the 'default package' (the terminology is correct) by having your own class(es) in the default package or by using reflection (last time I tried reflection would work). Both are rather bad solutions, but if you really, really want...
Note: Java actively discourages the use of the 'default package' and more so recently, this is why I am not even sure that reflection would still work. -
Importing classes, package, Jamlab, JAMA
Hello:
I am using, inside a JSP, a modified version of this code --> http://www.developer.com/java/other/article.php/806711, which uses a package named JAMA and Jamlab(to work with matrix) --> http://www.developer.com/java/other/article.php/762441
It is already recognizing the JAMA package (basic linear algebra package), after I added the Jama.jar file path to the CLASSPATH.
I was trying to import the Jamlab classes and I thought that I could do the same: add to the CLASSPATH the Jamlab.jar path.
The download did not come with a .JAR file, I did it using the JAR command: adding the classes to it. I already checked that the classes are actually inside the .JAR, not in a sub-folder.
The compiler is not recognizing a method which is found inside the Jamlab package:
//Create matrix of the coefficients.
polyCoeffMatrix = new Matrix(JElmat.convertTo2D(polynomialCoefficients));
"JElmat cannot be resolved" is the error message.
The import directive of my JSP page:
<%@page import="java.io.*,java.lang.*, java.util.*, java.awt.*, java.awt.image.*, Jama.*, Jama.util.*, jamlab.*, jamlab.JElmat.*"%>Any help is extremely appreciated!Yes they are in the same folder with 'package graphs;' in the 1st line,
i've tried with and without package.class to no avail
the exact errors i'm getting are
without the package in front
error: File .\CustomLabel.class does not contain type CustomLabel as expected, but type graphs.CustomLabel. Please remove the file or make sure it appears in the correct subdirectory of the class path
with the graphs.CustomLabel i get the following errors
error: Invalid class File formate: .\graphs\CustomLabel.class, wrong version: 46, expected 45
2nd error: Class graphs.CustomLabel not found in import. -
i am currently developing a flash movie with no graphics at
the moment. It is being done with a lot of classes and packages,
many of the AS classes import the same packages as well. I have
many linked movie clips to those classes.
The problem is that when i compile it takes quite a long
time. I want to know if there is a way to have a single file for
all my classes (like an include file) as opposed to having a dozen
import lines of code in each AS script.I'm a newbie too, but I thought I would give you this URL. It was extremely helpful when I began using packages. I hope it helps.
http://developer.java.sun.com/developer/onlineTraining/new2java/divelog/part1/page9.jsp -
How can I import my class or package in JSP?
Hello.
I develop jsp. When I assign variables in jsp, everything work fine. For Example:
connStr="jdbc:oracle:thin:@191.168.0.1:1521:orcl";
But I want put some variables inside class or package, so using text editor I created and compiled package:
package Pack1;
public class Test1 extends java.lang.Object {
public static void main(String[] args) {
String ConnStr = "jdbc:oracle:thin:@191.168.0.1:1521:orcl";
or class
class Test1 {
public static void main(String[] args) {
String connStr = "jdbc:oracle:thin:@191.168.0.1:1521:orcl";
But as soon as I put in my jsp line
<%@ page import="Test1" %> or <%@ page import="Pack1.*" %>
I always have an error.
JSP Error:
Request URI:/DateN/search/Search.jsp
Exception:
oracle.jsp.provider.JspCompileException:
Errors compiling:e:\orant\oem8i\apache\apache\htdocs\daten\_pages\_daten\_search\_Search.java
C:\orant\oem8i\apache\apache\htdocs\daten\_pages\_daten\_search\_Search.java:12: Package DateN not found in import.
import Pack1.*; (or Test1)
^
1 error
I using OEM2.2 with Apache-Server under Win2000. I put my classes:
Test1 in package: in folder: C:\orant\oem8i\Apache\Apache\htdocs\WEB-INF\classes\Pack1
If just class, when just in folder: C:\orant\oem8i\Apache\Apache\htdocs\WEB-INF\classes
If I using just class, when I put just in folder: C:\orant\oem8i\Apache\Apache\htdocs\WEB-INF\classes.
Im stack. Anybody can help?
Thank you.Another way. You can use a USB flash drive & the camera connection kit.
Plug the USB flash drive into your computer & create a new folder titled DCIM. Then put your movie/photo files into the folder. The files must have a filename with exactly 8 characters long (no spaces) plus the file extension (i.e., my-movie.mov; DSCN0164.jpg).
Now plug the flash drive into the iPad using the camera connection kit. Open the Photos app, the movie/photo files should appear & you can import. (You can not export using the camera connection kit.)
Secrets of the iPad Camera Connection Kit
http://howto.cnet.com/8301-11310_39-57401068-285/secrets-of-the-ipad-camera-conn ection-kit/
Cheers, Tom -
Importing classes/packages
Does importing an entire package cause the classloader to load ALL the classes in that package into memory or are they loaded only on demand?
Suppose package called MyPackage.
import MyPackage.* - Does this cause all the classes to be loaded into memory ?Here's some more info on the 'import' statement:
http://developer.java.sun.com/developer/TechTips/2000/tt0110.html#tip2 -
Importing packages vs importing classes
What impact does it have if I import a complete package like:
import java.util.*
or import the classes that I need seperately like
import java.util.Vector;
import java.util.Collection;
import java.util.Iterator;Nothing as far as Java is concerned, the compiler only uses what it needs, so there is no efficiency or size considerations.
However, when you have to modify or debug a program that someone else wrote - which has only package imports - you will curse her/him!
So, class imports are by far the better choice. -
Import Statement without ID Specification
There is an import statement
IMPORT tab g_acc_tab FROM MEMORY.
While UCChecking it.. it saying that
import statement without id specification is only used for the sake of r/2 ......
Can i Comment it ? If so won't my application go into dump while running on 6.0cc???It has to do with packages. Most java classes are in a package, the name of which must conform to its place on the filesystem relative to the classpath. By that I mean that if you have com.mystuff.One.java, it must be in a folder com/mystuff where com is located somewhere in the classpath.
What you've done is a little different. I'm assuming a couple of things:
1. you have no package declaration at the top of one.java or two.java
2. you have the current directory "." in your classpath.
Java has the concept of the "default package", which covers classes without a declared package, and in your case is the current directory.
So when you're in c:\sourcefolder and run the compiler, then "."="c:\sourcefolder", and that directory is part of the default package. No import statements are necessary for classes that are in the same package. This is why two.java can call methods in one.java without an import statement.
When you run your jsp, the "current directory" part of your classpath is not c:\sourcefolder, but some other value (probably the directory you start your jsp engine from) You will have to import all non-java-library classes because the jsp itself becomes a java class, with a package that is determined by the jsp engine. -
Importing classes confusion AS3
I must admit, I don't know Actionscript 3.0 extremely well but I know my way around it and am able to get by as a designer.
I'm just wondering if classes should ALWAYS be imported. The reason I ask is because sometimes I don't import classes but my Actionscript still works without any problems.
Just wondering if anyone could shed some light on this please?
ThanksAre you using custom classes? If so then all of the ones you use will be required.
So suppose you have in your code:
var myInstance:SomeClass = new SomeClass();
Then at the top you should add
import com.mydomain.somePackage.SomeClass;
Or if you are using packages like TweenLite or such. Even if you have added that to your classpath and it works without the import statement, it would be a surprise if you move it to another machine that doesn't have that installed.
And of course the best way to find out is to have a problem where something goes wrong. That is really all that separates the noobs from the "pros" -- we have made a lot more mistakes than you've even thought of yet! -
Importing classes in Jsdk 1.4.2
Hi,
I have two swing applications that run perfectly well when compiled and run. But then I am trying to include these two programs as two tabbed panes in a third program.
I try to import classes from the other two programs using a simple import statement. But when I compile it the compiler return an error statement.
I tried putting a package line in both the programs and tried importing it as a package in the third one and it says invalid package name.
Can anybody help.
Thanks in advance.OK here is the code. This is a example code from the book Java2 from scratch
First file
PortfoilioTotalsPanel.java
// Import the packages used by this class
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
// PortfolioTotalsPanel Class
public class PortfolioTotalsPanel extends JPanel
// Define the dark green color
public final static Color darkGreen = new Color( 0, 150, 40 );
// Create our labels
JLabel lblDollarChange = new JLabel( "Dollar Change:", JLabel.CENTER );
JLabel lblPercentChange = new JLabel( "Percent Change:", JLabel.CENTER );
// Constructor
public PortfolioTotalsPanel()
// Set the layout manager
setLayout( new GridLayout( 2, 1 ) );
// Add the labels to the JPanel
add( lblDollarChange );
add( lblPercentChange );
// setDollarChange( fDollarChange )
// Set the Dollar Change label to the dollar amount in fDollarChange
public void setDollarChange( Float fDollarChange )
// Set color based off of value
if( fDollarChange.floatValue() > 0 )
// Green for positive
lblDollarChange.setForeground( darkGreen );
else if( fDollarChange.floatValue() < 0 )
// Red for negative
lblDollarChange.setForeground( Color.red );
else
// Black for no change
lblDollarChange.setForeground( Color.black );
// Set the label text
lblDollarChange.setText( "Dollar Change: $" + fDollarChange.toString() );
// setPercentChange( fPercentChange )
// Set the Percent Change label to the percent in fDollarChange
public void setPercentChange( Float fPercentChange )
// Set color based off of value
if( fPercentChange.floatValue() > 0 )
// Green for positive
lblPercentChange.setForeground( darkGreen );
else if( fPercentChange.floatValue() < 0 )
// Red for negative
lblPercentChange.setForeground( Color.red );
else
// Black for no change
lblPercentChange.setForeground( Color.black );
// Set the label text
lblPercentChange.setText( "Percent Change: " + fPercentChange.toString() + "%" );
// Main application entry point into this class
public static void main( String[] args )
// Create a JFrame object
JFrame frame = new JFrame( "Portfolio Totals" );
// Create an PortfolioTotalsPanel Object
PortfolioTotalsPanel app = new PortfolioTotalsPanel();
// Set the values of the labels
app.setDollarChange( new Float( "-150.50" ) );
app.setPercentChange( new Float( "15" ) );
// Add our PortfolioTotalsPanel Object to the JFrame
frame.getContentPane().add( app, BorderLayout.CENTER );
// Resize our JFrame
frame.setSize( 600, 100 );
// Make our JFrame visible
frame.setVisible( true );
// Create a window listener to close our application when we
// close our application
frame.addWindowListener
new WindowAdapter()
public void windowClosing( WindowEvent e )
System.exit( 0 );
Second Program
// ===========================================================================
// File: StockTablePanel.java
// Description: Sample file for Java 2 From Scratch
// ===========================================================================
// Import the libraries this application will use
import javax.swing.JTable;
import javax.swing.table.*;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
// Main application class: StockTablePanel
public class StockTablePanel extends JPanel
// Create a new Stock Table Model object
StockTableModel stockTableModel = new StockTableModel();
// Create a new JTable and associate it with the StockTableModel
JTable stockTable = new JTable( stockTableModel );
// Constructor
public StockTablePanel()
// Set the size of the table
stockTable.setPreferredScrollableViewportSize( new Dimension(620, 350) );
// Set the column widths for the table
TableColumn column = null;
for (int i = 0; i < 5; i++)
column = stockTable.getColumnModel().getColumn( i );
column.setPreferredWidth( stockTableModel.getColumnWidth( i ) );
// Create a scroll pane and add the stock table to it
JScrollPane scrollPane = new JScrollPane( stockTable );
// Add the scroll pane to our panel
add( scrollPane, BorderLayout.CENTER );
// float getDollarChange()
// Computes the total dollar change for the current portfolio
public float getDollarChange()
// Create a variable to hold the total change for all stocks
float fTotal = 0;
// Loop through all rows in the table
for( int i=0; i<stockTable.getRowCount(); i++ )
// Retrieve the dollar change for this stock
Float f = ( Float )stockTable.getValueAt( i, 10 );
// Add that value to our total
fTotal = fTotal + f.floatValue();
// Return the total value
return fTotal;
// float getPercentChange()
// Computes the total percentage change for the current portfolio
public float getPercentChange()
// Create a couple variables to hold the total the user spent
// on the stocks and the current value of those stocks
float fMoneySpent = 0;
float fMoneyWorth = 0;
// Loop through all rows in the table
for( int i=0; i<stockTable.getRowCount(); i++ )
// Extract some pertinent information for the computations
Float fLastSale = ( Float )stockTable.getValueAt( i, 2 );
Float fNumberOfShares = ( Float )stockTable.getValueAt( i, 6 );
Float fPricePaidPerShare = ( Float )stockTable.getValueAt( i, 7 );
// Add the amount of money the user spent on this stock
// to the total spent
fMoneySpent += fNumberOfShares.floatValue() * fPricePaidPerShare.floatValue();
// Add the value of this stock to the total value of the
// stock
fMoneyWorth += fNumberOfShares.floatValue() * fLastSale.floatValue();
// Compute the percentage change:
// TotalValue/TotalSpent * 100% - 100%
float fPercentChange = ( (fMoneyWorth / fMoneySpent) * 100 ) - 100;
// Return the percentage change
return fPercentChange;
// Main entry point into the StockTableApplication class
public static void main( String[] args )
// Create a frame to hold us and set its title
JFrame frame = new JFrame( "StockTablePanel Application" );
// Create an instance of our stock table panel
StockTablePanel stockTablePanel = new StockTablePanel();
// Add our tab panel to the frame
frame.getContentPane().add( stockTablePanel, BorderLayout.CENTER );
// Resize the frame
frame.setSize(640, 480);
// Make the windows visible
frame.setVisible( true );
// Set up a window listener to close the application window as soon as
// the application window closes
frame.addWindowListener
new WindowAdapter()
public void windowClosing( WindowEvent e )
System.exit( 0 );
// Table Model Class - holds all of our row and column information
class StockTableModel extends AbstractTableModel
// Create the columns for the table
final String[] strArrayColumnNames =
"Sym",
"Company Name",
"Last",
"Hi",
"Lo",
"Vol",
"#Shares",
"$Shares",
"Total",
"%Change",
"$Change"
// Create the rows for the table - hard coded for now!!
final Object[][] obArrayData =
// Row One
"SAMS", // Symbol
"Sams Publishing", // Company Name
new Float( 10 ), // Last Sale
new Float( 12 ), // High
new Float( 8 ), // Low
new Double( 2000000 ), // Volume
new Float( 100 ), // Number of Shares Owned
new Float( 7.5 ), // Purchase price per share
new Float( 1000 ), // Total Holdings
new Float( 33 ), // Percent change (increase!)
new Float( 250 ) // Dollar change
// Row Two
"Good", // Symbol
"Good Company", // Company Name
new Float( 50 ), // Last Sale
new Float( 52 ), // High
new Float( 45 ), // Low
new Double( 4000000 ), // Volume
new Float( 100 ), // Number of Shares Owned
new Float( 30 ), // Purchase price per share
new Float( 5000 ), // Total Holdings
new Float( 33 ), // Percent change (increase!)
new Float( 250 ) // Dollar change
// Row Three
"BAD", // Symbol
"Bad Company", // Company Name
new Float( 20 ), // Last Sale
new Float( 22 ), // High
new Float( 18 ), // Low
new Double( 2000000 ), // Volume
new Float( 500 ), // Number of Shares Owned
new Float( 50 ), // Purchase price per share
new Float( 10000 ), // Total Holdings
new Float( -60 ), // Percent change (increase!)
new Float( -25000 ) // Dollar change
// Return the number of columns in the table
public int getColumnCount()
return strArrayColumnNames.length;
// Return the number of rows in the table
public int getRowCount()
return obArrayData.length;
// Get the column name from the strArrayColumnNames array for the "col"-th
// item
public String getColumnName( int col )
return strArrayColumnNames[col];
// Return the value, in the form of an Object, from the obArrayData object
// array at position (row, col)
public Object getValueAt( int row, int col )
// We will compute columns 8, 9, and 10, so if the column number is
// below eight, we can just return it without computing or retrieving
// anything.
if( col < 8 )
return obArrayData[row][col];
// Retrive the necessary values from the object array to compute all
// of the remaining columns
Float fLastSale = ( Float )obArrayData[row][2];
Float fNumberOfShares = ( Float )obArrayData[row][6];
Float fPurchasePrice = ( Float )obArrayData[row][7];
switch( col )
// Total Holdings = Last Sale(2) * Number of Shares Owned(6)
case 8:
// Build a new Float object with the product of the two
Float fTotal = new Float
// Note, these have to be converted to type "float" to
// perform the multiplication
fLastSale.floatValue() * fNumberOfShares.floatValue()
// Return the result
return( fTotal );
// Percent change =
// (Last Sale Price (2) / Purchase Price (7)) * 100% - 100 %
case 9:
Float fPercentChange = new Float
((fLastSale.floatValue() / fPurchasePrice.floatValue ()) * 100) - 100
return fPercentChange;
// Dollar Change =
// LastSale*NumberOfShares - PurchasePrice * NumberOfShares
case 10:
Float fDollarChange = new Float
( fLastSale.floatValue() * fNumberOfShares.floatValue() )
( fPurchasePrice.floatValue() * fNumberOfShares.floatValue() )
return fDollarChange;
// We have included every case so far, but in case we add another
// column and forget about it, let's just return its value
default:
return obArrayData[row][col];
// Return the class type, in the form of a Class, for the c-th column in
// the first (0-th indexed) element of the obArrayData object array
public Class getColumnClass( int c )
return getValueAt(0, c).getClass();
// Return true if the "col"-th column of the table is editable, false
// otherwise. The following columns are editable:
// Cell Description
// 0 Symbol
// 6 Number of Shares Owned
// 7 Purchase Price per Share
public boolean isCellEditable(int row, int col)
// Check the column number
if( col == 0 || col == 6 || col == 7 )
return true;
else
return false;
// Set the value of the (row, col) element of the obArrayData to value
public void setValueAt(Object value, int row, int col)
// Symbol
if( col == 0 )
// We need a string value - we can convert any
// value to a string, so just assign it
obArrayData[row][col] = value;
// Number of Shares owned
else if( col == 6 )
// We need a number - either float or int
obArrayData[row][col] = new Float( getNumberString( value.toString() ) );
// Purchase Price per share
else if( col == 7 )
// We need a float
obArrayData[row][col] = new Float( getNumberString( value.toString() ) );
// Cell is not editable
else
return;
// Notify our parent of the change
fireTableCellUpdated(row, col);
// String getNumberString( String str )
// Read through str and return a new string with the numbers and decimal
// points contained in str
public String getNumberString( String str )
// Get str as a character array
char[] strSource = str.toCharArray();
// Create a buffer to copy the results into
char[] strNumbers = new char[strSource.length];
int nNumbersIndex = 0;
// Boolean to ensure we only have one decimal value
// in our number
boolean bFoundDecimal = false;
// Loop through all values of str
for( int i=0; i<strSource.length; i++ )
// Check for a digit or decimal point
if( Character.isDigit( strSource[i] ) )
strNumbers[nNumbersIndex++] = strSource;
else if( strSource[i] == '.' && !bFoundDecimal )
// Append the character to the String
strNumbers[nNumbersIndex++] = strSource[i];
// Note that we found the decimal value
bFoundDecimal = true;
// Build a new string to return to our caller
String strReturn = new String( strNumbers, 0, nNumbersIndex );
// Return our string
return strReturn;
// Return the column width of the column at index nCol
public int getColumnWidth( int nCol )
switch( nCol )
case 0:
case 2:
case 3:
case 4:
case 6:
case 7:
case 9:
return 50;
case 1:
return 125;
default:
return 75;
Third one that imports the previous two programs Classes
// Import the packages used by this class
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
// Import our other components
import StockTablePanel;
import PortfolioTotalsPanel;
// StockTableTabPanel
public class StockTableTabPanel extends JPanel implements TableModelListener
// Create our panels
StockTablePanel stockTablePanel = new StockTablePanel();
PortfolioTotalsPanel portfolioTotalsPanel = new PortfolioTotalsPanel();
// Constructor
public StockTableTabPanel()
// Set our layout
setLayout( new BorderLayout() );
// Initialize the portfolio panel
updatePortfolioTotals();
// Add the child panels to our JPanel
add( stockTablePanel );
add( portfolioTotalsPanel, BorderLayout.SOUTH );
// Add our class as a table model listener for the stock table
// model so that we can update the portfolio totals panel
// whenever the table changes.
stockTablePanel.stockTableModel.addTableModelListener( this );
// TableModelListener: tableChanged
public void tableChanged(TableModelEvent e)
// Make sure it is our table that changed
if( e.getSource() == stockTablePanel.stockTableModel )
// Call our method to update the portfolio totals
updatePortfolioTotals();
// public updatePortfolioTotals
// Updates the portfolio totals panel labels based off of the values
// in the stockTablePanel
public void updatePortfolioTotals()
// Get the values from the stockTablePanel and send them
// to the portfolioTotalsPanel
portfolioTotalsPanel.setDollarChange( new Float( stockTablePanel.getDollarChange() ) );
portfolioTotalsPanel.setPercentChange( new Float( stockTablePanel.getPercentChange() ) );
// Main application entry point into this class
public static void main( String[] args )
// Create a JFrame object
JFrame frame = new JFrame( "Stock Table Tab" );
// Create an StockTableTabPanel Object
StockTableTabPanel app = new StockTableTabPanel();
// Add our StockTableTabPanel Object to the JFrame
frame.getContentPane().add( app, BorderLayout.CENTER );
// Resize our JFrame
frame.setSize( 640, 440 );
// Make our JFrame visible
frame.setVisible( true );
// Create a window listener to close our application when we
// close our application
frame.addWindowListener
new WindowAdapter()
public void windowClosing( WindowEvent e )
System.exit( 0 );
Maybe you are looking for
-
Urgent: IDOC to EDI with SAP Conversion Agent
Hi, I have a requiremetn like IDOC to EDI ( Gentran ) scenario. We have decided to use SAP Conversion Agent to deal the same. Can anybody share their experiences on this kind of scenario. Needed step by step information to complete would be appreciat
-
HT1338 intel core duo / can't migrate to icloud?
Hi. I would like some help in clarifying please. I have an older Macbook with an Intel Core Duo running Snow Leopard. I can't upgrade to Lion. I have used my .mac account/Mobileme for years primarily for email purposes, idisk, and the gallery (I
-
Dv6-2018ax Original BIOS for Windows Vista 32bit
I have tried for hours to find the original BIOS for the DV6-2018AX (windows vista 32bit) with no luck. I know there is no BIOS update... I am not interested in that, just the bios it came out of the factory with. If anyone could help me I would be
-
Can't watch HD iTunes movies on my own new Mac!
Hello, I have a Macbook Pro (it's new, bought it recently, retina display) and I've just rented a HD movie on iTunes. For some reason iTunes doesn't play the movie, and it doesn't give me any window saying it can't play or anything. When I click to p
-
How to keep internet connection?
I have a MacBookPro. Just downloaded Yosemite X. Now can't stay connected to internet. Help??