Line Constructor
Hi
I have point geometries with id and i want to construct line geometry from this. If there are only two points for a line, i can pass start X, start Y, end X, end Y to sdo_ordinate_array.
But if i have intermediate vertices for a given id, how to do this as count of intermediate vertices is uncertain.
id x y
1 x1 y1
1 x2 y2
1 x3 y3
1 x4 y4
1 x5 y5
2 x1 y1
2 x2 y2
2 x3 y3
Thanks for your help..
Syed,
OK, here is an example that I hope reflects your situation.
Firstly, I will create a table called linepoints that I think contains data like yours:
create table linepoints as
SELECT case when trunc(level / 7) = 0 then 398639 else 2215595 end as feature_id,
row_number() over (partition by 1 order by rownum) as point_id,
sdo_geometry(2001,null,
sdo_point_type(round(dbms_random.value(1,10000),3),
round(dbms_random.value(1,10000),3),
NULL),NULL,NULL) as pointGeom
FROM dual
CONNECT BY LEVEL < 13;
-- Result
table LINEPOINTS created.This is what linepoints contains:
select * from linepoints;
-- Results
FEATURE_ID POINT_ID POINTGEOM
398639 1 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(512.505,9909.19,NULL),NULL,NULL)
398639 2 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(701.488,8150.579,NULL),NULL,NULL)
398639 3 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(753.581,2449.058,NULL),NULL,NULL)
398639 4 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(7160.47,6238.475,NULL),NULL,NULL)
398639 5 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(4550.681,1422.242,NULL),NULL,NULL)
398639 6 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(1972.044,6790.043,NULL),NULL,NULL)
2215595 7 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(1204.709,1973.255,NULL),NULL,NULL)
2215595 8 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(7485.635,2439.01,NULL),NULL,NULL)
2215595 9 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(5005.396,5022.274,NULL),NULL,NULL)
2215595 10 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(1180.856,6256.96,NULL),NULL,NULL)
2215595 11 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(6425.442,7360.927,NULL),NULL,NULL)
2215595 12 MDSYS.SDO_GEOMETRY(2001,NULL,MDSYS.SDO_POINT_TYPE(4200.348,5369.366,NULL),NULL,NULL)
12 rows selectedSecondly, given this table linepoints here is how I would create the linear (2002) sdo_geometry objects:
SELECT c.feature_id,
mdsys.sdo_geometry(2002,NULL,NULL,
mdsys.sdo_elem_info_array(1,2,1),
CAST(MULTISET(SELECT b.COLUMN_VALUE FROM linepoints a,table(mdsys.sdo_ordinate_array(a.pointGeom.sdo_point.x,a.pointGeom.sdo_point.y)) b where a.feature_id = c.feature_id order by a.point_id) as mdsys.sdo_ordinate_array))
as geom
FROM linepoints c
GROUP BY c.feature_id;
-- Results
FEATURE_ID GEOM
2215595 MDSYS.SDO_GEOMETRY(2002,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,2,1),MDSYS.SDO_ORDINATE_ARRAY(1204.709,1973.255,7485.635,2439.01,5005.396,5022.274,1180.856,6256.96,6425.442,7360.927,4200.348,5369.366))
398639 MDSYS.SDO_GEOMETRY(2002,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,2,1),MDSYS.SDO_ORDINATE_ARRAY(512.505,9909.19,701.488,8150.579,753.581,2449.058,7160.47,6238.475,4550.681,1422.242,1972.044,6790.043))If this is accurate and gives you the result you want, please mark my answer as being correct.
regard
Simon
Similar Messages
-
NotSerializable error while trying to write arraylist
I am getting a NotSerializable error while trying to write an arraylist to a file.
Here's the part of the code causing problem
File temp = fileOpenerAndSaver.getSelectedFile(); // fileOpenerAndSaver is a JFileChooser object which has been created and initialized and was already used to select a file with
currentWorkingFile = new File (temp.getAbsolutePath() + ".gd"); // currentWorking file is a file object
try
ObjectOutput output = new ObjectOutputStream (new BufferedOutputStream(new FileOutputStream(currentWorkingFile)));
output.writeObject(nodeList); // <-- This is the line causing problem (it is line 1475 on which exception is thrown)
output.writeObject(edgeList);
output.writeObject(nodesWithSelfLoop);
output.writeObject(nextId);
output.writeUTF(currentMessage);
output.close();
catch (Exception e2)
JOptionPane.showMessageDialog (graphDrawer, "Unknown error writing.", "Error", JOptionPane.ERROR_MESSAGE);
e2.printStackTrace();
} As far as what nodeList is -- it's an arraylist of my own class Node which has been serialized and any object used inside the class has been serialized as well.
Here is the declaration of nodeList:
private ArrayList <Node> nodeList; // ArrayList to hold a list all the nodesLet me show you whats inside the node class:
private class Node implements Serializable
private static final long serialVersionUID = -4625153386839971250L;
/* edgeForThisNodeList holds all the edges that are between this node and another node
* nodesConnected holds all the nodes that are connected (adjacent) to this node
* p holds the top left corner coordinate of this node. The centre. of this node is at (p.x + 5, p.y + 5)
* hasSelfLoop holds whether this node has a self loop.
* **NOTE**: ONLY ONE SELF LOOP IS ALLOWED FOR A NODE.
ArrayList <Edge> edgeForThisNodeList = new ArrayList <Edge> ();
ArrayList <Node> nodesConnected = new ArrayList <Node> ();
Point p;
boolean hasSelfLoop = false;
int index = -1;
BigInteger id;
... some methods following this....
}Here is the edge class
private class Edge implements Serializable
private static final long serialVersionUID = -72868914829743947L;
Node p1, p2; // The two nodes
Line2D line;
* Constructor:
* Assigns nodes provided as appropriate.
* Also calls the addEdge method on each of the two nodes, and passes
* "this" edge and the other node to the nodes, so that
* this edge and the other node can be added to the
* data of the node.
public Edge (Node p1, Node p2)
this.p1 = p1;
this.p2 = p2;
line = new Line2D.Float(p1.p.x+5,p1.p.y+5,p2.p.x+5,p2.p.y+5);
p1.addEdge(this, p2, true);
p2.addEdge(this, p1, false);
}Here is the error I am getting:
java.io.NotSerializableException: javax.swing.plaf.metal.MetalFileChooserUI
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at MyPanel.save(MyPanel.java:1475)
at GraphDrawer.actionPerformed(GraphDrawer.java:243)
I inentionally did not write the whole error stack because it was way too long and I ran out of characters. But line 1475 is where I do the writeObject call. I also goet some weird not serialized exceptions before on some other classes that are not being written to the file or are not part of the object that I am writing. I serialized those classes and now it's this unknown object that's causing problems.
Edit: The problem may be due to the JFileChooser I am using to select the file as it is a non-serializable object. But I am not trying to write it to the file and in fact am just writing the arrayLists and BigInteger as objects to the file.
Edited by: Cricket_struck on Dec 21, 2009 1:25 PM
Edited by: Cricket_struck on Dec 21, 2009 1:32 PM
Edited by: Cricket_struck on Dec 21, 2009 2:16 PMjava.io.NotSerializableException: javax.swing.plaf.metal.MetalFileChooserUIThat's a Swing component and it is clearly related to the JFileChooser.
I also get some weird not serialized exceptions before on some other classes that are not being written to the file or are not part of the object that I am writing.That's a contradiction in terms. If you get NotSerialzableException it means the objects are being written. So they are reachable from the objects you're writing.
Edit: The problem may be due to the JFileChooser I am using to select the file as it is a non-serializable object.JFileChooser implements Serializable, but you're right, you shouldn't try to serialize it. But clearly this is the current problem. Somewhere you have a reference to it reachable via the object(s) you are serializing.
I suspect that Node and Edge inner classes and that you aren't aware that inner classes contain a hidden reference to their containing class. The solution for serializaition purposes is to make them static nested classes, or outer classes. -
Creating class instances at different depths
I have a custom class called line that takes two sets of co
ordinates and draws a line between them.
The class uses _root.createEmptyMovieClip() to make a
container to draw in to but I need it to draw in to other movies on
the stage in a similar way to createEmptyMovieClip() eg
_root.childClip1.childClip2.line=new Line(x1,y1,x2,y2);
I have tried createEmptyMovieClip(),
this.createEmptyMovieClip(), _parent.createEmptyMovieClip() etc but
with no joy.
How can my Line constructor function get the path information
from the declaration or do I have to pass it as a parameter?Whenever I design a class, that class always takes a
target:MovieClip parameter. then I create a container for the class
inside that target. This way, I can place my class objects inside
any clip I so desire at any level. -
Hello everyone!! can you help;I am new to java programming. I have this project assignment to develop a small sofware that reads a file and use the data in the file to plot the graph, the prgm can read the file when the file name is entered but getting it to plot the graph, i am struggling with. please see the code below
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.Graphics.*;
import java.awt.Graphics2D.*;
public class BioxSim extends JFrame {
static Float a1=200F,a2=500F;//x
static Float b1=200F,b2=75F;//y
//JTextField to hold input data .
private JTextField data_in;
private JTextField data2_in;
//JLabel to show output results.
private JLabel degreesC;
private JLabel fileLabel;
//JTextArea to hold output results.
private JTextArea ta;
private FileReader readfile ;
private BufferedReader buffer ;
private JButton loadButton;
private JButton plotButton;
private JButton maths1;
private JButton maths2;
private JButton tempConversion;
private JButton saveButton;
private JButton clearButton;
private String line;
//Constructor for GoodDocs class - this method is used to set up the GUI
public BioxSim() {
// call the JFrame parent class with the window title
super("Data Conversion");
// we need the container for JFrames in order to add components
Container container = getContentPane();
FlowLayout flow = new FlowLayout();
container.setLayout(flow);
JLabel title = new JLabel("**************************************************************** Data Conversion Program *****************************************************");
container.add(title, new BorderLayout().NORTH);
//pos.gridx = 00; pos.gridy = 00;
// container.add(title);
// private label for the input units
JLabel units = new JLabel("X, Y Data ");
// private label to store prompt text
JLabel prompt = new JLabel(" Input data for [X], [Y] coorinates ");
JLabel fileLabel = new JLabel("File been Accessed is :" +line );
// create an instance of the JLabel holding the output result
degreesC = new JLabel("****************************** Example data: Input Degrees F; Output DegreesC Temp ******************************");
// pos.gridx = 0; pos.gridy = 3;
//container.add(prompt, pos);
// create an instance of the JTextField for a specific number of columns
data_in = new JTextField(15);
data2_in = new JTextField("C: ", 18 );
ta = new JTextArea(" The Output Data is Used to Plot the graph Below.", 3,62);
loadButton = new JButton("Load File");
plotButton =new JButton("PlotGraph");
maths1 = new JButton("Maths1");
maths2 = new JButton("Maths2");
tempConversion = new JButton("tempConversion");
saveButton = new JButton("Save");
clearButton = new JButton("Clear");
//pos.gridx =0; pos.gridy = 6;
container.add(degreesC);
container.add(prompt);
container.add(data_in);
container.add(units);
container.add(loadButton);
container.add(data2_in);
container.add(plotButton);
container.add( maths1);
container.add(maths2);
container.add(tempConversion);
container.add(saveButton);
container.add(clearButton);
container.add(fileLabel);
container.add(ta);
JScrollPane scroll = new JScrollPane(ta,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
container.add(scroll);
CustomPanel panel = new CustomPanel();
//Dimension dim = new Dimension(500, 400);
//JPanel panel = new JPanel();
panel.setPreferredSize( new Dimension(700,300));
panel.setMinimumSize( new Dimension( 200, 100 ) );
JScrollPane scroll1 = new JScrollPane(panel);
container.add(scroll1);
// register the TextField event handler - this is an inner class
TextFieldHandler handler = new TextFieldHandler();
data_in.addActionListener(handler);
loadButton.addActionListener(handler);
// set the applications size and make it visible
setSize(800, 550);
setVisible(true);
class CustomPanel extends JPanel
public void paintComponent (Graphics painter)
painter.setColor(Color.white);
painter.fillRect(0,0,getSize().width,getSize().height);
Color customPurple = new Color(128,0,128);
painter.setColor(customPurple);
painter.drawString("graph",250,60);
//Horizontal coordinate of the graph.
Graphics2D X_line2D = (Graphics2D) painter;
Line2D.Float X_line = new Line2D.Float(40F, 200F, 650F, 200F);
X_line2D.draw(X_line);
X_line2D.drawString("X coordinate", 50, 325);
//Vertical coordinate of the graph.
Graphics2D Y_line2D = (Graphics2D) painter;
Line2D.Float Y_line = new Line2D.Float(200F, 450F, 200F, 20F);
Y_line2D.draw(Y_line);
//Line representing mathematical functions, where a[n],b[n] resp.are variables.
Graphics2D Y1_line2D = (Graphics2D) painter;
//graphdata(a2,b2);
Line2D.Float Y1_line = new Line2D.Float(a1, b1, a2, b2);
Y1_line2D.draw(Y1_line);
//This method is used to execute the application */
public static void main(String args[]) {
// create an instance of our application
BioxSim application = new BioxSim();
// set the JFrame properties to respond to the window closing event
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
private String convertFtoC(String input) {
//variables to store the real values of the Strings
double tempF = 0.0;
double tempC = 0.0;
// use a try-catch block to contain data conversion exceptions
try {
// use the Double wrapper class to parse the string to a double
tempF = Double.parseDouble(input);
catch (NumberFormatException nfe) {
// no need to do anything here - errors will leave tempF = 0.0
// perform the conversion
tempC = 5.0 / 9.0 * (tempF - 32.0);
// return the result as a String
return Double.toString(tempC);
private String convertFtoC1(String input) {
// variables to store the real values of the Strings
double tempF = 0.0;
double tempC = 0.0;
// FileReadTest f = new FileReadTest();
// f.readMyFile("input");
// use a try-catch block to contain data conversion exceptions
try {
// use the Double wrapper class to parse the string to a double
tempF = Double.parseDouble(input);
catch (NumberFormatException nfe) {
// no need to do anything here - errors will leave tempF = 0.0
// perform the conversion
tempC = tempF;//5.0 / 9.0 * (tempF - 32.0);
// return the result as a String
return Double.toString(tempC);
/** Class TextFieldHandler implements ActionListner to provide the event handling
for this application. It is a private inner class, which gives it access to
all of the GoodDocs instance variables */
private class TextFieldHandler implements ActionListener {
/** This method is required for an ActionListener to process the events */
public void actionPerformed(ActionEvent event) {
String string = "";
String filename = null;
String taString;
// The user pressed Enter in the JTextField textField1
if(event.getSource() == data_in){
// retrieve the input as a String
// degreesC.setText("Input temperature is:" string "DegreeF");
string = convertFtoC(event.getActionCommand());
ta.setText(string);
// The user pressed Enter in the JTextField textField1
if(event.getSource() == loadButton)
filename = string;
// retrieve the input as a String
filename = data2_in.getText();
//fileLabel.setText("File been read is : " +filename );
try
readfile = new FileReader(new File(filename));
buffer = new BufferedReader (readfile);
String lineRead = buffer.readLine();
//clears the imput area
ta.setText("");
do
ta.append(lineRead+ "\n");
while ((lineRead = buffer.readLine()) != null);
buffer.close();
catch (IOException e)
if(event.getSource() == clearButton){
ta.setText("");
} // end of the private inner class TextFieldHandler
} // end of public class GoodDocs
DATA FILE e.g.
Time[sec] VD[g/m3] VDFlux[g/m3h] Flux[g/m2h] AmbT[C] AmbRH[%] ProbeT[C] ProbeRH[%] CondenserT[C] HeatsinkT[C]
0 1.025237E-02 0 -108.264 16.7752 61.27579 23.63191 48.14857 23.30489 23.22949
0.421 1.025237E-02 0 -108.264 16.7752 61.27579 23.63191 48.14857 23.30489 23.22949
0.828 1.025237E-02 0 -108.264 16.7752 61.27579 23.63191 48.14857 23.30489 23.22949
1.218 1.025581E-02 3.179105E-02 -108.229 16.7752 61.2831 23.63191 48.15666 23.30489 23.22949
1.609 1.025891E-02 2.856279E-02 -108.1975 16.7752 61.28748 23.63191 48.16799 23.30489 23.22949
1.968 1.025972E-02 8.050361E-03 -108.1893 16.7752 61.29041 23.63191 48.17554 23.30489 23.22949
2.343 1.026729E-02Don't forget to use the "Code Formatting Tags",
see http://forum.java.sun.com/help.jspa?sec=formatting,
so the posted code retains its original formatting. -
Ok trying a bit of programming, first in ages...
Trying to make 2 classes, Player and GameTest. Ok, what i want to do is for a prompt to ask the user for firstname, secondname, nickname etc...you will see in the code.
This is player:
import java.io.* ;
class Player
String line, firstName, secondName, nickName;
int age;
char sex;
// constructor
Player( String first, String last, String nick, int age, char sex )
firstName = first ;
secondName = last ;
nickName = nick ;
BufferedReader userIn =
new BufferedReader(
new InputStreamReader( System.in ) );
System.out.println("Please enter your first name:" );
firstName = userIn.readLine();
System.out.println("Please enter your second name:" );
secondName = userIn.readLine();
System.out.println("Please enter your nickName:" );
nickName = userIn.readLine();
System.out.println("Please enter your age:" );
line = userIn.readLine();
age = Integer.parseInt( line );
System.out.println("Are you male or female?:" );
sex = userIn.readLine();
//put in if m=male or f=female otherwise error
void details()
System.out.println( "Your details: " + firstName + secondName);//and all the rest....
}This is gameTest:
class GameTest
public static void main( String[] args )
Player player1 = new Player(
Andrew, Schofield, Sco, 22, M);
System.out.println( "Your details: "
+ player1.details() );
}Now instead of me typing in my details into the code, i would like to be prompted on it, so do I need all the lines of code prompting in the player class, or the game test?
My overall idea is to have like a text based story game, you know with loads of decisions which effect the way the book turns out. I want those decisions to effect characteristics which the user enters at the start, so age will increase, nickname may change etc etc, all depending on decisions in the story. I may also need to add more than 1 player, so thats why i have the player class...
Could anyone modify my code so that it will do what I want, either that or give me some simple advice to follow, as I am kind of new to java.
Any help?
ScoOk I seem to be stuck now. have managed to creater a player object by having the details entered into the code. I dont know how to make it so that the user can input the details himself...well I kind of do. In one of the posts I showed above, I used the readline method, but I am not sure how to get thisinfo to go into the constructor in my test class. Sorry if this doesn't make sense... Here is what i have:
import java.io.*;
class Player
// instance variables
String firstName; // First Name
String surName; // Second name
String nickName; // nick Name
int age;
String line;
// constructor
Player( String first, String sur, String nick, int age )
firstName = first;
surName = sur;
nickName = nick;
this.age = age;
BufferedReader userIn =
new BufferedReader(
new InputStreamReader( System.in ) );
// methods
String details()
String result = "\nFirst Name: "+firstName+"\nSur Name: "+surName+"\nNickname: "+nickName;
return result;
String names()
System.out.println("Please enter your first name:" );
firstName = userIn.readLine();
System.out.println("Please enter your second name:" );
surName = userIn.readLine();
System.out.println("Please enter your nickName:" );
nickName = userIn.readLine();
int age()
System.out.println("Please enter your age:" );
line = userIn.readLine();
age = Integer.parseInt( line );
}Now I can make each of the attributes (ie the 3 names) into seperate methods if its going to be easier?
Now I want the info it stores to replace this line of code in PlayerTest.java
Player player = new Player( "Andy", "Schofield", "Sco", 22 ); That is what I am not too sure of. If you could help that would be great.
EDIT: Actually can i just replace "Andy" with firstName, "Sco" with nickName or will that not work? Also my age keeps on coming out as 0, do I need to do something there too?
Cheers
Andy -
How can I resolve StackTrace data into a Method?
Howdy,
I am aware that using StackTraceElement will get me a method name, class name, and line number.
I'd like to resolve this information to a java.lang.reflect.Method, but when method names are overloaded there is no indicator (other than line number) which signature was called.
Has this problem been solved? Does someone have code to do this? Is there some key class or field somewhere that I have overlooked?
Thanks,
=AustinAustin_Hastings wrote:
The "greater context" is that I'd like to know what method called me, in such a way that I can look up annotations on that method.Not possible, I'm afraid. I still don't really know what the purpose would be, anyway. What is the greater context here, 'cos what you've posted above is just an extension of your requirements :-)
The only way I currently know of to get caller info is to get a stack trace element from the current thread, or by creating a fake Throwable. It isn't really "caller info", though, just a bit of debug. It isn't really designed to be used by your application
Sadly, stack trace elements resolve file and line number info, but I'm not aware of a Method(file, line) constructor :( so I'm wondering if anyone has already done this work.There isn't one. This isn't really what stack traces were designed for, and the Java runtime doesn't really provide what you're after. I can't honestly think what use it would be, either -
Print a line after each constructor
Would one of you java gods tell me how i can print a line after each constructor that tells me that the constructor has been constructed?
* Employee.java
* Created on April 28, 2007, 11:58 PM
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
* @author Pete Berardi
package edu.ctu.peteberardi.phase3db;
import java.util.Scanner;
public abstract class Employee extends Object
protected String EmpName;
protected String EmpAddress;
protected String EmpSsn;
protected String EmpEmployeeID;
protected double EmpYearlySalary;
protected double computePay;
protected String Constructor;
/** Creates a new instance of Employee */
public Employee(String name, String address, String ssn,
String id, double salary, double pay, String cvariable)
name = EmpName;
address = EmpAddress;
ssn = EmpSsn;
id = EmpEmployeeID;
salary = EmpYearlySalary;
pay = computePay;
public void setEmpName(String name)
EmpName = name;
public String getEmpName()
return EmpName;
public void setEmpAdress(String address)
EmpAddress = address;
public String getEmpAddress()
return EmpAddress;
public void setEmpSsn(String ssn)
EmpSsn = ssn;
public String getEmpSsn()
return EmpSsn;
public void setEmpID(String id)
EmpEmployeeID = id;
public String getEmployeeID()
return EmpEmployeeID;
public void setEmpYearlySalary(double salary)
EmpYearlySalary = salary;
public double getEmpYearlySalary()
return EmpYearlySalary;
public void setcomputePay(double pay)
computePay = pay;
public double computePay()
return computePay;
public void setContstructor(String cvariable)
Constructor = cvariable;
public String Constructor()
return Constructor;
public static void main( String args[])
System.out.print("Constructor has been constructed");
I do not know why you have declared the class as abstract. Abstract class must contain at least one abstract method.
In your code, there is no abstract method.
public Employee(String name, String address, String ssn,
String id, double salary, double pay, String cvariable)
name = EmpName;
address = EmpAddress;
ssn = EmpSsn;
id = EmpEmployeeID;
salary = EmpYearlySalary;
pay = computePay;
System.out.println("Constructor created");
}The above code works only when you instantiate the object for the class. If it is abstract class, it will not work.
Abstract class cannot be instantiated. -
A BG Renderer user is getting this error when running aerender version 10.5.1x2:
"Unable to execute script at line 95. Window does not have a constructor"
The render proceeds but the process never completes which is preventing the rest of the BG Renderer notifications from triggering. Any idea what this error means and how to fix it?
Thanks,
LloydI guess we'll have to wait for Adobe to answer what could be causing the transmission to drop on Line 95. Todd's out of the office for a month or two, but maybe someone else can shed some light.
-
Constructors and command lines
I would like to know how you allow command line input for a constructor created object.
For example, my patient class has a constructor that will create a patient with 5 parameters id, name, age, etc.....
public Patient(int d, String n, int a, int s, int x) {
id = d;
age = a;
tl = s;
name = n;
timearv = x;
In my Clinic class I would like to allow a user to be able to enter details on the command line to create a patient......DON'T KNOW HOW!!!
below is what i've come up with, but of course it doesnt work.....any help would be appreciated.....
Clinic c = new Clinic();
System.out.println("Add patient details");
Patient x = new Patient(id, name, age, tl,timearv);Normally you present the user with a form consisting of fields the user fills in. When the user is finished and presses an OK button you read the filled-in fields and convert them to the internal types you expect/need. This information is then used to create objects.
You can read about this in the Swing tutorial.
A simpler way is to read from the standard input like this,
http://javaalmanac.com/egs/java.io/ReadFromStdIn.html
You can convert the read Strings to numbers like this,
http://javaalmanac.com/egs/java.lang/ConvertNum.html -
Trying to use this() in a constructor, not the first line
I'm currently re-writing some old code of mine that was used to create a neural network. My main contructor, originally, was
public Network(int sizeLayer1, int sizeLayer2, int sizeLayer3) Now, however, I've decided that I want to make my network a little more general, and allow any number of layers. Therefore, my revised basic constructor is
public Network(int[] sizeLayers)which expects an array of ints corresponding to the size of each layer.
However, I've got some old programs that use the old contructor which I can't change (and anyway, it's good to have the option to be able to use both). I therefore want to create a constructor that has the same signature as the old one, but simply places the values in an array and passes the array to the new constructor.
public Network(int sizeLayer1, int sizeLayer2, int sizeLayer3) {
int[] sizeLayers = {sizeLayer1, sizeLayer2, sizeLayer3};
this(sizeLayers);
}obviously won't work, because 'this' must be the first line of the constructor. How can I put my values in an array and call the new constructor?
Thanks!Silly me -- I had been trying to do
this({sizeLayer1, sizeLayer2, sizeLayer3});but of course that wouldn't work.
Thank you very much for that reply!
However, more generally, what if I wanted to do a few lines of processing on the variables passed, like adding them together before calling this()? Is there no way to do that? What's the purpose of requiring that this() be the first line in the constructor?
Thanks! -
Value set in constructor is not getting saved in button Action method
Hi All,
I am not understanding why the value set ( On Condition )in constructor is not hold in the button actoin method.
Could any body explain me on that
for this I will try to explain with sample example
I have taken a button and add a integer property in session bean.
now if session bean's property is even then I am trying to set the button value to bidNow other wise Accept Invitation.
Till this opstion everything is OK
but once I click on Button,
Constructor is doing the right job only. But I do not understand why in button action I am getting the First Value only.
public Page1() {
// <editor-fold defaultstate="collapsed" desc="Creator-managed Component Initialization">
try {
if (getSessionBean1().getIntValue()%2==0)
button1.setValue("BidNow");
else
button1.setValue("Accept Invitation");
getSessionBean1().setIntValue(getSessionBean1().getIntValue()+1);
log("In Constructor Button Value : "+button1.getValue());
} catch (Exception e) {
log("Page1 Initialization Failure", e);
throw e instanceof javax.faces.FacesException ? (FacesException) e: new FacesException(e);
// </editor-fold>
// Additional user provided initialization code
public String button1_action() {
// TODO Replace with your code
log("In Action Button Value : "+button1.getValue());
return null;
}and here is the log
[#|2005-07-19T11:55:17.859+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
[#|2005-07-19T11:55:17.859+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:18.359+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
[#|2005-07-19T11:55:18.359+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:18.843+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
[#|2005-07-19T11:55:18.843+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:19.312+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
[#|2005-07-19T11:55:19.312+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:19.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
[#|2005-07-19T11:55:19.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:20.234+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
[#|2005-07-19T11:55:20.250+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:20.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
[#|2005-07-19T11:55:20.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:21.328+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
[#|2005-07-19T11:55:21.328+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:35.437+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
[#|2005-07-19T11:55:35.437+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:35.906+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
[#|2005-07-19T11:55:35.921+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:36.265+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
[#|2005-07-19T11:55:36.265+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:36.890+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
[#|2005-07-19T11:55:36.890+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:37.171+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
[#|2005-07-19T11:55:37.171+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
[#|2005-07-19T11:55:37.468+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
[#|2005-07-19T11:55:37.468+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]As per this log every time I am getting Bid Now only in action, though the value is changed in Construtcor
Can u explain the reason for thisHi Sudhakar,
Please try the following and you will get an idea as to what is happening:
1. Drag and drop a button, 2 outputText components
2. Add a property to the session bean called intValue of type int. Customize it to set it's initial value to 0
3. Add the following lines of code to the constructor
outputText1.setValue("" + getSessionBean1().getIntValue());
getSessionBean1().setIntValue(getSessionBean1().getIntValue()+1);
4. Double click on the button component to go to the button action method.
5. Add the following line of code
outputText2.setValue("" + etSessionBean1().getIntValue());
6. Save and run the application
7. Watch the values of outputText1 and outputText2 with each click of the button
Also, try the application with the following code block in the button action method:
if(getSessionBean1().getIntValue()%2==0){
button1.setValue("Bid Now");
} else{
button1.setValue("Accept Invitation");
getSessionBean1().setIntValue(getSessionBean1().getIntValue()+1);
outputText1.setValue(button1.getValue());
outputText2.setValue("" + getSessionBean1().getIntValue());
When the above code block is in the button action method the values set to button are as expected.
Hope that helps
Cheers
Giri :-) -
Passing arraylist between constructors?
Hi guys,
I've pretty new to java, and I think i'm having a little trouble
understanding scope. The program I'm working on is building a jtree
from an xml file, to do this an arraylist (xmlText) is being built and
declared in the function Main. It's then called to an overloaded
constructor which processes the XML into a jtree:
public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException
Later, in the second constructor which builds my GUI, I try and call
the same arraylist so I can parse this XML into a set of combo boxes,
but get an error thrown up at me that i'm having a hard time solving- :
public Editor( String title ) throws ParserConfigurationException
// additional code
// Create a read-only combobox- where I get an error.
String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);
JComboBox queryBox = new JComboBox(items);
JComboBox queryBox2 = new JComboBox(items);
JComboBox queryBox3 = new JComboBox(items);
JComboBox queryBox4 = new JComboBox(items);
JComboBox queryBox5 = new JComboBox(items);
This is the way I understand the Arraylist can be converted to a string
to use in the combo boxs. However I get an error thrown up at me here
at about line 206, which as far as I understand, is because when the
overloaded constructor calls the other constructor:
public Editor( String title ) throws ParserConfigurationException -
It does not pass in the variable xmlText.
I'm told that the compiler complains because xmlText is not defined
at that point:
- it is not a global variable or class member
- it has not been passed into the function
and
- it has not been declared inside the current function
Can anyone think of a solution to this problem? As I say a lot of this
stuff is still fairly beyond me, I understand the principles behind the
language and the problem, but the solution has been evading me so far.
If anyone could give me any help or a solution here I'd be very
grateful- I'm getting totally stressed over this.
The code I'm working on is below, I've highlighted where the error
crops up too- it's about line 200-206 area. Sorry for the length, I was
unsure as to how much of the code I should post.
public class Editor extends JFrame implements ActionListener
// This is the XMLTree object which displays the XML in a JTree
private XMLTree XMLTree;
private JTextArea textArea, textArea2, textArea3;
// One JScrollPane is the container for the JTree, the other is for
the textArea
private JScrollPane jScroll, jScrollRt, jScrollUp,
jScrollBelow;
private JSplitPane splitPane, splitPane2;
private JPanel panel;
// This JButton handles the tree Refresh feature
private JButton refreshButton;
// This Listener allows the frame's close button to work properly
private WindowListener winClosing;
private JSplitPane splitpane3;
// Menu Objects
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem newItem, openItem, saveItem,
exitItem;
// This JDialog object will be used to allow the user to cancel an exit
command
private JDialog verifyDialog;
// These JLabel objects will be used to display the error messages
private JLabel question;
// These JButtons are used with the verifyDialog object
private JButton okButton, cancelButton;
private JComboBox testBox;
// These two constants set the width and height of the frame
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 450;
* This constructor passes the graphical construction off to the
overloaded constructor
* and then handles the processing of the XML text
public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException
this( title );
textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
for ( int i = 1; i < xmlText.size(); i++ )
textArea.append( ( String )xmlText.get( i ) + "\n" );
try
XMLTree.refresh( textArea.getText() );
catch( Exception ex )
String message = ex.getMessage();
System.out.println( message );
}//end try/catch
} //end Editor( String title, String xml )
* This constructor builds a frame containing a JSplitPane, which in
turn contains two
JScrollPanes.
* One of the panes contains an XMLTree object and the other contains
a JTextArea object.
public Editor( String title ) throws ParserConfigurationException
// This builds the JFrame portion of the object
super( title );
Toolkit toolkit;
Dimension dim, minimumSize;
int screenHeight, screenWidth;
// Initialize basic layout properties
setBackground( Color.lightGray );
getContentPane().setLayout( new BorderLayout() );
// Set the frame's display to be WIDTH x HEIGHT in the middle of
the screen
toolkit = Toolkit.getDefaultToolkit();
dim = toolkit.getScreenSize();
screenHeight = dim.height;
screenWidth = dim.width;
setBounds( (screenWidth-FRAME_WIDTH)/2,
(screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
FRAME_HEIGHT );
// Build the Menu
// Build the verify dialog
// Set the Default Close Operation
// Create the refresh button object
// Add the button to the frame
// Create two JScrollPane objects
jScroll = new JScrollPane();
jScrollRt = new JScrollPane();
// First, create the JTextArea:
// Create the JTextArea and add it to the right hand JScroll
textArea = new JTextArea( 200,150 );
jScrollRt.getViewport().add( textArea );
// Next, create the XMLTree
XMLTree = new XMLTree();
XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION
XMLTree.setShowsRootHandles( true );
// A more advanced version of this tool would allow the JTree to
be editable
XMLTree.setEditable( false );
// Wrap the JTree in a JScroll so that we can scroll it in the
JSplitPane.
jScroll.getViewport().add( XMLTree );
// Create the JSplitPane and add the two JScroll objects
splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
jScrollRt );
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
jScrollUp = new JScrollPane();
jScrollBelow=new JScrollPane();
// Here is were the error is coming up
String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);
JComboBox queryBox = new JComboBox(items);
JComboBox queryBox2 = new JComboBox(items);
JComboBox queryBox3 = new JComboBox(items);
JComboBox queryBox4 = new JComboBox(items);
JComboBox queryBox5 = new JComboBox(items);
* I'm adding the scroll pane to the split pane,
* a panel to the top of the split pane, and some uneditible
combo boxes
* to them. Then I'll rearrange them to rearrange them, but
unfortunately am getting an error thrown up above.
panel = new JPanel();
panel.add(queryBox);
panel.add(queryBox2);
panel.add(queryBox3);
panel.add(queryBox4);
panel.add(queryBox5);
jScrollUp.getViewport().add( panel );
// Now building a text area
textArea3 = new JTextArea(200, 150);
jScrollBelow.getViewport().add( textArea3 );
splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
jScrollUp, jScrollBelow);
splitPane2.setPreferredSize( new Dimension(300, 200) );
splitPane2.setDividerLocation(100);
splitPane2.setOneTouchExpandable(true);
// in here can change the contents of the split pane
getContentPane().add(splitPane2,BorderLayout.SOUTH);
// Provide minimum sizes for the two components in the split pane
minimumSize = new Dimension(200, 150);
jScroll.setMinimumSize( minimumSize );
jScrollRt.setMinimumSize( minimumSize );
// Provide a preferred size for the split pane
splitPane.setPreferredSize( new Dimension(400, 300) );
// Add the split pane to the frame
getContentPane().add( splitPane, BorderLayout.CENTER );
//Put the final touches to the JFrame object
validate();
setVisible(true);
// Add a WindowListener so that we can close the window
winClosing = new WindowAdapter()
public void windowClosing(WindowEvent e)
verifyDialog.show();
addWindowListener(winClosing);
} //end Editor()
* When a user event occurs, this method is called. If the action
performed was a click
* of the "Refresh" button, then the XMLTree object is updated using
the current XML text
* contained in the JTextArea
public void actionPerformed( ActionEvent ae )
if ( ae.getActionCommand().equals( "Refresh" ) )
try
XMLTree.refresh( textArea.getText() );
catch( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
else if ( ae.getActionCommand().equals( "OK" ) )
exit();
else if ( ae.getActionCommand().equals( "Cancel" ) )
verifyDialog.hide();
}//end if/else if
} //end actionPerformed()
// Program execution begins here. An XML file (*.xml) must be passed
into the method
public static void main( String[] args )
String fileName = "";
BufferedReader reader;
String line;
ArrayList xmlText = null;
Editor Editor;
// Build a Document object based on the specified XML file
try
if( args.length > 0 )
fileName = args[0];
if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
".xml" ) )
reader = new BufferedReader( new FileReader( fileName )
xmlText = new ArrayList();
while ( ( line = reader.readLine() ) != null )
xmlText.add( line );
} //end while ( ( line = reader.readLine() ) != null )
// The file will have to be re-read when the Document
object is parsed
reader.close();
// Construct the GUI components and pass a reference to
the XML root node
Editor = new Editor( "Editor 1.0", xmlText );
else
help();
} //end if ( fileName.substring( fileName.indexOf( '.' )
).equals( ".xml" ) )
else
Editor = new Editor( "Editor 1.0" );
} //end if( args.length > 0 )
catch( FileNotFoundException fnfEx )
System.out.println( fileName + " was not found." );
exit();
catch( Exception ex )
ex.printStackTrace();
exit();
}// end try/catch
}// end main()
// A common source of operating instructions
private static void help()
System.out.println( "\nUsage: java Editor filename.xml" );
System.exit(0);
} //end help()
// A common point of exit
public static void exit()
System.out.println( "\nThank you for using Editor 1.0" );
System.exit(0);
} //end exit()
class newMenuHandler implements ActionListener
public void actionPerformed( ActionEvent ae )
textArea.setText( "" );
try
// Next, create a new XMLTree
XMLTree = new XMLTree();
XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION );
XMLTree.setShowsRootHandles( true );
// A more advanced version of this tool would allow the JTree
to be editable
XMLTree.setEditable( false );
catch( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
}//end actionPerformed()
}//end class newMenuHandler
class openMenuHandler implements ActionListener
JFileChooser jfc;
Container parent;
int choice;
openMenuHandler()
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = openItem.getParent();
}//end openMenuHandler()
public void actionPerformed( ActionEvent ae )
// Displays the jfc and sets the dialog to 'open'
choice = jfc.showOpenDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
String fileName, line;
BufferedReader reader;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
reader = new BufferedReader( new FileReader( fileName ) );
textArea.setText( reader.readLine() + "\n" );
while ( ( line = reader.readLine() ) != null )
textArea.append( line + "\n" );
} //end while ( ( line = reader.readLine() ) != null )
// The file will have to be re-read when the Document
object is parsed
reader.close();
XMLTree.refresh( textArea.getText() );
catch ( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
jfc.setCurrentDirectory( new File( fileName ) );
} //end if ( choice == JFileChooser.APPROVE_OPTION )
}//end actionPerformed()
}//end class openMenuHandler
class saveMenuHandler implements ActionListener
JFileChooser jfc;
Container parent;
int choice;
saveMenuHandler()
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = saveItem.getParent();
}//end saveMenuHandler()
public void actionPerformed( ActionEvent ae )
// Displays the jfc and sets the dialog to 'save'
choice = jfc.showSaveDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
String fileName;
File fObj;
FileWriter writer;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
writer = new FileWriter( fileName );
textArea.write( writer );
// The file will have to be re-read when the Document
object is parsed
writer.close();
catch ( IOException ioe )
ioe.printStackTrace();
}//end try/catch
jfc.setCurrentDirectory( new File( fileName ) );
} //end if ( choice == JFileChooser.APPROVE_OPTION )
}//end actionPerformed()
}//end class saveMenuHandler
class exitMenuHandler implements ActionListener
public void actionPerformed( ActionEvent ae )
verifyDialog.show();
}//end actionPerformed()
}//end class exitMenuHandler
class XmlFileFilter extends javax.swing.filechooser.FileFilter
public boolean accept( File fobj )
if ( fobj.isDirectory() )
return true;
else
return fobj.getName().endsWith( ".xml" );
}//end accept()
public String getDescription()
return "*.xml";
}//end getDescription()
}//end class XmlFileFilter
} //end class Editor
Sorry if this post has been a bit lengthy, any help you guys could give
me solving this would be really appreciated.
Thanks,
Iain.Hey. Couple pointers:
When posting, try to keep code inbetween code tags (button between spell check and quote original). It will pretty-print the code.
Posting code is good. Usually, though, you want to post theminimum amount of code which runs and shows your problem.
That way people don't have to wade through irrelevant stuff and
they have an easier time helping.
http://homepage1.nifty.com/algafield/sscce.html
As for your problem, this is a scope issue. You declare an
ArrayList xmlText in main(). That means that everywhere after
the declaration in main(), you can reference your xmlText.
So far so good. Then, inside main(), you call
Editor = new Editor( "Editor 1.0", xmlText );Now you've passed the xmlText variable to a new method,
Editor(String title, ArrayList xmlText) [which happens to be a
constructor, but that's not important]. When you do that, you
make the two variables title and xmlText available to the whole
Editor(String, ArrayList) method.
This is where you get messed up. You invoke another method
from inside Editor(String, ArrayList). When you call
this(title);you're invoking the method Editor(String title). You aren't passing
in your arraylist, though. You've got code in the Editor(String) method
which is trying to reference xmlText, but you'd need to pass in
your ArrayList in order to do so.
My suggestion would be to merge the two constructor methods into
one, Editor(String title, ArrayList xmlText). -
Hi Experts;
How do I add a caret listener on this code so that it will just add a number
when the user goes to the next line.
import java.awt.*;
import javax.swing.*;
public class LineNumber extends JComponent
private final static Color DEFAULT_BACKGROUND = new Color(213, 213, 234);
private final static Color DEFAULT_FOREGROUND = Color.white;
private final static Font DEFAULT_FONT = new Font("arial", Font.PLAIN, 11);
// LineNumber height (abends when I use MAX_VALUE)
private final static int HEIGHT = Integer.MAX_VALUE - 1000000;
// Set right/left margin
private final static int MARGIN = 5;
// Line height of this LineNumber component
private int lineHeight;
// Line height of this LineNumber component
private int fontLineHeight;
// With of the LineNumber component
private int currentRowWidth;
// Metrics of this LineNumber component
private FontMetrics fontMetrics;
* Convenience constructor for Text Components
public LineNumber(JComponent component)
if (component == null)
setBackground( DEFAULT_BACKGROUND );
setForeground( DEFAULT_FOREGROUND );
setFont( DEFAULT_FONT );
else
setBackground( DEFAULT_BACKGROUND );
setForeground( DEFAULT_FOREGROUND );
setFont( component.getFont() );
setPreferredSize( 99 );
public void setPreferredSize(int row)
int width = fontMetrics.stringWidth( String.valueOf(row) );
if (currentRowWidth < width)
currentRowWidth = width;
setPreferredSize( new Dimension(2 * MARGIN + width, HEIGHT) );
public void setFont(Font font)
super.setFont(font);
fontMetrics = getFontMetrics( getFont() );
fontLineHeight = fontMetrics.getHeight();
* The line height defaults to the line height of the font for this
* component. The line height can be overridden by setting it to a
* positive non-zero value.
public int getLineHeight()
if (lineHeight == 0)
return fontLineHeight;
else
return lineHeight;
public void setLineHeight(int lineHeight)
if (lineHeight > 0)
this.lineHeight = lineHeight;
public int getStartOffset()
return 4;
public void paintComponent(Graphics g)
int lineHeight = getLineHeight();
int startOffset = getStartOffset();
Rectangle drawHere = g.getClipBounds();
g.setColor( getBackground() );
g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
g.setColor( getForeground() );
int startLineNumber = (drawHere.y / lineHeight) + 1;
int endLineNumber = startLineNumber + (drawHere.height / lineHeight);
int start = (drawHere.y / lineHeight) * lineHeight + lineHeight - startOffset;
for (int i = startLineNumber; i <= endLineNumber; i++)
String lineNumber = String.valueOf(i);
int width = fontMetrics.stringWidth( lineNumber );
g.drawString(lineNumber, MARGIN + currentRowWidth - width, start);
start += lineHeight;
setPreferredSize( endLineNumber );
} Thanks for your time . . .
The_DeveloperHere's what I use. It behaves correctly WRT wrapped lines, and should work equally well with a JTextArea or a JTextPane.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.SizeSequence;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
* LineNumberView is a simple line-number gutter that works correctly
* even when lines are wrapped in the associated text component. This
* is meant to be used as the RowHeaderView in a JScrollPane that
* contains the associated text component. Example usage:
*<pre>
* JTextArea ta = new JTextArea();
* ta.setLineWrap(true);
* ta.setWrapStyleWord(true);
* JScrollPane sp = new JScrollPane(ta);
* sp.setRowHeaderView(new LineNumberView(ta));
*</pre>
* @author Alan Moore
public class LineNumberView extends JComponent
// This is for the border to the right of the line numbers.
// There's probably a UIDefaults value that could be used for this.
private static final Color BORDER_COLOR = Color.GRAY;
private static final int WIDTH_TEMPLATE = 99999;
private static final int MARGIN = 5;
private FontMetrics viewFontMetrics;
private int maxNumberWidth;
private int componentWidth;
private int textTopInset;
private int textFontAscent;
private int textFontHeight;
private JTextComponent text;
private SizeSequence sizes;
private int startLine = 0;
private boolean structureChanged = true;
* Construct a LineNumberView and attach it to the given text component.
* The LineNumberView will listen for certain kinds of events from the
* text component and update itself accordingly.
* @param startLine the line that changed, if there's only one
* @param structureChanged if <tt>true</tt>, ignore the line number and
* update all the line heights.
public LineNumberView(JTextComponent text)
if (text == null)
throw new IllegalArgumentException("Text component cannot be null");
this.text = text;
updateCachedMetrics();
UpdateHandler handler = new UpdateHandler();
text.getDocument().addDocumentListener(handler);
text.addPropertyChangeListener(handler);
text.addComponentListener(handler);
setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, BORDER_COLOR));
* Schedule a repaint because one or more line heights may have changed.
* @param startLine the line that changed, if there's only one
* @param structureChanged if <tt>true</tt>, ignore the line number and
* update all the line heights.
private void viewChanged(int startLine, boolean structureChanged)
this.startLine = startLine;
this.structureChanged = structureChanged;
revalidate();
repaint();
/** Update the line heights as needed. */
private void updateSizes()
if (startLine < 0)
return;
if (structureChanged)
int count = getAdjustedLineCount();
sizes = new SizeSequence(count);
for (int i = 0; i < count; i++)
sizes.setSize(i, getLineHeight(i));
structureChanged = false;
else
sizes.setSize(startLine, getLineHeight(startLine));
startLine = -1;
/* Copied from javax.swing.text.PlainDocument */
private int getAdjustedLineCount()
// There is an implicit break being modeled at the end of the
// document to deal with boundary conditions at the end. This
// is not desired in the line count, so we detect it and remove
// its effect if throwing off the count.
Element map = text.getDocument().getDefaultRootElement();
int n = map.getElementCount();
Element lastLine = map.getElement(n - 1);
if ((lastLine.getEndOffset() - lastLine.getStartOffset()) > 1)
return n;
return n - 1;
* Get the height of a line from the JTextComponent.
* @param index the line number
* @param the height, in pixels
private int getLineHeight(int index)
int lastPos = sizes.getPosition(index) + textTopInset;
int height = textFontHeight;
try
Element map = text.getDocument().getDefaultRootElement();
int lastChar = map.getElement(index).getEndOffset() - 1;
Rectangle r = text.modelToView(lastChar);
height = (r.y - lastPos) + r.height;
catch (BadLocationException ex)
ex.printStackTrace();
return height;
* Cache some values that are used a lot in painting or size
* calculations. Also ensures that the line-number font is not
* larger than the text component's font (by point-size, anyway).
private void updateCachedMetrics()
Font textFont = text.getFont();
FontMetrics fm = getFontMetrics(textFont);
textFontHeight = fm.getHeight();
textFontAscent = fm.getAscent();
textTopInset = text.getInsets().top;
Font viewFont = getFont();
boolean changed = false;
if (viewFont == null)
viewFont = UIManager.getFont("Label.font");
changed = true;
if (viewFont.getSize() > textFont.getSize())
viewFont = viewFont.deriveFont(textFont.getSize2D());
changed = true;
viewFontMetrics = getFontMetrics(viewFont);
maxNumberWidth = viewFontMetrics.stringWidth(String.valueOf(WIDTH_TEMPLATE));
componentWidth = 2 * MARGIN + maxNumberWidth;
if (changed)
super.setFont(viewFont);
public Dimension getPreferredSize()
return new Dimension(componentWidth, text.getHeight());
public void setFont(Font font)
super.setFont(font);
updateCachedMetrics();
public void paintComponent(Graphics g)
updateSizes();
Rectangle clip = g.getClipBounds();
g.setColor(getBackground());
g.fillRect(clip.x, clip.y, clip.width, clip.height);
g.setColor(getForeground());
int base = clip.y - textTopInset;
int first = sizes.getIndex(base);
int last = sizes.getIndex(base + clip.height);
String text = "";
for (int i = first; i <= last; i++)
text = String.valueOf(i+1);
int x = MARGIN + maxNumberWidth - viewFontMetrics.stringWidth(text);
int y = sizes.getPosition(i) + textFontAscent + textTopInset;
g.drawString(text, x, y);
class UpdateHandler extends ComponentAdapter
implements PropertyChangeListener, DocumentListener
* The text component was resized. 'Nuff said.
public void componentResized(ComponentEvent evt)
viewChanged(0, true);
* A bound property was changed on the text component. Properties
* like the font, border, and tab size affect the layout of the
* whole document, so we invalidate all the line heights here.
public void propertyChange(PropertyChangeEvent evt)
Object oldValue = evt.getOldValue();
Object newValue = evt.getNewValue();
String propertyName = evt.getPropertyName();
if ("document".equals(propertyName))
if (oldValue != null && oldValue instanceof Document)
((Document)oldValue).removeDocumentListener(this);
if (newValue != null && newValue instanceof Document)
((Document)newValue).addDocumentListener(this);
updateCachedMetrics();
viewChanged(0, true);
* Text was inserted into the document.
public void insertUpdate(DocumentEvent evt)
update(evt);
* Text was removed from the document.
public void removeUpdate(DocumentEvent evt)
update(evt);
* Text attributes were changed. In a source-code editor based on
* StyledDocument, attribute changes should be applied automatically
* in response to inserts and removals. Since we're already
* listening for those, this method should be redundant, but YMMV.
public void changedUpdate(DocumentEvent evt)
// update(evt);
* If the edit was confined to a single line, invalidate that
* line's height. Otherwise, invalidate them all.
private void update(DocumentEvent evt)
Element map = text.getDocument().getDefaultRootElement();
int line = map.getElementIndex(evt.getOffset());
DocumentEvent.ElementChange ec = evt.getChange(map);
viewChanged(line, ec != null);
} -
Can you create a "constructor" for movie clips?
What I'm doing:
var this_array[counter] = new monster; //monster is a movie clip
init_monster(); //set's things like .name, .x, .y, etc.
What I want to do:
var this_array[counter] = new monster();
When I add a "monster" I then call a function to "initialize" all of it's stats.
Is there a way in the creation of the object, like with a constructor, where it automatilly does it on 1 line?
I'm teaching myself and am a little stuck on this part. If I have to create a "monster class" to do what I want just say so.
Any simple examples or links to simple examples would be great. Thanks in advance.Ok so I've made a class Monster, and I have my movie object Red_Monster
How would I go about creating the variable so it knows it's both?
The only thing I can think of is linking them together as a .variable of the other.
Example:
var this_monster[x] = new Red_Monster();
this_monster[x].stats = new Monster();
It just seems a bit slopy, it would be nice to have this_monster know it's both. Is there a way to do that?
(added)
I've gotten Monster to extend MovieClip, and this is working to use it as a movieclip.
Currently trying to change the image of the movie clip in code to Red_Monster. Is there a way to do that?
(added)
Found how to do it, sort of. Change the class linkage name to Monster instead of Red_Monster. I just have to make classes for each movie clip.
(last add, answer for anyone else)
Ok the answer is to create a Monster class that extends MovieClip. Then for each color_Monster they all extend Monster, no other code needed inside each class other then the constructor. -
How can i copy line with text and image to ms word
When I insert an image in textflow using InlineGraphicElement it works, but when I copy the line with the image to MS Word it copies only the text (not the image).
How can i copy the image to MS Word?If you want copy formatted text and image to MS Word, you need to give MS Word rtf markup, because Word can recognize rtf markup but not TLF markup.
So you need to create a custom clipboard to paste a rtf markup. It's a large feature for you, because you need a tlf-rtf converter in your custom clipboard.
TLF Custom Clipboard Example:
package
import flash.display.Sprite;
import flash.desktop.ClipboardFormats;
import flashx.textLayout.container.ContainerController;
import flashx.textLayout.conversion.ITextImporter;
import flashx.textLayout.conversion.TextConverter;
import flashx.textLayout.edit.EditManager;
import flashx.textLayout.elements.*;
import flashx.undo.UndoManager;
// Example code to install a custom clipboard format. This one installs at the front of the list (overriding all later formats)
// and adds a handler for plain text that strips out all consonants (everything except aeiou).
public class CustomClipboardFormat extends Sprite
public function CustomClipboardFormat()
var textFlow:TextFlow = setup();
TextConverter.addFormatAt(0, "vowelsOnly_extraList", VowelsOnlyImporter, AdditionalListExporter, "air:text" /* it's a converter for cliboard */);
private const markup:String = '<TextFlow whiteSpaceCollapse="preserve" version="2.0.0" xmlns="http://ns.adobe.com/textLayout/2008"><p><span color=\"0x00ff00\">Anything you paste will have all consonants removed.</span></p></TextFlow>';
private function setup():TextFlow
var importer:ITextImporter = TextConverter.getImporter(TextConverter.TEXT_LAYOUT_FORMAT);
var textFlow:TextFlow = importer.importToFlow(markup);
textFlow.flowComposer.addController(new ContainerController(this,500,200));
textFlow.interactionManager = new EditManager(new UndoManager());
textFlow.flowComposer.updateAllControllers();
return textFlow;
import flashx.textLayout.conversion.ITextExporter;
import flashx.textLayout.conversion.ConverterBase;
import flashx.textLayout.conversion.ITextImporter;
import flashx.textLayout.conversion.TextConverter;
import flashx.textLayout.elements.IConfiguration;
import flashx.textLayout.elements.TextFlow;
class VowelsOnlyImporter extends ConverterBase implements ITextImporter
protected var _config:IConfiguration = null;
/** Constructor */
public function VowelsOnlyImporter()
super();
public function importToFlow(source:Object):TextFlow
if (source is String)
var firstChar:String = (source as String).charAt(0);
firstChar = firstChar.toLowerCase();
// This filter only applies if the first character is a vowel
if (firstChar == 'a' || firstChar == 'i' || firstChar == 'e' || firstChar == 'o' || firstChar == 'u')
var pattern:RegExp = /([b-df-hj-np-tv-z])*/g;
source = source.replace(pattern, "");
var importer:ITextImporter = TextConverter.getImporter(TextConverter.PLAIN_TEXT_FORMAT);
importer.useClipboardAnnotations = this.useClipboardAnnotations;
importer.configuration = _config;
return importer.importToFlow(source);
return null;
public function get configuration():IConfiguration
return _config;
public function set configuration(value:IConfiguration):void
_config = value;
import flashx.textLayout.elements.ParagraphElement;
import flashx.textLayout.elements.SpanElement;
import flashx.textLayout.elements.ListElement;
import flashx.textLayout.elements.ListItemElement;
class AdditionalListExporter extends ConverterBase implements ITextExporter
/** Constructor */
public function AdditionalListExporter()
super();
public function export(source:TextFlow, conversionType:String):Object
if (source is TextFlow)
source.getChildAt(source.numChildren - 1).setStyle(MERGE_TO_NEXT_ON_PASTE, false);
var list:ListElement = new ListElement();
var item1:ListItemElement = new ListItemElement();
var item2:ListItemElement = new ListItemElement();
var para1:ParagraphElement = new ParagraphElement();
var para2:ParagraphElement = new ParagraphElement();
var span1:SpanElement = new SpanElement();
span1.text = "ab";
var span2:SpanElement = new SpanElement();
span2.text = "cd";
list.addChild(item1);
list.addChild(item2);
item1.addChild(para1);
para1.addChild(span1);
item2.addChild(para2);
para2.addChild(span2);
source.addChild(list);
var exporter:ITextExporter = TextConverter.getExporter(TextConverter.TEXT_LAYOUT_FORMAT);
exporter.useClipboardAnnotations = this.useClipboardAnnotations;
return exporter.export(source, conversionType);
return null;
Maybe you are looking for
-
Safari locks up when I try to open it, ultimatley will not open
When I click on the Safari icon in my dock, it shows Safari in the toolbar at the top of my screen, but it just shows the spinning beach ball with no safari window actually on my screen. I have to "force quit" the application in order to get out of i
-
Filtering extended event in sql server 2008 r2
This code has been generated in sql server 2012 (using the graphical interface). CREATE EVENT SESSION [backupsmssql] ON SERVER ADD EVENT sqlserver.sp_statement_starting( ACTION( sqlserver.client_app_name, sqlserver.client_hostname,sqlserver.nt_userna
-
Need help in the use of 'setVisible()'
Well i am having some problems using the setVisible() method. what i want to do is to have a textfield appear when a button is clicked. It have a button and a textfield and i add it in the init() method. i also added a actionlistener to the button an
-
What program(s) opens the airport utility download file
I am installing on PC and have nothing to open a dmg file - any suggestions
-
Hi, I created an applet (extends JApplet). if the applet is not packaged, it can be displayed properly on HTML page with tag: <applet codebase="file:///F:/temp/paper" code="UserJApplet.class" width=400 height=300 > </applet> but if It is packaged, it