Public class ArrayEx extends Array
Hi, I'm very bad at OO programming, but I'm trying to learn.
I want to add some functions to my Arrays, like checking if
arrays contain a value (indexOf can be equal to 0, which is false,
though actually I'm used to the loose data typing of as2, so this
may not be quite true. Bear with me though, I want to learn how to
extend a class). So I'm trying to write a class that extends the
basic Array class.
I am confused about the constructor, I want to mimic the
behaviour of the Array class but I'm not sure if I need to write
functions for each method of Array. Since my ArrayEx extends the
Array class it should inherit the array functions right? So it
should already have .pop() and .push() ext. defined? How should I
write my constructor to store the data the same way as the Array
class does though?
Is there somewhere I can look at the internal Array class to
figure out how it does it?
What I have written so far appears at the bottom of the
message. I include questions as comments.
I hope someone can help me out. I'm sorry if I'm asking stuff
that seems obvious. Thanks for your time.
Jon
I've found the solution to my second set of problems and
since I chose to trouble you all with the question I thought I'd
post the answer.
First problem, I had declared the ArrayEx class as dynamic
but not as public. Should read;
dynamic public class ArrayEx extends Array{
Second problem. An empty constructor function, by default,
calls the parent constructor function with no arguements. Since I
wanted to construct my new array class like the default array class
i had to add some code to handle that.
So here is the working class;
Similar Messages
-
Extending Array class, get Error #1069: Property 0 not found with indexOf call
I'm using inheritance to extend the Array class to create a Paths class that moves Sprites/MovieClips around on the screen. I'm getting an odd error on a call to indexOf. Here's the error:
ReferenceError: Error #1069: Property 0 not found on Paths and there is no default value.
at Array$/_indexOf()
at Array/http://adobe.com/AS3/2006/builtin::indexOf()
at Paths/Next()[D:\Stephen\Documents\Flash\TossGame\TossGameFirstPerson\Paths.as:40]
Here's the relevant code in the Paths class:
public class Paths extends Array
private var cCurrentPath:Path;
public function Next():Path
var lArray:Array = this;
var lNextIndex:int = indexOf(cCurrentPath) + 1;
if (lNextIndex == length) lNextIndex = 0;
var lPath:Path = lArray[lNextIndex];
return lPath;
} // class
I get the error at the highlighted line. cCurrentPath is populated with a Path object which is the object located at position 0 of the this object (Paths). I've tried the following variants of the Next() function:
public function Next():Path
var lArray:Array = this;
var lNextIndex:int = lArray.indexOf(cCurrentPath) + 1;
if (lNextIndex == lArray.length) lNextIndex = 0;
var lPath:Path = lArray[lNextIndex];
return lPath;
public function Next():Path
var lArray:Array = this;
var lNextIndex:int = this.indexOf(cCurrentPath) + 1;
if (lNextIndex == this.length) lNextIndex = 0;
var lPath:Path = lArray[lNextIndex];
return lPath;
public function Next():Path
var lArray:Array = this;
var lNextIndex:int = super.indexOf(cCurrentPath) + 1;
if (lNextIndex == super.length) lNextIndex = 0;
var lPath:Path = lArray[lNextIndex];
return lPath;
Same error happens whichever I try. Anyone got any ideas?
Stephen
Flash Pro CS3 (Version 9.0)Mark your class dynamic.
public dynamic class Paths extends Array -
Creating array of objects of class which extends Thread
getting NullPointerException
can i not create thread array this way?
class sample extends Thread
{ int i,id;
public sample(int c)
{ id=c;
public void run()
{ for(i=0;i<6;i++)
System.out.println("Thread "+id+" "+i);
public class thread extends Frame implements ActionListener
{ Button b1;
sample s[];
thread()
{ for(int i=0;i<2;i++)
s=new sample(i);
setLayout(new FlowLayout());
b1=new Button("OK");
add(b1);
b1.addActionListener(this);
public void actionPerformed(ActionEvent e)
{ b1.setEnabled(false);
for(int i=0;i<2;i++)
{ s[i]=new sample(i);
s[i].start();
public static void main(String args[])
{ thread t1=new thread();
t1.setVisible(true);
t1.setSize(150,150);You need:
sample [] s = new sample[2];However
1) You should get into the habit that class names start with capital letters, variable and field names with lower case.
2) It's not a good idea to extend Thread, make a class which implements the Runnable interface and hook a standard Thread object to that. -
I want to define a new method to search arrays for specific
values.
I have a new class defined like this:
class Array2 extends Array{
function Array2(){
function myMethod(){
In my code I use this line to declare a new instance:
var myArray:Array2=new Array2(1,2,3,4,5);
If I now use use:
trace(myArray[1]);
it returns 'undefined'. What is the reason for this and is
there a way round it?
If I define the myArray without any values and then use the
push() method it seems to work but I need Array2 to work exactly
the same as Array only with some additional methods.
Cheers for any and all helpCheers JPK that works well. I am confused about the super()
statement though as if you remove it from the last example it still
works.
The help file suggests that you should be able to use:
functio Array2(){
super(arguments);
but if I do and then create an instance with ...new
Array2(1,2,3,4);
it makes an array with one node only containing the string
"1,2,3,4"
This is all beside the point really as I can now make it work
at least (thank again everyone) but I would like to understand
exactly what is going in the background here so please keep posting
any findings.
NIce nice nice :) -
Calls to methods in a class that extends Thread
Hello,
I have some code that I am initiating from within an ActionListener that is part of my programs GUI. The code is quite long winded, at least in terms of how long it takes to perform. The code runs nicely, however once it is running the GUI freezes completely until operations have completed. This is unacceptable as the code can take up to hours to complete. After posting a message on this forum in regard to the freezing of the GUI it was kindly suggested that I use multi-threading to avoid the unwelcome program behaviour.
The code to my class is as follows:
public class FullURLAddress
private boolean success_flag = true;
private BufferedReader iN;
private Document dT;
private EditorKit kT;
private Element lmNt;
private ElementIterator lmIterate;
private XURL[] compAddress;
private int countX = 0; //Tracks Vector vT's size.
private int countY = 0; //Tracks Vector vS's size.
private int xURLcount = 0; //Tracks XURL objects instantiated by this FullURLAddress object.
private SimpleAttributeSet simpAtSet;
private String aURL; //Contains original (Xtended) URL!
private String fileType;
private String indexContent;
private String[] parseURL;
private String[] finalStrings;
private String[] sortStrings;
private URL indexConnect;
private URLConnection iconn;
private Vector vT; //Stores href information, from targeted URL's HTML souce code.
private Vector vS; //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
public FullURLAddress(String aURL)
this.aURL = aURL;
try{
indexConnect = new URL(aURL);
iconn = indexConnect.openConnection();
iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
/* Document creation, analysis objects instantiated */
vT = new Vector();
vS = new Vector();
kT = new HTMLEditorKit();
dT = kT.createDefaultDocument();
dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
/* Iterate through document and store all HREF values */
kT.read(iN, dT, 0);
lmIterate = new ElementIterator(dT);
while((lmNt = lmIterate.next()) != null)
simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
if(simpAtSet != null) //As long as there are A tags to be read...
vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
}catch(MalformedURLException e){
success_flag = false;
System.out.println("FullURLAddress object has encountered a "+
"MalformedURLException at: "+aURL);
}catch(IOException e){
e.getMessage();
success_flag = false;
}catch(BadLocationException e){
e.getMessage();
success_flag = false;
/* Searches through all HREF attributes that are now stored in Vector
vT for occurences of the character string ".htm" */
sortStrings = new String[countX];
for(int i=0;i<countX;i++)
sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
countY++;
if(sortStrings[i].endsWith("GIF"))
vS.addElement(sortStrings[i]);
countY++;
if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
countY++;
if(sortStrings[i].endsWith("JPG"))
vS.addElement(sortStrings[i]);
countY++;
finalStrings = new String[countY];
for(int j=0;j<countY;j++)
finalStrings[j] = (String)vS.elementAt(j);
public int getCount()
return countY; //Returns number of instances of htm strings
} //ending with either "jpg" or "gif".
public String[] xurlAddressDetails()
return finalStrings;
I have changed the above code to make use of multithreading by making this class extend Thread and implementing the run() method as follows:
public class FullURLAddress extends Thread
private boolean success_flag = true;
private BufferedReader iN;
private Document dT;
private EditorKit kT;
private Element lmNt;
private ElementIterator lmIterate;
private XURL[] compAddress;
private int countX = 0; //Tracks Vector vT's size.
private int countY = 0; //Tracks Vector vS's size.
private int xURLcount = 0; //Tracks XURL objects instantiated by this FullURLAddress object.
private SimpleAttributeSet simpAtSet;
private String aURL; //Contains original (Xtended) URL!
private String fileType;
private String indexContent;
private String[] parseURL;
private String[] finalStrings;
private String[] sortStrings;
private URL indexConnect;
private URLConnection iconn;
private Vector vT; //Stores href information, from targeted URL's HTML souce code.
private Vector vS; //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
public FullURLAddress(String aURL)
this.aURL = aURL;
public void run()
try{
indexConnect = new URL(aURL);
iconn = indexConnect.openConnection();
iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
/* Document creation, analysis objects instantiated */
vT = new Vector();
vS = new Vector();
kT = new HTMLEditorKit();
dT = kT.createDefaultDocument();
dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
/* Iterate through document and store all HREF values */
kT.read(iN, dT, 0);
lmIterate = new ElementIterator(dT);
while((lmNt = lmIterate.next()) != null)
simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
if(simpAtSet != null) //As long as there are A tags to be read...
vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
}catch(MalformedURLException e){
success_flag = false;
System.out.println("FullURLAddress object has encountered a "+
"MalformedURLException at: "+aURL);
}catch(IOException e){
e.getMessage();
success_flag = false;
}catch(BadLocationException e){
e.getMessage();
success_flag = false;
/* Searches through all HREF attributes that are now stored in Vector
vT for occurences of the character string ".htm" */
sortStrings = new String[countX];
for(int i=0;i<countX;i++)
sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
countY++;
if(sortStrings[i].endsWith("GIF"))
vS.addElement(sortStrings[i]);
countY++;
if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
countY++;
if(sortStrings[i].endsWith("JPG"))
vS.addElement(sortStrings[i]);
countY++;
finalStrings = new String[countY];
for(int j=0;j<countY;j++)
finalStrings[j] = (String)vS.elementAt(j);
/* What happens with these methods, will they need to have their
own treads also? */
public int getCount()
return countY; //Returns number of instances of htm strings
} //ending with either "jpg" or "gif".
public String[] xurlAddressDetails()
return finalStrings;
Are there any special things that I need to do in regard to the variables returned by the getCount() and xurlAddressDetails() methods. These methods are called by the code that started the run method from within my GUI. I don't understand which thread these methods are running in, obviously there is an AWT thread for my GUI and then a seperate thread for my FullURLAddress objects, but does this new thread also encompass the getCount() and xurlAddressDetails() methods?
Please explain.
This probably sounds a little wack, but I don't understand what thread is responisble for the methods in my FullURLAddress class aside of course from the run() method which is obvious. Any help will be awesome.
Thanks
DavoThreads are part of code that allows you to run multiple operations "simultaneously". "Simultaneously", because threads are not run actually simultaneously in any one-CPU machine. Since you most propably have only one CPU in your system, you can only execute one CPU instruction at time. Basically this means that your CPU can handle only one java-operation at time. It does not matter if you put some code in thread and start it, it will still take up all CPU time as long as the thread runs.
So you would need a way to let other threads run also, for that purpose thread contains a yield feature that allows you to give time for other threads to run.
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Thread.html#yield()
You need to use thread's yield() method in your thread code, in a place you want to give other threads time to run. Also bear in mind that if you yield your first thread run to allow second thread to run, you also need to add yield to the second thread also. If you don't, after yielding the first thread, the second thread will eat up all CPU time until it finishes, thus meaning the rest of your first thread will be run after second thread is done.
One good place to execute yield() is usually at the end of a loop, for example 'for' or 'while' loop. This way you prevent for example while-deadlocks.
Here is a java thread tutorial, worthy reading:
http://java.sun.com/docs/books/tutorial/essential/threads/ -
Class A extends B- where is paintComponent(Graphics) supposed to paint?
Hi,
i have the following problem: I thought ControlPanel.paintComponent(Graphics) was supposed to paint the GraphArea (since ConrolPanel.paintComponent(Graphics) overrides GraphAreaExtension.paintComponent(Graphics) ), but lines AND vertices appear on the ControlPanel. Any ideas?
import ...
public class GraphAreaExtension extends JPanel
public int clickCounter; //how many clicks have been performed, ie
//how many vertices have been painted
public int clickedX;
public int clickedY;
public Point[] darray;
public GraphAreaExtension()
setBorder(BorderFactory.createTitledBorder("Graph Area"));
setPreferredSize(new Dimension(640, 450));
setMaximumSize(new Dimension(640, 450));
clickCounter=0;
darray=new Point[8];
clickedX=-50;
clickedY=-50;
initializeDarray();
addMouseListener(new MouseAdapter()
public void mouseClicked (MouseEvent e)
clickCounter++;
if (clickCounter<=8)
clickedY=e.getY();
clickedX=e.getX();
darray[clickCounter-1]=new Point(clickedX, clickedY);
System.out.print("Click counter "+clickCounter+" ");
System.out.println("Mouse clicked X: "+clickedX+" Y:"+clickedY);
repaint();
validate();
}//GraphAreaExtension constructor
public void paintComponent(Graphics g)
System.out.println("paint vertex...");
g.drawOval(clickedX,clickedY, 25,25);
g.drawString(getVertexName(clickCounter),clickedX+11, clickedY+15);
printDarray();
private static String getVertexName(int num)
num=num+96;
char c=(char)num;
String s=String.valueOf(c);
return s.toUpperCase();
private void initializeDarray()
for (int i=0; i<darray.length; i++)
darray=new Point(0,0);
public void printDarray()
for (int i=0; i<darray.length;i++)
System.out.print(darray[i].getX()+"\t");
System.out.println();
for (int i=0; i<darray.length;i++)
System.out.print(darray[i].getY()+"\t");
System.out.println();
import ...
/* This is the Control Panel. 3 kinds of visual objects exist here:
* -the JCheckBoxes, which indicate the incoming connections: in1-in8
* -the JCheckBoxes, which indicate the outcoming connections: out1-out8
* -the "Enter" button, which when pressed updates the in/out-coming
* connections -graphically designs the edges, between the vertices.
* The data taken from the in/out-coming JCheckBoxes are stored inside
* 2 boolean arrays respectively: inCon and outCon.
public class ControlPanel extends GraphAreaExtension implements ItemListener
JPanel controlPanel;
JButton jb;
boolean[] inCon;
boolean[] outCon;
JCheckBox in1, in2, in3, in4, in5, in6, in7, in8;
JCheckBox out1, out2, out3, out4, out5, out6, out7, out8;
public ControlPanel()
inCon= new boolean[8];
outCon= new boolean[8];
initializeBooleanTable(inCon);
initializeBooleanTable(outCon);
setPreferredSize(new Dimension(800,150));
setBackground(Color.LIGHT_GRAY);
setBorder(BorderFactory.createTitledBorder("Connections"));
setPreferredSize(new Dimension(120, 150));
setMaximumSize(new Dimension(120, 150));
JLabel in= new JLabel("Incoming connections");
add(in);
in1=new JCheckBox("A");
in1.addItemListener(this);
add(in1);
in4=new JCheckBox("D");
in4.addItemListener(this);
add(in4);
in8=new JCheckBox("H");
in8.addItemListener(this);
add(in8);
JLabel out= new JLabel("Outcoming connections");
add(out);
out1=new JCheckBox("A");
add(out1);
out1.addItemListener(this);
out3=new JCheckBox("C");
add(out3);
out3.addItemListener(this);
out8=new JCheckBox("H");
add(out8);
out8.addItemListener(this);
initializeCheckbox();
/* pressing the Enter button, the data concerning the connections,
* which the user has entered are transformed into edges between the
* vertices.
* Incoming edges: Green and Outcoming: Red
jb= new JButton("Enter");
add(jb);
jb.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
printConnectionArrays();
repaint();
validate();
}//ControlPanel constructor
public void paintComponent(Graphics g)
System.out.println("paint edge...");
for (int i=0; i<darray.length; i++)
if (inCon==true)
System.out.println("Entered incoming edges condition for node num "+ (i+1));
g.drawLine(clickedX,clickedY,(int)darray[i].getX(), (int)darray[i].getY());
System.out.println("baseX "+clickedX+" baseY "+clickedY+" destX "+(int)darray[i].getX()+" destY "+(int)darray[i].getY());
g.setColor(Color.GREEN);
if (outCon[i]==true)
System.out.println("Entered outcoming edges condition for node num "+ (i+1));
g.drawLine(clickedX, clickedY,(int)darray[i].getX(), (int)darray[i].getY());
System.out.println("baseX "+clickedX+" baseY "+clickedY+" destX "+(int)darray[i].getX()+" destY "+(int)darray[i].getY());
g.setColor(Color.RED);
}//END for
initializeCheckbox();
initializeBooleanTable(inCon);
initializeBooleanTable(outCon);
/******************************Helper***Functions***************************/
/* unchecks Checkboxes for next use
public void initializeCheckbox()
in1.setSelected(false); out1.setSelected(false);
in8.setSelected(false); out8.setSelected(false);
public void itemStateChanged(ItemEvent e)
System.out.println("Entered ItemStateChanged()...");
Object source = e.getItemSelectable();
if (source.equals(in1)) inCon[0]=true;
else if (source.equals(in2)) inCon[1]=true;
else if (source.equals(in8)) inCon[7]=true;
if (source.equals(out1)) outCon[0]=true;
else if (source.equals(out2)) outCon[1]=true;
else if (source.equals(out8)) outCon[7]=true;
public void printConnectionArrays()
System.out.print("Incoming ");
for (int i=0; i<darray.length; i++)
System.out.print(inCon[i]+" ");
System.out.print("Outcoming ");
for (int i=0; i<darray.length; i++)
System.out.print(outCon[i]+" ");
System.out.println();
public static void initializeBooleanTable(boolean[] t)
for (int i=0; i<t.length-1; i++)
t[i]=false;I've not a clue which is faster, but from an OO point of view--the object should know how to draw itself.
-
Adding a JPanel from one class to another Class (which extends JFrame)
Hi everyone,
So hopefully I go about this right, and I can figure out what I'm doing wrong here. As an exercise, I'm trying to write a Tic-Tac-Toe (TTT) game. However, in the end it will be adaptable for different variations of TTT, so it's broken up some. I have a TTTGame.java, and TTTSquareFrame.java, and some others that aren't relavent.
So, TTTGame:import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import joshPack.jUtil.*;
public class TTTGame extends JFrame
private Integer sides = 3;
private TTTSquareFrame mainSquare;
private TTTGame newGame;
private Container contents;
private JPanel mainSquarePanel, addPanel;
public static void main(String [] args)
TTTGame newGame = new TTTGame();
newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public TTTGame()
super("Tic-Tac-Toe");
contents = getContentPane();
contents.setLayout(new FlowLayout());
addPanel = startSimple();
if(!addPanel.isValid())
System.out.println("Something's wrong");
contents.add(addPanel);
setSize(300, 300);
setVisible(true);
public JPanel startSimple()
mainSquare = new TTTSquareFrame(sides);
mainSquarePanel = mainSquare.createPanel(sides);
return mainSquarePanel;
}and TTTSquareFrame:import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import joshPack.jUtil.Misc;
public class TTTSquareFrame
private JPanel squarePanel;
private JButton [] squares;
private int square, index;
public TTTSquareFrame()
System.out.println("Use a constructor that passes an integer specifying the size of the square please.");
System.exit(0);
public TTTSquareFrame(int size)
public JPanel createPanel(int size)
square = (int)Math.pow(size, 2);
squarePanel = new JPanel();
squarePanel.setLayout(new GridLayout(3,3));
squares = new JButton[square];
System.out.println(MIN_SIZE.toString());
for(int i = 0; i < square; i++)
squares[i] = new JButton();
squares.setRolloverEnabled(false);
squares[i].addActionListener(bh);
//squares[i].setMinimumSize(MIN_SIZE);
squares[i].setVisible(true);
squarePanel.add(squares[i]);
squarePanel.setSize(100, 100);
squarePanel.setVisible(true);
return squarePanel;
}I've successfully added panels to JFrame within the same class, and this is the first time I'm modularizing the code this way. The issue is that the frame comes up blank, and I get the message "Something's wrong" and it says the addPanel is invalid. Originally, the panel creation was in the constructor for TTTSquareFrame, and I just added the mainSquare (from TTTGame class) to the content pane, when that didn't work, I tried going about it this way. Not exactly sure why I wouldn't be able to add the panel from another class, any help is greatly appreciated.
I did try and cut out code that wasn't needed, if it's still too much let me know and I can try and whittle it down more. Thanks.Yea, sorry 'bout that, I just cut out the parts of the files that weren't relevant but forgot to compile it just to make sure I hadn't left any remnants of what I had removed. For whatever it's worth, I have no idea what changed, but something did and it is working now. Thanks for your help, maybe next time I'll post an actual question that doesn't somehow magically solve itself.
EDIT: Actually, sorry, I've got the panel working now, but it's tiny. I've set the minimum size, and I've set the size of the panel, so...why won't it respond to that? It almost looks like it's being compressed into the top of the panel, but I'm not sure why.
I've compressed the code into:
TTTGame.java:
import java.awt.*;
import javax.swing.*;
public class TTTGame extends JFrame
private Integer sides = 3;
private TTTSquareFrame mainSquare;
private TTTGame newGame;
private Container contents;
private JPanel mainSquarePanel, addPanel;
public static void main(String [] args)
TTTGame newGame = new TTTGame();
newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public TTTGame()
super("Tic-Tac-Toe");
contents = getContentPane();
contents.setLayout(new FlowLayout());
mainSquare = new TTTSquareFrame(sides.intValue());
contents.add(mainSquare);
setSize(400, 400);
setVisible(true);
}TTTSquareFrame.java
import java.awt.*;
import javax.swing.*;
public class TTTSquareFrame extends JPanel
private JButton [] squares;
private int square, index;
private final Dimension testSize = new Dimension(50, 50);
public TTTSquareFrame(int size)
super();
square = (int)Math.pow(size, 2);
super.setLayout(new GridLayout(size, size));
squares = new JButton[square];
for(int i = 0; i < square; i++)
squares[i] = new JButton();
squares.setMinimumSize(testSize);
squares[i].setVisible(true);
super.add(squares[i]);
setSize(200, 200);
setVisible(true);
I've made sure the buttons are smaller than the size of the panel, and the panel is smaller than the frame, so...
Message was edited by:
macman104 -
Error: "Could not resolve [public class] to a component implementation
Here's another clueless newbie question! :-(
I define a public class "DynamicTextArea" at the top of the file, and get the compiler error message "Could not resolve <DynamicTextArea> to a component implementation" at the bottom of the same file.
Clearly, I don't understand something very basic.
(The code between the commenrted asterisks was originally in a separate package file, which I couldn't get either mxmlc or FlexBuilder to find, so rather than fight that issue now, I moved it into the same file.)
Here's the file:
<?xml version="1.0" encoding="utf-8" ?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
>
<!--****************************************************************-->
<mx:Script>
<![CDATA[
import flash.events.Event;
import mx.controls.TextArea;
public class DynamicTextArea extends TextArea{
public function DynamicTextArea(){
super();
super.horizontalScrollPolicy = "off";
super.verticalScrollPolicy = "off";
this.addEventListener(Event.CHANGE, adjustHeightHandler);
private function adjustHeightHandler(event:Event):void{
trace("textField.getLineMetrics(0).height: " + textField.getLineMetrics(0).height);
if(height <= textField.textHeight + textField.getLineMetrics(0).height){
height = textField.textHeight;
validateNow();
override public function set text(val:String):void{
textField.text = val;
validateNow();
height = textField.textHeight;
validateNow();
override public function set htmlText(val:String):void{
textField.htmlText = val;
validateNow();
height = textField.textHeight;
validateNow();
override public function set height(value:Number):void{
if(textField == null){
if(height <= value){
super.height = value;
}else{
var currentHeight:uint = textField.textHeight + textField.getLineMetrics(0).height;
if (currentHeight<= super.maxHeight){
if(textField.textHeight != textField.getLineMetrics(0).height){
super.height = currentHeight;
}else{
super.height = super.maxHeight;
override public function get text():String{
return textField.text;
override public function get htmlText():String{
return textField.htmlText;
override public function set maxHeight(value:Number):void{
super.maxHeight = value;
]]>
</mx:Script>
<!--****************************************************************-->
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private var str:String = "This text will be long enough to trigger " +
"the TextArea to increase its height.";
private var htmlStr:String = "This <b>text</b> will be <font color='#00FF00'>long enough</font> to trigger " +
"the TextArea to increase its height.";
private function setLargeText():void{
txt1.text = str;
txt2.text = str;
txt3.text = str;
txt4.text = str;
txt5.htmlText = htmlStr;
txt6.htmlText = htmlStr;
txt7.htmlText = htmlStr;
txt8.htmlText = htmlStr;
]]>
</mx:Script>
<DynamicTextArea id="txt1" width="300" height="14"/>
<DynamicTextArea id="txt2" width="300" height="20"/>
<DynamicTextArea id="txt3" width="300" height="28"/>
<DynamicTextArea id="txt4" width="300" height="50"/>
<DynamicTextArea id="txt5" width="300" height="14"/>
<DynamicTextArea id="txt6" width="300" height="20"/>
<DynamicTextArea id="txt7" width="300" height="28"/>
<DynamicTextArea id="txt8" width="300" height="50"/>
<mx:Button label="Set Large Text" click="setLargeText();"/>
</mx:Application>
Thanks for any insight you can provide!
HarveyGordon:
As you've noted, there were multiple misunderstandings.
Some are due to references in the language which are different from uses in pre-existing languages.
Take "name spaces". They look like URLs but they're not. One of the first errors I made when starting Flex was to try to browse to http://www.adobe.com/2006/mxml. I figured that it would have some description of the language. But it didn't. In spite of LOOKING like a URL, it doesn't point to anything; it's really just an arbitrary magic incantation, like "Open Sesame".
But, then when I wanted to use my OWN namespace, I find that it's NOT arbitrary, and does have to point to something, but it's still not a URL. The "AHA" moment was when Michael told me that "*" means "look in this directory for a file with the name later named in an import statement, but not named here". And if the file was in subfolder "X" I'd have to use "X.*", while if it were a URL I'd use slash instead of dot, but never an asterisk.
When the language syntax is so contrary to the expectations of people coming from a declarative language or web programming background, I think it is important to explicitly address the differences and disabuse them of their preconceptions. I think the same should apply to the ways in which ActionScript differs from ECMAScript.
Another problem adding to my confusion is the habit of naming variables with the names of keywords but with capitalization changes. Not only does that set readers up for subtle "gotchas", but makes it unclear which names are truly arbitrary, and which are required by the compiler.
It might be a good idea to have a convention of an identifiable format for user variables. Many authors use names like myButton for that purpose.
It would also be helpful if printed text could simulate the syntax coloring of the better editors, or at least have more in-source comments saying exactly what each line does. (Or both)
Another aid to understanding would be to provide a reference to the alternative (MXML or AS) way of doing anything, whenever you demonstrate one of the ways.
I find that the emphasis on using FlexBuilder distracts from a sense of what is really going on behind the scenes. E,g.: If FlexBuilder automatically sets up the folder structure, I don't learn to do it myself. I like to work at the code level, so when something goes wrong I don't have to worry about what level it went wrong at.
Also, not everyone is willing to drop $600 or $250 BEFORE they've learned whether they even like Flex. Your tutorials are, by definition, addressed to newcomers who may well not yet have committed to the expense of FlexBuilder. So more emphasis on using mxmlc would be nice. It would also be helpful to discuss how to use local servers, like Tomcat, during the development stage.
Thanks for asking my opinion. I'm afraid that my 40 years of programming experience may make it harder for me to adapt to this new style of programming than it would be for a kid with a tabula rasa. But, it looks like it'll be fun once I get over the hump!
Harvey -
How to set the size of a class that extends JDialog
Hi,
I was trying to set the size of my dialog window to be 600 by 600, but couldn't change it. Here is my code:
public class alii extends JDialog {
/** Creates new form alii */
public alii(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
private void initComponents() {
Container contentPane = getContentPane();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
closeDialog(evt);
pack();
public static void main(String args[]) {
JFrame frame = new JFrame();
alii a = new alii(new javax.swing.JFrame(), true);
frame.setSize(600,500);
frame.setLocation(200,200);
frame.setVisible(true);}}
Please help me with this and explain to me what is the problem and what needs to be changed.
CheersHi,
The code you sent me doesn't work, and the code I posted wasn't a complete, but there is the complete one. You can see now what the code does.
* alii.java
* Created on 15 November 2003, 13:31
* @author Ali
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
public class sun extends JDialog {
int x[] = new int[4];
int y[] = new int[4];
int w[] = new int[4];
int h[] = new int[4];
int Y_ax = 310;
double DrawGraf[][] = new double[4][4];
String line[] = new String[9];
double Perc[] = new double[4];
double Sum=0;
GUICanvas can;
double graphvalue[] = new double [5];
/** Creates new form alii */
public sun(Frame parent, boolean modal) {
super(parent, modal);
initComponents();
//setVisible(true);
//setSize(600,500);
//setLocation(200,200);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
private void initComponents() {
//Container contentPane = getContentPane();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
closeDialog(evt);
//contentPane.setSize(700,700);
//pack();
public void drawthegraph(String s)
/* try {
URL url = new URL(
"http://localhost:111/test/servlet/Compare?value="+s);
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
for (int c = 0; c<9; c++)
line[c] = in.readLine();
in.close();
}catch (Exception e){
e.printStackTrace();
graphvalue[0] = 200;
graphvalue[1] = 200;
graphvalue[2] = 100;
graphvalue[3] = 300;
graphvalue[4] = 20;
//graphvalue[4] = can.d2i(graphvalue[4]);
//System.out.println(line[8]);
Sum = graphvalue[0]+graphvalue[1]+graphvalue[2]+graphvalue[3];
Perc[0] = graphvalue[0]/Sum*200;
Perc[1] = graphvalue[1]/Sum*200;
Perc[2] = graphvalue[2]/Sum*200;
Perc[3] = graphvalue[3]/Sum*200;
System.out.println(Perc[0]);
DrawGraf[0][0] = 130;
DrawGraf[0][1] = Y_ax - Perc[0];
DrawGraf[0][2] = 60;
DrawGraf[0][3] = Perc[0];
DrawGraf[1][0] = DrawGraf[0][0]+60;
DrawGraf[1][1] = Y_ax - Perc[1];
DrawGraf[1][2] = 60;
DrawGraf[1][3] = Perc[1];
DrawGraf[2][0] = DrawGraf[1][0]+60;
DrawGraf[2][1] = Y_ax - Perc[2];
DrawGraf[2][2] = 60;
DrawGraf[2][3] = Perc[2];
DrawGraf[3][0] = DrawGraf[2][0]+60;
DrawGraf[3][1] = 310 - Perc[3];
DrawGraf[3][2] = 60;
DrawGraf[3][3] = Perc[3];
for(int d=0;d<4;d++)
x[d]=d2i(DrawGraf[d][0]);
y[d]=d2i(DrawGraf[d][1]);
w[d]=d2i(DrawGraf[d][2]);
h[d]=d2i(DrawGraf[d][3]);
repaint();
static int d2i(double d) {return (int) Math.round(d);}
public void paint (Graphics g)
g.setColor(Color.red);
for(int d=0;d<4;d++)
g.fill3DRect(x[d],y[d],w[d],h[d],true);
g.setColor(Color.blue);
g.drawLine(130,130,130,310);
g.drawLine(130,310,370,310);
g.setColor(Color.black);
g.drawString("WELCOME TO Ali",150,100);
g.drawString("Region: Lambeth",430,150);
g.drawString("Manger: ",430,170);
g.drawString("Location: ",430,190);
g.drawString("Number of Staff: "+graphvalue[4],430,210);
g.drawString("Week1",135,345);
g.drawString("Week2",195,345);
g.drawString("Week3",255,345);
g.drawString("Week4",315,345);
g.drawString(" "+"20 -",100,295);
g.drawString(" "+"40 -",100,255);
g.drawString(" "+"60 -",100,215);
g.drawString(" "+"80 -",100,175);
g.drawString("100 -",100,135);
g.setColor(Color.yellow);
g.drawLine(130,290,370,290);
g.drawLine(130,250,370,250);
g.drawLine(130,210,370,210);
g.drawLine(130,170,370,170);
g.drawLine(130,130,370,130);
/** Closes the dialog */
private void closeDialog(java.awt.event.WindowEvent evt) {
setVisible(false);
dispose();
* @param args the command line arguments
public static void main(String args[]) {
JFrame frame = new JFrame();
sun sn = new sun(frame, true);
frame.setSize(600,500);
frame.getContentPane().add(sn);
frame.setLocation(200,200);
frame.setVisible(true);
You were right that I am know to this, but getting there slowly and thanks for your help.
Cheers -
Calling public class method from the servlet dopost() implementation
Hi!
My application is a simple application where i wrote a JSP page to enter the USERNAME and PASSWORD. And this JSP will call a HttpServlet
with in which i am calling another Java class ValidateUser which will check aginst the Oracle Database table whether that Username and password combination exists and returns the user's name.
But when i am trying to call that method is throwing me an error. here is the typical code i wrote.
servlet
package isispack;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class Login extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException{
String userId = req.getParameter("user_id");
String password = req.getParameter("user_pass");
// if uName is null .. user is not authorized.
String uName = Validate(userId, password);
and
Validate class
package isispack;
import java.sql.*;
import java.util.*;
import java.lang.*;
public class ValidateUser
public String ValidateUser(String inputUserid, String inputPwd) throws
SQLException{
String returnString = null;
String dbUserid = "isis"; // our Database user id
String dbPassword = "isisos" ; // our Database password
Connection con = DriverManager.getConnection("jdbc:odbc:JdbcOdbcDriver","isis","osiris");
Statement stmt = con.createStatement();
String sql= "select user_id from isis_table where user_id = '" inputUserid + "' and user_pass= '" + inputPwd +"' ;" ;
ResultSet rs = stmt.executeQuery(sql);
if (rs.next())
returnString = rs.getString("user_id");
stmt.close();
con.close();
return returnString ;
The ERROR
Error(18,18): method ValidateUser(java.lang.String, java.lang.String) not found in class isispack.Login
One more thing i forgot to tell you. I am trying to run this application on JDeveloper. Please helpme out if you can . Thank you.
-SreekanthOK! I made it static method
and tried to call the method as follows
String uName = ValidateUser.ValidateUser(userId, password);
even if i create the instence and
ValidateUser Validate;
then call
String uName= Validate.ValidateUser(userId,password)
In either case is giving me the following error.Tarun, am new to Java programming, please help me out. And can you please tell me where can i find things in consise to brush up my fundamentals?.
Error(18,43): unreported exception: java.sql.SQLException; must be caught or declared to be thrown -
Pass a value to a class that extends AbstractTableModel
Hi
I have a problem with a table model that I cannot find a way of overcoming.
I have created a class called MyTableModel that extends AbstractTableModel.
MyTableModel creates and uses another class that I have defined in order to retrieve records from a database, MyTableModel fills the table with these records.
However, I wish to alter my class in order to provide an int parameter that will act as a �where� value in the classes sql query.
The problem is this, I cannot work out how to pass a value into MyTableModel. I have tried creating a simple constructor in order to pass the value but it doesn�t work.
My code is shown below:
import BusinessObjects.JobItemClass;
import DBCommunication.*;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class MyJobItemTableModel extends AbstractTableModel
public MyJobItemTableModel(int j)
jobNo = j;
int jobNo;
JobAllItems jobItems = new JobAllItems(jobNo);
ArrayList items = jobItems.getItems();
String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
int c = items.size();
Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
Object table[][] = new Object[c][4];
public void fillTable()
if(c > 0)
for (int i = 0; i < c; i = i + 1)
this.setValueAt(((JobItemClass) items.get(i)).getItemNumber(), i, 0);
this.setValueAt(((JobItemClass) items.get(i)).getDescription(), i, 1);
this.setValueAt(((JobItemClass) items.get(i)).getCostPerItem(), i, 2);
this.setValueAt(((JobItemClass) items.get(i)).getQuantity(), i, 3);
public void setJobNo(int s)
jobNo = s;
public int getColumnCount()
if(c > 0)
return table[0].length;
else
return 0;
public int getRowCount()
return table.length;
public Object getValueAt(int r, int c)
return table[r][c];
public String getColumnName(int column)
return columnName[column];
public Class getColumnClass(int c)
return columnType[c];
public boolean isCellEditable(int r, int c)
return false;
public void setValueAt(Object aValue, int r, int c)
table[r][c] = aValue;
}Any advice will be appreciated.
Many Thanks
GByour JobAllItems is created before constructor code is run (since it is initialized in class member declaration)
use something like
public MyJobItemTableModel(int j)
jobNo = j;
items = (new JobAllItems(jobNo)).getItems();
c = items.size();
table = new Object[c][4];
int jobNo;
ArrayList items;
String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
int c;
Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
Object table[][] ;instead of
public MyJobItemTableModel(int j)
jobNo = j;
int jobNo;
JobAllItems jobItems = new JobAllItems(jobNo);
ArrayList items = jobItems.getItems();
String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
int c = items.size();
Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
Object table[][] = new Object[c][4]; -
Create a new class which extends DataGrid
Can someone give me a simple example on how to create a new
class that extends DataGrid. Still having a little trouble
understanding classes.
Thanks for any help.
Jeremyimport mx.controls.DataGrid
public class MyGrid extends DataGrid {
It is pretty much as you would extend a class in Java -
Hi,
I need this applet as a class that extends JPanel, I will be very very thankful to you if any one kindly change this Applet code into a class that extends JApplet.
I will be very thankful to you if some one can reserve few minutes & do this favor early.
Thanks a lot for any help.
My Pong Code
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
public class Class1 extends Applet implements Runnable
{ private final int APPLET_WIDTH = 900;
private final int APPLET_HEIGHT = 600;
private int px = 15;
private final int py = 560;
private final int ph = 10;
private final int pw = 75;
private int old_px = px;
private int bx = 450;
private int by = 15;
private final int bh = 20;
private final int bw = 20;
private int move_x = 2;
private int move_y = 2;
private boolean done = false;
Thread t;
private final int delay = 25;
public void init()
{ setBackground(Color.black);
setSize(APPLET_WIDTH, APPLET_HEIGHT);
requestFocus();
addKeyListener(new DirectionKeyListener());
(t = new Thread(this)).start();
public void run() {
try { while((t == Thread.currentThread()) && (done == false)) {
if ((bx < 15) || (bx > APPLET_WIDTH-30)) move_x = -move_x; if ((by < 15) || ((by > APPLET_HEIGHT-60)&& ((px<=bx)&&(bx<=px+pw))))
move_y = -move_y;
if (by > APPLET_HEIGHT)
done = true;
bx = bx + move_x;
by = by + move_y; repaint();
t.sleep(delay);
catch(Exception e) {}
}//end run
/*public void move_paddle(int amount)
old_px = px;
//if (amount > 0)
//if (px <= APPLET_WIDTH-15)
px = px + amount;
//else if (amount < 0)
// if (px >= 15)
px = px + amount;
public void paint(Graphics page)
// page.setColor(Color.black);
// page.drawRect(old_px, py, pw, ph);
page.setColor(Color.blue);
page.drawRect(px, py, pw, ph);
page.setColor(Color.white);
page.drawOval(bx, by, bw, bh);
if ((done == true) && (by > APPLET_HEIGHT))
page.drawString("LOSER!!!", APPLET_WIDTH/2, APPLET_HEIGHT/2);
else if (done == true)
page.drawString("Game Over, Man!", APPLET_WIDTH/2-10, APPLET_HEIGHT/2);
private class DirectionKeyListener implements KeyListener
public void keyPressed (KeyEvent event)
switch (event.getKeyCode())
case KeyEvent.VK_LEFT:
old_px = px;
if (px >=15)
px -=10;
break;
case KeyEvent.VK_RIGHT:
old_px = px;
if (px+pw <= APPLET_WIDTH-15)
px += 10;
break;
case KeyEvent.VK_Q:
done = true;
default:
} //end switch
repaint();
}//end keyPressed
public void keyTyped (KeyEvent event)
public void keyReleased (KeyEvent event)
} //end class
}thank you sir for your advice.
Its not like that I without any attempt, just past code here & asked for its conversion. I spent about 5 hours on it, can say spoil whole day but to no avail. You then just guide me, give some hint so that I do it. I will most probably wanted to do it by myself but asked for help when was just disappointed.
I try to put all init() in default constructor of identical copy of this applet that extends JPanel. Problem.....ball tend to fell but pad not moving. Also out out was not getting ant color input. That was like my best effort.....other tried that I found by search like just do nothing only extend panel OR frame in spite of applet, start applet from within main of another class.... these are few I remember what I tried.
I will be very very thankful to you if you can help/guide me how can I do it. Behavior of the Applet is like a normal PONG game with on pad controlled by arrow keys, & one ball colliding with walls of boundary & falling down.
Thanks a lot again for your attention & time. -
JEditorPane (or subclasses) and a class that extends JPanel
hello to all,
i'm realizing an application with Swing.
i have realized a class that extends JPanel(called "PanelLayer") and, other to draw a ruler as Office 2003, it must contain an other subclass of JPanel (called "PanelLayer") that, in turn, will contain a JEditorPane.
the problem is strange: i should continue in moviment the mouse to look well the JEditorPane (or subclasses)
the URL is a image of the result that i get...
URL : http://phantom89.helloweb.eu/img/img.jpg
codes:
public class Layer extends JPanel implements ComponentListener{
private static final long serialVersionUID = 1L;
private Rectangle2D.Double areaCentrale = new Rectangle2D.Double(100,100,850,1285);
private double larghFoglio = 21.0*50;
private double altFoglio = 29.7*50;
private double zoom = 1.0;
private JScrollPane sp = new JScrollPane(this);
private Rectangle2D.Double posFoglio = new Rectangle2D.Double();
private int lastX,lastY;
private PanelLayer pl;
private Point mouse = null;
private JEditorPane text;
public Layer(PanelLayer pl){
this.setLayout(null);
this.pl = pl;
this.setPreferredSize(new Dimension((int)(40+larghFoglio*zoom), (int)(100+altFoglio*zoom)));
areaCentrale = new Rectangle2D.Double(100*zoom,100*zoom,850*zoom,1285*zoom);
sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//try{
text = new JEditorPane();
text.setBounds(50,50,200,200);
this.add(text);
//}catch(IOException e){}
lastX = sp.getHorizontalScrollBar().getValue();
lastY = sp.getVerticalScrollBar().getValue();
this.addComponentListener(this);
this.addMouseListener(this);
this.addMouseMotionListener(this);
public void paintComponent(Graphics g){
if(posFoglio.height + posFoglio.width == 0){
this.posFoglio = new Rectangle2D.Double((this.getWidth()-larghFoglio*zoom)/2,50,larghFoglio*zoom,altFoglio*zoom);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(Color.lightGray);
g2d.fillRect(0,0,this.getWidth(),this.getHeight());
g2d.translate((this.getWidth()-larghFoglio*zoom)/2,50);
g2d.setPaint(Color.black);
g2d.draw(new Rectangle2D.Double(0,0,larghFoglio*zoom,altFoglio*zoom));
g2d.setPaint(Color.white);
g2d.fill(new Rectangle2D.Double(1,1,larghFoglio*zoom-1,altFoglio*zoom-1));
g2d.setPaint(Color.blue);
g2d.draw(areaCentrale);
public JScrollPane getJScrollPane(){
return sp;
public Rectangle2D.Double getDimFoglio(){
return this.posFoglio;
public double getCmWidth(){
return larghFoglio*zoom/50+((larghFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
public double getCmHeight(){
return altFoglio*zoom/50+((altFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
public Point getPointMouse(){
return mouse;
public void refresh(){
lastX = sp.getHorizontalScrollBar().getValue();
posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
public double getIncr(){
return zoom/2;
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {
mouse = e.getPoint();
mouse.x -= sp.getHorizontalScrollBar().getValue();
mouse.y -= sp.getVerticalScrollBar().getValue();
pl.repaint();
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {
lastX = sp.getHorizontalScrollBar().getValue();
posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
lastY = sp.getVerticalScrollBar().getValue();
posFoglio.y = 50-lastY;
pl.repaint();
public void componentResized(ComponentEvent e) {
this.repaint();
pl.repaint();
public void componentShown(ComponentEvent e) {}
public class PanelLayer extends JPanel implements MouseWheelListener,MouseInputListener{
private static final long serialVersionUID = 1L;
private Layer layer;
private JScrollPane sp = null;
private boolean visualizzaMouse = false;
public PanelLayer(){
this.setLayout(null);
layer = new Layer(this);
layer.addMouseListener(this);
layer.addMouseMotionListener(this);
public void paintComponent(Graphics g){
if(layer.getDimFoglio().getWidth()+layer.getDimFoglio().getHeight() == 0){
layer.setSize(50,50);
if(sp == null){
sp = layer.getJScrollPane();
sp.addMouseWheelListener(this);
sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
this.add(sp);
}else{
layer.refresh();
sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(new Color(153,255,153));
g2d.fill(new Rectangle2D.Double(0,0,this.getWidth(),30));
g2d.fill(new Rectangle2D.Double(0,0,30,this.getHeight()));
g2d.setPaint(Color.black);
g2d.drawLine(0,0,this.getWidth(),0);
g2d.drawLine(0,30,this.getWidth(),30);
g2d.drawLine(0,0,0,this.getHeight());
g2d.drawLine(30,0,30,this.getHeight());
for(double i=0,j=0;i<=layer.getCmWidth();i+=layer.getIncr(),j++){
if(j%2==0){
g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 15,(int)(layer.getDimFoglio().x+31+i*50), 30);
g2d.drawString(String.valueOf((int)(j/2)), (float)(layer.getDimFoglio().x+31+i*50), 13);
}else{
g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 22,(int)(layer.getDimFoglio().x+31+i*50), 30);
for(double i=0,j=0;i<=layer.getCmHeight();i+=layer.getIncr(),j++){
if(j%2==0){
g2d.drawLine(15, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
g2d.drawString(String.valueOf((int)(j/2)),5,(float)(layer.getDimFoglio().y+31+i*50));
}else{
g2d.drawLine(22, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
if((layer.getPointMouse() != null)&&(visualizzaMouse)){
g2d.drawLine(layer.getPointMouse().x+30,0,layer.getPointMouse().x+30,30);
g2d.drawLine(0,layer.getPointMouse().y+30,30,layer.getPointMouse().y+30);
g2d.setPaint(new Color(153,255,153));
g2d.fillRect(1,1,29,29);
int largh = layer.getJScrollPane().getVerticalScrollBar().getWidth();
g2d.fillRect(this.getWidth()-largh, 1, largh, 29);
g2d.fillRect(1, this.getHeight()-largh, 29, largh);
public void mouseWheelMoved(MouseWheelEvent e) {
JScrollBar vsb = layer.getJScrollPane().getVerticalScrollBar();
vsb.setValue(vsb.getValue()+20*e.getWheelRotation());
public void refresh(){
if((layer != null)&&(sp != null)){
layer.setSize(this.getWidth()-30,this.getHeight()-30);
sp.setViewportView(layer);
this.repaint();
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
visualizzaMouse = true;
repaint();
public void mouseExited(MouseEvent e) {
visualizzaMouse = false;
repaint();
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
}(my english isn't very good)Don't really understand what the posted code does and I can't execute the code so I don't have much to offer.
But I did notice that you don't invoke super.paintComponent(...) which means you may have garbage being painted on the panels.
If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
http://homepage1.nifty.com/algafield/sscce.html -
ClassCastexception when casting a Class that extends HttpServletRequestWrap
I have inherited some code that runs OK in JDK 1.4.2 in a JSP, but give s an exception when the JSP runs unfer 1.5.0. My Class is a as follows:
public class WrappedRequest extends HttpServletRequestWrapper {
public WrappedRequest(HttpServletRequest req) {
super(req);
/** Return value string of requested parameter.
* <ul>
* <li> If htmlEncode == NO_HTML_ENCODE, return the native request param, un-html encoded
* <li> If htmlEncode == HTML_ENCODE, return an html encoded copy of the requested parameter
* <li> If htmlEncode is neither, return the html encoded copy of the requested parameter
* </ul>
* @param name name of the request parameter
* @param htmlEncode whether html encoded/un-encoded parameter value should be returned.
* @return String of the requested parameter value. If parameter name is null, return null
public String getParameter(String name, int htmlEncode) {
if(name != null && (htmlEncode == NO_HTML_ENCODE)) {
String str = super.getParameter(name);
return str;
else
return getParameter(name);
public String getParameter(String name) {
String str = super.getParameter(name);
if(str != null)
str = Utils.htmlEncode(str); //Another package class
return str;
This class in normally invoked as follows:
String changeApproval = ((WrappedRequest)request).getParameter("CrApp" , WrappedRequest.NO_HTML_ENCODE);
I get a ClassCastException exception on this line. Any suggestions?
Regards,Stuart_Millington wrote:
Further to my original post I have another question. Please bear in mind that I am fairly new to Java and this is code that I have inherited. In the following line of code (which is the line that causes the exception:
String changeApproval = ((WrappedRequest)request).getParameter("CrApp" , WrappedRequest.NO_HTML_ENCODE);
Why is the request being cast? The following code SEEMS to run OK:
WrappedRequest wr = new WrappedRequest(request);
String CrApproval = wr.getParameter("CrApp" , WrappedRequest.NO_HTML_ENCODE);
Any ideas?
Regards,
Stuart MillingtonOkay, then I understand your problem.
You can only cast request to WrappedRequest when request IS A WrappedRequest - ie the statement request = new WrappedRequest(request) was called. You are apparently trying to convert a default implementation of HttpServletRequest into a WrappedRequest without first 'Wrapping' the request.
What does Wrapping a Request mean and do? A request object is generated by the servlet container and it isn't easy to switch in your own implementation. So instead you make a WrappedRequest which takes the original instance of the HttpServletRequest generated from by the container and adds functionality to it. A WrappedRequest would have to extend an HttpServletRequest, and implement all the public API of said parent class. Most of the time the methods would look something like this:
public String getParameter(String key) { return this.parentRequest.getParameter(key); } That is, it simply delegates most of the work to the HttpServletRequest it is wrapping. But some functions it may want to change behavior for and for those you insert your implementation.
What you need to do:
1) Learn how to use Java before you touch Servlets and server side stuff. You are adding too much complication by going straight to the end game. Use a book and the tutorials to get you through.
2) Take the time to run the JavaEE tutorial.
3) Start with your own code. Taking code snippets you see around the net and trying to get them to work is tough when you don't understand the concepts. For example, using a WrappedRequest is normally fairly useless if it isn't implemented using a Filter, and they work the best when they don't require a change to the request interface (i.e. when you never actually have to do a cast). Since you don't know Filters, and don't yet understand how the wrapper works I would suggest not using them.
This is probably a mis-use of the RequestWrapper idea anyway (since, like I said, it requires a change in interface). What you would be better off doing is simply choosing to pass the parameter through a utility function that does the encoding for you. Example like:
String changeApproval = HTMLEncoder.encode(request.getParameter("CrApp");when you want the parameter encoded and
String changeApproval = request.getParameter("CrApp");when you don't.
If you don't want to make your own utility for this purpose (and why would you) you can download a library that does it for you. One example is the [org.apache.commons.lang.StringEscapeUtils#escapeXML|http://commons.apache.org/lang/apidocs/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)] class#method from the Apache Foundation. The StringEscapeUtils is part of the Apache Commons Lang project, which you can reach [At the Commons/lang website.|http://commons.apache.org/lang/]
Maybe you are looking for
-
How to get the values of the value table ?
Hello all, I want to get the values of the value table, given a domain name. Ex: To get the MATNR values of table MARA, giving the MATNR as input on the selection screen. Is it possible? Is there any FM? Thanks SR
-
SAP PI 7.0 configuration
i am trying to configure the SAP PI 7.0 in other client using Template based configuration. But by default its getting congigured in 001 client. how can we change the client in PI 7.0
-
Listener stop automatically when my application installation is done....
Hi All, I come across one incidence in my environment that when my application installation is finished , listener at oracle database goes down. I am using Oracle Enterprise Linxu 5.3 and database is 10.2.0.4. when looking to listener.log file for mo
-
Executing an oracle stored procedure in xMII 11.5
Dear all, I am facing problem executing an oracle stored procedure using sql query in MII. The SP does not have any input or output parameters & consists of only 2 insert statements. I tried to use Command Mode, FixedQuery & FixedQuery With out
-
Inserting FLV videos that allow student to start and stop anywhere
Hello, I am inserting flv videos that students need to be able to start and stop anywhere, and when the video reaches the end, the student clicks on the NEXT button to go to next slide. As long as the student lets the video play without any interrupt