Int/Double workaround with an imported class.
Hi,
I've been having a heck of a time trying to figure something out. I have a bunch of data that is in double format (eg 10.351). However, I'm importing a class awt.Polygon for a bunch of reasons, and one of it's key methods (addPoints();) only accepts integers.
What I would like to do is take my double value, multiply it by enough so that it can be cast into an int without losing an data, than manipulate it with the addPoint function.
I was thinking it would look something like:
public class chsShape extends Polygon{
public void addPointDoub(Double x, Double y)
int xi =(int)(x*1000);
int yi =(int)(y*1000);
addPoint( xi, yi);
} Obviously, this doesn't work (or I wouldn't be posting). It gives me "java.lang.NoSuchMethodError:chsShape.addPointDoub".
Anyone have any suggestions? Thanks!
Here is a demo using the PathIterator:
import java.awt.geom.*;
public class GeneralPathExample {
public static void main(String[] args) {
GeneralPath p = new GeneralPath();
p.moveTo(1,1);
p.lineTo(1,2);
p.lineTo(2,2);
p.lineTo(2,1);
p.closePath();
double[] coords = new double[6];
for (PathIterator i = p.getPathIterator(null);!i.isDone(); i.next()) {
switch(i.currentSegment(coords)) {
case PathIterator.SEG_MOVETO:
System.out.format("moveTo(%f,%f)%n", coords[0], coords[1]);
break;
case PathIterator.SEG_LINETO:
System.out.format("lineTo(%f,%f)%n", coords[0], coords[1]);
break;
case PathIterator.SEG_CLOSE:
System.out.println("closePath()");
break;
default:
System.out.println("too lazy to code other cases...");
}Perhaps what may prove more useful to you is to have a shape, GeneralPath, plus maintain a separate list of points, for easy access. The thing is, a GeneralPath is more than a list of points: it can include curved segments and gaps, etc...
Similar Messages
-
Int/Double Workaround for an imported class
Hi,
I've been having a heck of a time trying to figure something out. I have a bunch of data that is in double format (eg 10.351). However, I'm importing a class awt.Polygon for a bunch of reasons, and one of it's key methods (addPoints();) only accepts integers.
What I would like to do is take my double value, multiply it by enough so that it can be cast into an int without losing an data, than manipulate it with the addPoint function.
I was thinking it would look something like:
public class chsShape extends Polygon{
public void addPointDoub(Double x, Double y)
int xi =(int)(x*1000);
int yi =(int)(y*1000);
addPoint( xi, yi);
} Obviously, this doesn't work (or I wouldn't be posting). It gives me "java.lang.NoSuchMethodError:chsShape.addPointDoub".
Anyone have any suggestions? Thanks!Double posted and answered.
http://forum.java.sun.com/thread.jspa?threadID=5253042&tstart=0 -
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 ); -
Replacing " (double quote) with ' (single quote)
Hi there,
I have the following method to manipulate user input. All I want to do is, to replace the double quote with a single quote. The implementation I tried was,
this.replace(desc, "\"", "'");
This does not work for me. It jsut removes the double quote and does not introduces the single quote. Could any one please advise?
Thanks,
Des
public static String replace(String line, String oldString, String newString) {
if(line != null && oldString != null && newString != null) {
int index = 0;
while ((index = line.indexOf(oldString, index)) >= 0) {
line = line.substring(0, index) +
newString +
line.substring(index + oldString.length());
index += newString.length();
return line;
}Bad luck.. I am unable to get it still.
This is the code I am using (implemetation is in a JSP. I am using this code to test it).
public class Test{
public static void main(String args[]){
String s = args[0];
Test t = new Test();
String doubleQuote = "\"";
System.out.println(" output :"+ t.replace(s,doubleQuote,"'"));
//System.out.println(" output :"+ t.replace(s,"\"","'"));
//System.out.println(" output :"+ t.replace('"', '\''));
public static String replace(String line, String oldString, String newString) {
if(line != null && oldString != null && newString != null) {
int index = 0;
while ((index = line.indexOf(oldString, index)) >= 0) {
System.out.println(" line count :");
line = line.substring(0, index) +
newString +
line.substring(index + oldString.length());
index += newString.length();
return line;
}mshn02
The main problem is I am stuck with the server's version of Java (which I have no control on it). I could not use 1.4.2 -
How to call a Derived call fucntion with a base class object ?
Hi all
i am working on a JNI interface to Java, and in the process of simulating a C++ behaviour in java
so i need some help form you people, in this regard.
here is a c++ code, i need a equivalent fucntionality in java , to put it one word, the question is
how to implement the dynamic_cast functionality in java, as java also has virtual fucntions, i think
this should be possible, if it is not, what is the alternative
class Base
public:
Base()
~Base()
virtual void F1()
cout<<"The BASE::F1() is called"<<endl;
virtual void F2()
cout<<"The BASE::F2() is called"<<endl;
class Derived : public Base
public:
Derived()
~Derived()
virtual void F3()
cout<<"The Derived::F3() is called"<<endl;
virtual void F4()
cout<<"The Derived::F4() is called"<<endl;
Base * GetDerived()
return new Derived();
int _tmain(int argc, _TCHAR* argv[])
Base *ptr = NULL;
ptr = GetDerived();
Derived *dPtr = dynamic_cast<Derived *>(ptr);
dPtr->F3();
}regards
pradishJust to clarify a point that I consider important--the distinction between references and objects:
Your subject is: How to call a Derived call fucntion with a base class object ? The answer to that is: You cannot. It is completely impossible in Java. If you have a base class object, the derivced class' methods are not present. On the other hand, if you have a compile-time reference of the parent type, but at runtime it happens to point to an instance of the derived class, then, as pointed out, you can cast the reference. (Note that casting does not apply to objects.) -
Help with designing basic class
Ok, I'm trying to learn java by implementing a Recipe program that I will eventually put up on my web page. My thought was to create a base class called recipe that would essentially be a collection of strings and such. This would then be tied to a database with getFromDatabase() methods etc... However I'm I just want to clarify a few things and make sure I'm headed in the right direction.
I figure I should create my class something like this:
public class Recipe
public String recipeName;
// more strings like serves source, etc...
public int rating; // 1-5
// Ingredient list
// Category list
public String directions;
public Recipe(String recipeName)
this.recipeName = recipeName;
}The above is pretty much what I think is right with what I have so far. For the ingredients, I created a special class called ingredient that looks like:
public class Ingredient
public String qty;
public String amt;
public String desc;
public Ingredient(String quant, String ammount, String description)
this.qty = quant;
this.amt = ammount;
this.desc = description;
public Ingredient()
this.qty = "";
this.amt = "";
this.desc = "";
public String toString()
String tempstring = new String(this.qty + " " + this.amt + " " + this.desc);
return tempstring;
}Then in my recipe class I have:
public List ingredients = Collections.synchronizedList(new LinkedList());and then I have two overloaded addIngredient methods to add an Ingredient object to this list.
So am I on the right track? Should I not even bother with a special class just for ingredients?
Also while I have your attention, if I were to try and get a list of recipes in the database (ie, SELECT recipename FROM recipes;) where should I put this method? Thank you for any help.
-ChrisYou only use get() and set() methods for data you need to change, I didn't think that I had to point that out.
The guy is obviously a beginner, there is no need to saturate him with loads of information that isn't too important to him right now; however, it is good to get him used to the get and set methods for the variables that might need changing, and keeping (most of) the variables private (or protected as the case may be).
Please tell me how setting variables to private does not contribute to information hiding? @_@
Because, the last time I heard, private variables can't be accessed by other classes.
Not only that, the get() and set() methods DO hide information, mainly the inner workings of the code. Consider:
public class Foo {
private int x;
public int getX() {
return x;
public void setX(int anInt){
x = anInt;
public class Bar {
private Foo mFoo = new Foo();
public int process(){
int intialValue = myFoo.getX();
return initialValue * 4;
}And say for whatever reason the way Foo handled the way x was stored had to change:
public class Foo {
public String x = "0"; // x no longer an int
public int getX() {
return Integer.parseInt(x); // convert when needed
public void setX(int anInt){
x = new Integer(anInt).toString(); // convert back
public class Bar {
private Foo mFoo = new Foo();
public int process(){
int intialValue = myFoo.getX(); // none the wiser
return initialValue * 4;
}Note, because of the get and set methods, we didn't have to change Bar. I'd say this was a kind of data hiding, no?
I do know a bit about what I'm saying. I may not be an expert, but what I said was on the wholecorrect, especially considering the OP is a beginner. I never claimed what I told him was the WHOLE of tight encapsulation, but it is a part of it. He doesn't need to know more than what I told him ATM. -
I was reading the tutorial on importing class's. This is what
I read
Importing classes
To reference a class in another script, you must prefix the
class name with the class's package path. The combination of a
class's name and its package path is the class's fully qualified
class name. If a class resides in a top-level classpath
directory--not in a subdirectory in the classpath directory--then
its fully qualified class name is its class name.
To specify package paths, use dot (.) notation to separate
package directory names. Package paths are hierarchical, where each
dot represents a nested directory. For example, suppose you create
a class named Data that resides in a com/xyzzycorporation/ package
in your classpath. To create an instance of that class, you could
specify the fully qualified class name, as shown in the following
example:
var dataInstance = new com.xyzzycorporation.Data();
My Question is about com/xyzzycorporation/ . would the full
class parth be c:/com/xyzzycorporation/ . Why do they never state
the drive letter when teaching about directories.Because there is no need. you don't need to reference the
drive letter.
Here's the basic jist of what they are saying....
Single Class File...
If you create your own custom class and want to use it in
your flash file, save it into the same directory as the fla file
and call the classes constructor. By default flash will look inside
the folder where the fla resides in for the class files if it
cannot find it inside the default directory.
Multiple Class Files - 1 Project (often referred to as
packages)
Use your qualified domain name but backwards.....
my domain is www.sd-dezign.com so if I was going to include a
package of utility class files in my document I would do the
following
Create a folder in the same folder with my fla name it com
and inside that a folder called sddezign and inside that utils and
all my as files would be in there...the folder structure might look
like this....
myfile.fla
com
>sddezign
>>utils
>>>box.as
>>>circle.as
To call the constructor for each class, I have two options.
The first which is by far the easiest looks like this
In whatever frame you need to call that class constructor
include "com.sddezign.utils.*";
var myBox:Box = new Box();
The second method requires more typing and can get tedious
var myBox = new com.sddezign.utils.Box();
Hope this helps you a bit better. -
Import collides with another import statement
Suppose I have 2 packages, train and plane. Each package has a class called Engine. In addition, train.Engine and plane.Engine have nothing in common. In a 3rd class, I import both of these:
import train.Engine;
import plane.Engine;Doing so results in the following error:
The import plane.Engine collides with another import statement
How do I do this?One of these imports have to be commented. The imports are reside in the source code, not just in jar or other class path entries. If the imports are in different files then you'd browse the sources and find import with the same name but in different name spaces. This is happened if you you don't wanna add a big jar to the class path instead you created a class file with the same name because of huge references. And you just wanted route it out of the jar and possibly remove dependency.
-
Audio sync problem with videos imported from iPod Touch
I have an iPod Touch 4th Generation that I used to shoot video at a family birthday party. When I imported the footage into iMovie '11, the audio is not in sync with the video (video is about two seconds behind audio) and there is only the left channel of audio. I verified that the video on the iPod plays just fine--no audio sync problem, both left and right channels work. I just upgraded to iOS 5 on the iPod Touch. The iMac is running Snow Leopard 10.6.8.
As a workaround, I can import the video into iPhoto instead. When I play the video in iPhoto, there are no audio sync problems and both channels of audio can be heard. I have imported other iPod Touch videos successfully into iMovie '11 in the past few months, but this has been the first time these problems have occurred. Any help would be appreciated.Premiere cannot handle clips with variable framerate.
Your converted clips need to have constant framerate.
Otherwise use a converter like Handbrake. -
Please help with the URL class
Hello,
I am trying to write a Java app that will take a url and download it.
I believe you can do this with the URL class but I don't understand how to. For example, if the http url location points to a picture file, how would I code the app to retrieve this picture and save it to a specified directory?
Also, is there a way that my java app could open another program, let's say Microsoft Internet Explorer?
Please be as specific as possible, thanks!You'll see below an example to download a file
private static String copyFile (String url, String nomFichier){
// construction du fichier de sortie
File outputFile = new File(repertoire + "\\fichiers\\" + nomFichier);
// si le fichier existe d�j�, il ne sert � rien de le t�l�charger !
if (outputFile.exists())
return "fichiers/" + nomFichier;
try {
HttpURLConnection connect = (HttpURLConnection)new URL(url).openConnection();
boolean connected = false;
while (!connected){
try {
connect.connect();
connected = true;
catch (java.io.IOException e1) { System.out.print("...Tentative de connection"); }
DataInputStream reader = new DataInputStream(
connect.getInputStream());
FileOutputStream out = new FileOutputStream(outputFile);
int length = 1024;
byte[] buf = new byte[length];
int offset = 0;
long offsetCourant = 0;
int nb=0;
while ((nb=reader.read(buf,offset,length))!= -1) {
out.write(buf,0,nb);
out.close();
catch (java.net.MalformedURLException e) { System.out.println("pb d'url"); }
catch (java.io.IOException e1) { System.out.println(e1.getMessage()); }
return "fichiers/" + nomFichier;
} -
Compilation Error for import classes not found in generated Proxy Class
Hi,
We are generating java classes for the COM dll using JCOM com2java compiler.
We are getting a compilation error for import class not found when compiling the
generated Proxy java source code. It can't find the com.bea.jcom.Dispatch class that
the generated Proxy java source code extends. It also can't find com.bea.jcom.Variant
or com.bea.jcom.Param. These are interfaces or data types or classes used by COM
library.
I added weblogic.jar to my class path and the only Dispatch class i found inside
the weblogic.jar is com.linar.jintegra.Dispatch;
We have com objects for which we want to develop an EJB client to interface with
the COM object using JCOM with Native Mode disabled.
Any help on the compilation error..I tried changing the extends for Dispatch to com.linar.jintegra.Dispatch
but the other errors are still there.
To begin with, I think the generated code should not refer to any of the COM data
types.
Any help please.
Thank you in advance,
Regards,
Rahul Srivastava
[email protected]Hi,
I resolved the other errors by changing all references from com.bea.jcom.Variant
etc to com.linar.jintegra.class name..all were present under the com.linar.jintegra
package.
Thank you all anyways,
Regards,
rahul
"Rahul Srivastava" <[email protected]> wrote:
>
Hi,
We are generating java classes for the COM dll using JCOM com2java compiler.
We are getting a compilation error for import class not found when compiling
the
generated Proxy java source code. It can't find the com.bea.jcom.Dispatch
class that
the generated Proxy java source code extends. It also can't find com.bea.jcom.Variant
or com.bea.jcom.Param. These are interfaces or data types or classes used
by COM
library.
I added weblogic.jar to my class path and the only Dispatch class i found
inside
the weblogic.jar is com.linar.jintegra.Dispatch;
We have com objects for which we want to develop an EJB client to interface
with
the COM object using JCOM with Native Mode disabled.
Any help on the compilation error..I tried changing the extends for Dispatch
to com.linar.jintegra.Dispatch
but the other errors are still there.
To begin with, I think the generated code should not refer to any of the
COM data
types.
Any help please.
Thank you in advance,
Regards,
Rahul Srivastava
[email protected] -
Working with AS3 External Classes
Ok... trying to work with AS3 external classes. I have a movieClip that I want to also function as a button. Instance name is "_onDemand". This movieClip is on the stage of my Home.fla. "_onDemand" movieClip properties Class:HomePage Base clase: flash.display.MovieClip
I want the user to click this movieClip and take the user to an external URL within a new browser window or tab.
Can anyone help me? Or at least point me to a really really good tutroial that does exactly this using external classes?
Thanks so much,
Mark
My code:
package com.cox4college.pages
import com.gaiaframework.templates.AbstractPage;
import com.gaiaframework.events.*;
import com.gaiaframework.debug.*;
import com.gaiaframework.api.*;
import flash.display.*;
import flash.events.*;
import com.greensock.TweenMax;
import flash.net.URLRequest;
import flash.net.navigateToURL;
public class HomePage extends AbstractPage
public function HomePage()
super();
alpha = 0;
//new Scaffold(this);
override public function transitionIn():void
super.transitionIn();
TweenMax.to(this, 0.3, {alpha:1, onComplete:transitionInComplete});
override public function transitionOut():void
super.transitionOut();
TweenMax.to(this, 0.3, {alpha:0, onComplete:transitionOutComplete});
public class _onDemand extends Sprite
// Link Navigation button handlers
public var _onDemand:Sprite;
// if you want a hand cursor
_onDemand.buttonMode = true;
_onDemand.useHandCursor = true;
_onDemand.addEventListener(MouseEvent.CLICK, onDemandClickHandler);
_onDemand.addEventListener(MouseEvent.ROLL_OVER, onDemandRollOverHandler);
_onDemand.addEventListener(MouseEvent.ROLL_OUT, onDemandRollOutHandler);
public function onDemandClickHandler(e:MouseEvent):void{
navigateToURL(new URLRequest("http://ww2.cox.com/residential/santabarbara/tv/ondemand.cox"));
public function onDemandRollOverHandler(event:MouseEvent):void{
_onDemand.gotoAndStop("hover");
public function onDemandRollOutHandler(event:MouseEvent):void{
_onDemand.gotoAndStop("static");
Getting the following errors:
1120: Access of undefined property _onDemand.Ok. I admit it... I had some wonderful help to resolve this issue. You ever feel like you are on an island learning AS3 External Classes? I feel that way all the time... so far... I plan on not feeling that way soon. I hope this helps someone get off that island.
package com.domainname.client {
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
import caurina.transitions.Tweener;
import caurina.transitions.properties.*;
FilterShortcuts.init();
ColorShortcuts.init();
public class Main extends MovieClip {
private var coverDelay:Number = 4;
//#DF6D27
public function Main():void {
initMain();
private function initMain():void {
mc_form.visible = false;
Tweener.addTween(mc_cover,{alpha:1,time:1,delay:coverDelay,onComplete:formIn});
btn_onDemand.buttonMode = true;
btn_listings.buttonMode = true;
btn_ppv.buttonMode = true;
btn_rhapsody.buttonMode = true;
btn_onDemand.addEventListener(MouseEvent.MOUSE_OVER,navOver);
btn_onDemand.addEventListener(MouseEvent.MOUSE_OUT,navOut);
btn_onDemand.addEventListener(MouseEvent.CLICK,navClick);
btn_listings.addEventListener(MouseEvent.MOUSE_OVER,navOver);
btn_listings.addEventListener(MouseEvent.MOUSE_OUT,navOut);
btn_listings.addEventListener(MouseEvent.CLICK,navClick);
btn_ppv.addEventListener(MouseEvent.MOUSE_OVER,navOver);
btn_ppv.addEventListener(MouseEvent.MOUSE_OUT,navOut);
btn_ppv.addEventListener(MouseEvent.CLICK,navClick);
btn_rhapsody.addEventListener(MouseEvent.MOUSE_OVER,navOver);
btn_rhapsody.addEventListener(MouseEvent.MOUSE_OUT,navOut);
btn_rhapsody.addEventListener(MouseEvent.CLICK,navClick);
function navOver(evt:MouseEvent):void {
Tweener.addTween(evt.target,{_color:0xffc614,time:.2});
function navOut(evt:MouseEvent):void {
Tweener.addTween(evt.target,{_color:0xffffff,time:.2});
function navClick(evt:MouseEvent):void {
var url;
switch (evt.target.name) {
case 'btn_onDemand':
url = new URLRequest("http://ww2.cox.com/residential/santabarbara/tv/ondemand.cox");
break;
case 'btn_listings':
url = new URLRequest("http://ww2.cox.com/myconnection/santabarbara/watch/entertainment/tv-listings.cox");
break;
case 'btn_ppv':
url = new URLRequest("http://ww2.cox.com/residential/santabarbara/tv/pay-per-view.cox");
break;
case 'btn_rhapsody':
url = new URLRequest("http://ww2.cox.com/myconnection/santabarbara/listen.cox");
break;
navigateToURL(url,"_blank"); -
Problem importing classes and beans
Hey there. Im having one major fustrating problem! When I code supporting classes and beans for my JSPs I get a code 500 internal server error when trying to import (via <%@ page import="class" %> and <jsp:useBean/>) Im storing my classes and beans in the WEB-INF folder and the calling JSPs are located in /ROOT/tests/8/jsp.jsp. Im using the following to import a class or bean:
<%@ import="aClass" %>
Seen as tho its in the WEB-INF folder I won't have to explicitly refer to where the class is located, just the class name.
I never had this problem when I was using my hosting service. Its only on my localhost server in which I get the Internal Server error.
Help appreciated, thx.
PS: Im quite new to JSP/Java Servlet.import (via <%@ page import="class" %> and
<jsp:useBean/>) Im storing my classes and beans in the
WEB-INF folder try put your class file in WEB-INF/classes.
or first put bean in the package, like WEB-INF/classes/packagename/beanclass
in jsp page:
<jsp:useBean id="Mybean" class="packagename.beanclass" scope="request" />
Question: is /ROOT a context entry in your server.xml?
Which JSP Container (version) you use? Maybe your localhost server's set up is different with your hosting. -
Problems with VLM Import Utility
Hello!
We I are using NI Volume License Manager 3.0 together with NI Volume License Manager Import Utility for importing users data.
The problem is that we can't import .xml data into VLM when the user types his name into Full Name field and his name contains characters like ČŠĆŽĐ čšćžđ. These characters are not correctly written into .xml file with VLM Import Utility and we have to manually replace them with Microsoft Expression Web before we can load .xml file into VLM server.
Do you have better solution? Is there some new version of NI Volume License Manager Import Utility that correctly handles non English characters?
Thank you
Bojan Gergič
Solved!
Go to Solution.Hi
Sorry for not having a god news. This issue is a known bug (You can refere to it by a number CAR - Corrective Action Request - #320545). Unfortunatelly, I have no knowledge about a workaround for this.
Regards
Barbara -
I have one class calling another, like this:
import CloseWindowListener;
import DatabaseSearchControls;
import java.awt.event.*;
public class DatabaseSearch {
public static void main (String[] args) {
DatabaseSearchControls frame = new DatabaseSearchControls();
frame.addWindowListener ( new CloseWindowListener() );
frame.show();
I get these errors when I compile DatabaseSearch:
C:\Documents and Settings\Korbel\My Documents\benmay\DatabaseSearch.java:9: '.' expected
import CloseWindowListener;
^
C:\Documents and Settings\Korbel\My Documents\benmay\DatabaseSearch.java:10: '.' expected
import DatabaseSearchControls;
The other 2 files complied correctly and are in the same directory. Anyone ever seen this and know what I am doing wrong?
Thank you!Are you compiling with version 1.4? If so, it is now invalid to import classes that don't belong to a package. It is not necessary to do so anyway, so just remove the import statements. Better yet, follow the Java standard and put each class you write into a named package, using the package statement.
Maybe you are looking for
-
Hello, I am having a requirement, I need to pick an output type in transaction VF02 based upon some conditions. We can't to this through NACE transaction since it requires some custom table involvement and it is not possible to handle those condition
-
E72 email doesn't properly connect
Hi, I've run a quick search and while I found this issue has been mentioned before, it hasn't been resolved as far as I can see (if it has, I'd be happy if you point me to a solution!). I've set up my Gmail account on my E72 device, and it has been w
-
"iTunes application could not be opened"
I get the message "iTunes application could not be opened. An unknown error occurred (-51)" every single time I open iTunes now. The application worked fine when it was version 5.0, but everything went south after 6.0 then 6.0.1, it hasn't worked sin
-
Safari doesn't show the keyboard on my webmail text field
So..... I go away for a weekend - wonder which hardware to take - choose iPad - wifi at my mates place, can read email - fill in to and cc fields on the reply but bounce cursor to the text body - no keyboard. Errrrr how do I send an email - no key (I
-
MacBook Louder in XP than in OS X
I have a new 13" Aluminum MacBook on which I installed Windows XP using Boot Camp yesterday. I am noticing that the MacBook is much louder when running XP than it is when running OS X. It sounds like a fan spinning. (does it even have a fan? maybe it