Sequential.java [28:1] cannot resolve symbol
The program asks users to enter random numbers.They are stored in a vector. The numbers are then added and the results of the addition stored in an vector.ie
sum1=item1
sum2=item1+item2
sum3=item1+item2+item3
sumn=item1+item2+,,,,,+itemn
here is the program
import java.util.Vector;
import java.io.*;
public class Sequential {
/** Creates a new instance of Sequential */
public Sequential() {
public static int inputInt(String str){
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
System.out.println(str);
int val;
try{
val = Integer.parseInt(input.readLine());
}catch(Exception e){}
return val;
public static void main (String args[]){
//initialising
Vector myarray = new Vector();
Vector sum = new Vector();
int ans = 0;
int dim;
dim = inputInt("Enter the array dimension");
//populate the
for(int i=0; i < dim; i++){
myarray.add(i,inputInt("Enter the array dimension"));
for(int i=0; i < dim; i++ ){
ans = Integer.parseInt(myarray.get(i)) + ans;
sum.add(i,ans);
for(int i=0; i < dim; i++){
System.out.println("Item [" + i + "] is " + sum.get(i));
it dispalys on ".add" part
Sequential.java [28:1] cannot resolve symbol in
myarray.add(i,inputInt("Enter the array dimension"));
Vectors store objects, not primitives.
Try the Integer wrapper class, e.g. myarray.add(i, new Integer(inputInt("Enter the array dimension")));
There are some other code problems I think you'll notice, but you should be able to work those out.
Similar Messages
-
Import java.util.Formatter - cannot resolve symbol
I use j2sdk1.4.2_04
when I try to compile my program using Formatter, it response error "cannot resolve symbol"
Pls help!Where did you get this java.util.Formatter from? If you check the official 1.4.2 API for Java, that class does not exisit! However, java.util.logging.Formatter, does exisit...
http://java.sun.com/j2se/1.4.2/docs/api/
If you ment: java.util.logging.Formatter have you checked the API to make sure you are using it correctly???
HTH. -
Cannot resolve symbol - getCodeBase()
Hey,
I'm trying to read from a file into my java applet however, I get the following error:
Player.java [49:1] cannot resolve symbol
symbol : method getCodeBase ()
location: class Player
url = new URL(getCodeBase().toString() + "/bot" + playerNo + ".txt");
^
1 error
Errors compiling Player.
The ^ should point at the 'g' of getCodeBase. I'm not sure what is up as I import both .net.* and .applet.* and have used similar syntax in another class which works fine. Any ideas what's up?getCodeBase() is an Applet method. You need you have a reference to the applet.,
-
3 graphic errors- Cannot resolve Symbols
I am looking for help to resolve 3 errors that I don't understand and I am hoping someone can take the time to point me in the right directions.
The errors occur while setting the forground color, trying to repaint and trying to draw a rectangle.
Here are the errors from the compiler:
Worm.java [42:1] cannot resolve symbol
symbol : method setForeground (java.awt.Color)
location: class Worm
setForeground(Color.RED);
^
Worm.java [49:1] cannot resolve symbol
symbol : method repaint ()
location: class Worm
repaint();
^
Worm.java [56:1] cannot resolve symbol
symbol : method drawRectangle (int,java.awt.Rectangle,int,int)
location: class java.awt.Graphics
g.drawRectangle(rec.x, rec[i], rec[i].height, rec[i].width );
^
3 errors
Errors compiling Worm.java.
The code follows:
Thanks for any assistance inadvance
WBR
import java.awt.*;
import java.awt.Graphics.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Rectangle.*;
import java.io.*;
import java.util.*;
class WormFrame extends JFrame{
public WormFrame(){
setTitle("CenteredFrame");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenHeight = d.height;
int screenWidth = d.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
public class Worm{
Rectangle rec[];
private Worm(){
Rectangle rec[] = new Rectangle [25];
int x = 25;
int y = 25;
for(int i = 0; i < rec.length; i++ ){
rec.x = x++;
rec[i].y = y++;
rec[i].height = 1;
rec[i].width = 1;
private void wormDraw( ){
setForeground(Color.RED); // Error 1
for(int a = 1; a < 20; a++){
for(int i = 1; i < rec.length; i++ ){
rec[i].x += 1;
rec[i].y += 1;
repaint(); // Error 2
public void paint(Graphics g) {
System.out.println("paint : " + new Date( ) );
// Draw dots
for(int i = 0; i < rec.length; i++ ){
g.drawRectangle(rec[i].x, rec[i], rec[i].height, rec[i].width ); // Error 3
public static void main(String[] args){
JFrame frame = new WormFrame();
frame.show();
Worm w = new Worm();
w.wormDraw();Hello! This works...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Worm extends JFrame
Rectangle rec[];
public Worm()
setTitle("CenteredFrame");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenHeight = d.height;
int screenWidth = d.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
setVisible(true);
rec = new Rectangle [25];
int x = 25;
int y = 25;
for(int i = 0; i < rec.length; i++ )
System.out.println("Creating rec " + i);
rec[i] = new Rectangle();
rec.x = x++;
rec[i].y = y++;
rec[i].height = 1;
rec[i].width = 1;
public void wormDraw( )
setForeground(Color.RED);
for(int a = 1; a < 20; a++)
for(int i = 1; i < rec.length; i++ )
System.out.println("Drawing rec " + i);
rec[i].x += 1;
rec[i].y += 1;
System.out.println("Calling paint");
repaint();
validate();
System.out.println("Done");
public void paint(Graphics g)
System.out.println("paint : " + new Date( ) );
for(int i = 0; i < rec.length; i++ )
g.fillRect(rec[i].x, rec[i].y, rec[i].height, rec[i].width);
public static void main(String[] args)
new Worm().wormDraw();
regards,
Liam -
A cannot resolve symbol question
I have this code: CurrencyTable is just a class extended from JTable and has only one constructor with string parameter. So I get one error for each those lines:
euro = new CurrencyTable("euro");
dollar = new CurrencyTable("dollar");
chf = new CurrencyTable("chf");
Could you explain me why I can't declare my variables like this ? Thanks
import javax.swing.*;
public class YearPane extends JTabbedPane{
private String name;
private int index;
private CurrencyTable euro;
private CurrencyTable dollar;
private CurrencyTable chf;
private GraphicPanel gpanel;
public YearPane(String aname, int anindex) {
name = aname;
index = anindex;
euro = new CurrencyTable("euro");
dollar = new CurrencyTable("dollar");
chf = new CurrencyTable("chf");
gpanel = new GraphicPanel();
}In fact I don't use the package instructions... Here are the errors:
Chargement/YearPane.java [28:1] cannot resolve symbol
symbol : constructor CurrencyTable (java.lang.String)
location: class CurrencyTable
euro = new CurrencyTable("euro");
^
Chargement/YearPane.java [29:1] cannot resolve symbol
symbol : constructor CurrencyTable (java.lang.String)
location: class CurrencyTable
dollar = new CurrencyTable("dollar");
^
Chargement/YearPane.java [30:1] cannot resolve symbol
symbol : constructor CurrencyTable (java.lang.String)
location: class CurrencyTable
chf = new CurrencyTable("chf");
^
3 errors
Errors compiling YearPane. -
Cannot Resolve Symbol: Runtime.getRuntime().gc()
Hi
I'm a Java noob, and this is driving me insane trying to get this working, I'm trying to invoke garbage collection with:
Runtime.getRuntime().gc();
but on compiling I get the error:
------- Compiler says -------
Scroller.java -> line 50
cannot resolve symbol
symbol : method gc ()
location: class java.lang.Runtime
Any ideas?
Thanksrmanchigiah wrote:
Yes, I understand that the JVM clears the garbage automatically, But would'nt calling the gc() method amount to invoking the gc, albeit phrased differently. A scenario , i have encountered - where the gc method is called( or invoked) is when a user is logging out of a session and the application continues to run... So, we would effectively be requesting the JVM to collect garbage if it has'nt already done so... And this is something i am not too sure about , i have a faint memory of reading something about programatically collecting garbage in ways that are more efficient than the JVM implementation...The application (I assume you mean a Swing or AWT program) will only continue to run if there is at least one non-daemon thread left running. Garbage collection will not change this. -
Cannot resolve symbol java.awt.graphics
// DrawRectangleDemo.java
import java.awt.*;
import java.lang.Object;
import java.applet.Applet;
public class DrawRectangleDemo extends Applet
public void paint (Graphics g)
// Get the height and width of the applet's drawing surface.
int width = getSize ().width;
int height = getSize ().height;
int rectWidth = (width-50)/3;
int rectHeight = (height-70)/2;
int x = 5;
int y = 5;
g.drawRect (x, y, rectWidth, rectHeight);
g.drawString ("drawRect", x, rectHeight + 30);
x += rectWidth + 20;
g.fillRect (x, y, rectWidth, rectHeight);
// Calculate a border area with each side equal tp 25% of
// the rectangle's width.
int border = (int) (rectWidth * 0.25);
// Clear 50% of the filled rectangle.
g.clearRect (x + border, y + border,
rectWidth - 2 * border, rectHeight - 2 * border);
g.drawString ("fillRect/clearRect", x, rectHeight + 30);
x += rectWidth + 20;
g.drawRoundRect (x, y, rectWidth, rectHeight, 15, 15);
g.drawString ("drawRoundRect", x, rectHeight + 30);
x=5;
y += rectHeight + 40;
g.setColor (Color.yellow);
for (int i = 0; i < 4; i++)
g.draw3DRect (x + i * 2, y + i * 2,
rectWidth - i * 4, rectHeight - i * 4, false);
g.setColor (Color.black);
g.drawString ("draw3DRect", x, y, + rectHeight + 25);
x += rectWidth + 20;
g.setColor (Color.yellow);
g.fill3DRect (x, y, rectWidth, rectHeight, true);
g.setColor (Color.black);
g.drawString ("fill3DRect", x, y, + rectHeight + 25);
Help me with this codes. I typed correctly but there still errors.
--------------------Configuration: JDK version 1.3.1 <Default>--------------------
D:\Program Files\Xinox Software\JCreator LE\MyProjects\DrawRectangleDemo.java:56: cannot resolve symbol
symbol : method drawString (java.lang.String,int,int,int)
location: class java.awt.Graphics
g.drawString ("draw3DRect", x, y, + rectHeight + 25);
^
D:\Program Files\Xinox Software\JCreator LE\MyProjects\DrawRectangleDemo.java:64: cannot resolve symbol
symbol : method drawString (java.lang.String,int,int,int)
location: class java.awt.Graphics
g.drawString ("fill3DRect", x, y, + rectHeight + 25);
^
2 errors
Process completed.
-------------------------------------------------------------------------------------------------------------------------------cannot resolve symbol
symbol : method drawString (java.lang.String,int,int,int)
This is telling you that you are trying to invoke the drawString() method with 4 parameters: String, int, int, int
If you look at the API the drawString() method need 3 parameters: String, int, int - so you have an extra int
location: class java.awt.Graphics
g.drawString ("draw3DRect", x, y, + rectHeight + 25);
Now is you look at your code you will find that you have 3 ',' in you method call. (I don't think you want the ',' after the y. -
Java Bean Error in JSP: Cannot Resolve Symbol FirstBean
I have created a java bean with following package statement
package mybeans;
and my bean name is
FirstBean
it compile secessfully and now my directory structure is following
WebAppRootDir \ WEB-INF \ classes \ mybeans \ FirstBean.class
I am using Tomcat 4.1 and in JSP i am declaring the bean with following line
<jsp:useBean id="b" class="mybeans.FirstBean" />
and tomcat 4.1 is failed to find this bean and giving me following error
cannot resolve symbol
symbol : class StudentBean
location: package mybeans
mybeans.FirstBean b = null;
all my class and directory structure is ok i am puzzle why this error is coming, plz help me quickly i need solution quickly ...Error is for StudentBean, not for FirstBean. So check for it.
-
Java Bean Error in JSP: Cannot Resolve Symbol Error
I have created a java bean with following package statement
package mybeans;
and my bean name is
FirstBean
it compile secessfully and now my directory structure is following
WebAppRootDir \ WEB-INF \ classes \ mybeans \ FirstBean.class
I am using Tomcat 4.1 and in JSP i am declaring the bean with following line
<jsp:useBean id="b" class="mybeans.FirstBean" />
and tomcat 4.1 is failed to find this bean and giving me following error
cannot resolve symbol
symbol : class FirstBean
location: package mybeans
mybeans.FirstBean b = null;
all my class and directory structure is ok i am puzzle why this error is coming, plz help me quickly i need solution quickly ...It seem to be ok... why dont your try with a newer versi�n of Tomcat?
-
Getting error message Cannot Resolve Symbol when trying to compile a class
Hello All -
I am getting an error message cannot resolve symbol while trying to compile a java class that calls another java class in the same package. The called class compiles fine, but the calling class generates
the following error message:
D:\Apache Tomcat 4.0\webapps\examples\WEB-INF\classes\cal>javac
ConnectionPool.java
ConnectionPool.java:158: cannot resolve symbol
symbol : class PooledConnection
location: class cal.ConnectionPool
private void addConnection(PooledConnection value) {
^
ConnectionPool.java:144: cannot resolve symbol
symbol : class PooledConnection
location: class cal.ConnectionPool
PooledConnection pcon = new PooledConnection(con);
^
ConnectionPool.java:144: cannot resolve symbol
symbol : class PooledConnection
location: class cal.ConnectionPool
PooledConnection pcon = new PooledConnection(con);
The code is listed as follows for PooledConnection.java (it compiles fine)
package cal;
import java.sql.*;
public class PooledConnection {
// Real JDBC Connection
private Connection connection = null;
// boolean flag used to determine if connection is in use
private boolean inuse = false;
// Constructor that takes the passed in JDBC Connection
// and stores it in the connection attribute.
public PooledConnection(Connection value) {
if ( value != null ) {
connection = value;
// Returns a reference to the JDBC Connection
public Connection getConnection() {
// get the JDBC Connection
return connection;
// Set the status of the PooledConnection.
public void setInUse(boolean value) {
inuse = value;
// Returns the current status of the PooledConnection.
public boolean inUse() {
return inuse;
// Close the real JDBC Connection
public void close() {
try {
connection.close();
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
Now the code for ConnectionPool.java class that gives the cannot
resolve symbol error
package cal;
import java.sql.*;
import java.util.*;
public class ConnectionPool {
// JDBC Driver Name
private String driver = null;
// URL of database
private String url = null;
// Initial number of connections.
private int size = 0;
// Username
private String username = new String("");
// Password
private String password = new String("");
// Vector of JDBC Connections
private Vector pool = null;
public ConnectionPool() {
// Set the value of the JDBC Driver
public void setDriver(String value) {
if ( value != null ) {
driver = value;
// Get the value of the JDBC Driver
public String getDriver() {
return driver;
// Set the URL Pointing to the Datasource
public void setURL(String value ) {
if ( value != null ) {
url = value;
// Get the URL Pointing to the Datasource
public String getURL() {
return url;
// Set the initial number of connections
public void setSize(int value) {
if ( value > 1 ) {
size = value;
// Get the initial number of connections
public int getSize() {
return size;
// Set the username
public void setUsername(String value) {
if ( value != null ) {
username = value;
// Get the username
public String getUserName() {
return username;
// Set the password
public void setPassword(String value) {
if ( value != null ) {
password = value;
// Get the password
public String getPassword() {
return password;
// Creates and returns a connection
private Connection createConnection() throws Exception {
Connection con = null;
// Create a Connection
con = DriverManager.getConnection(url,
username, password);
return con;
// Initialize the pool
public synchronized void initializePool() throws Exception {
// Check our initial values
if ( driver == null ) {
throw new Exception("No Driver Name Specified!");
if ( url == null ) {
throw new Exception("No URL Specified!");
if ( size < 1 ) {
throw new Exception("Pool size is less than 1!");
// Create the Connections
try {
// Load the Driver class file
Class.forName(driver);
// Create Connections based on the size member
for ( int x = 0; x < size; x++ ) {
Connection con = createConnection();
if ( con != null ) {
// Create a PooledConnection to encapsulate the
// real JDBC Connection
PooledConnection pcon = new PooledConnection(con);
// Add the Connection to the pool.
addConnection(pcon);
catch (Exception e) {
System.err.println(e.getMessage());
throw new Exception(e.getMessage());
// Adds the PooledConnection to the pool
private void addConnection(PooledConnection value) {
// If the pool is null, create a new vector
// with the initial size of "size"
if ( pool == null ) {
pool = new Vector(size);
// Add the PooledConnection Object to the vector
pool.addElement(value);
public synchronized void releaseConnection(Connection con) {
// find the PooledConnection Object
for ( int x = 0; x < pool.size(); x++ ) {
PooledConnection pcon =
(PooledConnection)pool.elementAt(x);
// Check for correct Connection
if ( pcon.getConnection() == con ) {
System.err.println("Releasing Connection " + x);
// Set its inuse attribute to false, which
// releases it for use
pcon.setInUse(false);
break;
// Find an available connection
public synchronized Connection getConnection()
throws Exception {
PooledConnection pcon = null;
// find a connection not in use
for ( int x = 0; x < pool.size(); x++ ) {
pcon = (PooledConnection)pool.elementAt(x);
// Check to see if the Connection is in use
if ( pcon.inUse() == false ) {
// Mark it as in use
pcon.setInUse(true);
// return the JDBC Connection stored in the
// PooledConnection object
return pcon.getConnection();
// Could not find a free connection,
// create and add a new one
try {
// Create a new JDBC Connection
Connection con = createConnection();
// Create a new PooledConnection, passing it the JDBC
// Connection
pcon = new PooledConnection(con);
// Mark the connection as in use
pcon.setInUse(true);
// Add the new PooledConnection object to the pool
pool.addElement(pcon);
catch (Exception e) {
System.err.println(e.getMessage());
throw new Exception(e.getMessage());
// return the new Connection
return pcon.getConnection();
// When shutting down the pool, you need to first empty it.
public synchronized void emptyPool() {
// Iterate over the entire pool closing the
// JDBC Connections.
for ( int x = 0; x < pool.size(); x++ ) {
System.err.println("Closing JDBC Connection " + x);
PooledConnection pcon =
(PooledConnection)pool.elementAt(x);
// If the PooledConnection is not in use, close it
if ( pcon.inUse() == false ) {
pcon.close();
else {
// If it is still in use, sleep for 30 seconds and
// force close.
try {
java.lang.Thread.sleep(30000);
pcon.close();
catch (InterruptedException ie) {
System.err.println(ie.getMessage());
I am using Sun JDK Version 1.3.0_02" and Apache/Tomcat 4.0. Both the calling and the called class are in the same directory.
Any help would be greatly appreciated.
tnx..
addiIs ConnectionPool in this "cal" package as well as PooledConnection? From the directory you are compiling from it appears that it is. If it is, then you are compiling it incorrectly. To compile ConnectionPool (and PooledConnection similarly), you must change the current directory to the one that contains cal and type
javac cal/ConnectionPool. -
"cannot resolve symbol" in a Timer !!!Please Help!!!
I am doing a program for a class which involves timers. I am using JCreator and when i try to construct a new timer, the compiler points to the "new" in the line:
Timer T1=new Timer(interval, ActionListener);
^
This is what it looks like and the error reads: cannot resolve symbol; constructor Timer.
please tell me if yiou have any information or suggestions as to how this error might be remedied.Sure, here it is:
import java.awt.event.*;
import javax.swing.Timer;
import javax.swing.JOptionPane;
import java.util.*;
interface ActionListener
void actionPerformed(ActionEvent event);
class Ploid
public static void main(String[] args)
class Car implements ActionListener
int mpg=30;
int mph=35;
int gtank=20;
int interval;
int changer;
int totalmiles;
Car(int x)
interval=x;
public void actionPerformed(ActionEvent event)
for(int c=0;c<(interval/1000);c++)
totalmiles=totalmiles+mph;
int hyt=mpg*gtank;
if(totalmiles>hyt)
int y=totalmiles-hyt;
totalmiles=totalmiles-y;
System.out.println(totalmiles);
else
System.out.println(totalmiles);
class SUV implements ActionListener
int mpg=15;
int mph=55;
int gtank=30;
int interval;
int changer;
int totalmiles;
SUV(int x)
interval=x;
public void actionPerformed(ActionEvent event)
for(int c=0;c<(interval/1000);c++)
totalmiles=totalmiles+mph;
int hyt=mpg*gtank;
if(totalmiles>hyt)
int y=totalmiles-hyt;
totalmiles=totalmiles-y;
System.out.println(totalmiles);
else
System.out.println(totalmiles);
class Semi implements ActionListener
int mpg=60;
int mph=80;
int gtank=50;
int interval;
int changer;
int totalmiles;
Semi(int x)
interval=x;
public void actionPerformed(ActionEvent event)
for(int c=0;c<(interval/1000);c++)
totalmiles=totalmiles+mph;
int hyt=mpg*gtank;
if(totalmiles>hyt)
int y=totalmiles-hyt;
totalmiles=totalmiles-y;
System.out.println(totalmiles);
else
System.out.println(totalmiles);
String flag="y";
String trav=JOptionPane.showInputDialog("How long do you want to drive?(1000=1 hour)");
int t1=Integer.parseInt(trav);
Car listen=new Car(t1);
SUV listener2=new SUV(t1);
Semi listener3=new Semi(t1);
final int t2=t1/1000;
final int t3=t1/t2;
ActionListener listener=null;
Timer T1=new Timer(t3, listener);
Timer T2=new Timer(t3, listener);
Timer T3=new Timer(t3, listener);
while(flag.equals("y"))
T1.start();
T2.start();
T3.start();
String g=JOptionPane.showInputDialog("Do you want to drive again?");
if((g.equals("y"))||(g.equals("Y")))
System.out.println("Let's Drive!");
else
flag=g;
System.exit(0);
}Here is the errors:
[errors]
A:\Ploid2.java:116: cannot resolve symbol
symbol : constructor Timer (int,ActionListener)
location: class javax.swing.Timer
Timer T1=new Timer(t3, listener);
^
A:\Ploid2.java:117: cannot resolve symbol
symbol : constructor Timer (int,ActionListener)
location: class javax.swing.Timer
Timer T2=new Timer(t3, listener);
^
A:\Ploid2.java:118: cannot resolve symbol
symbol : constructor Timer (int,ActionListener)
location: class javax.swing.Timer
Timer T3=new Timer(t3, listener);
^
3 errors
Process completed.
[errors]
****There is the source code and the errors the compiler returns. That should be more help.**** -
Class error - cannot resolve symbol "MyDocumentListener"
Hello,
this is a groaner I'm sure, but I don't see the problem.
Newbie-itis probably ...
I'm not concerned with what the class does, but it would be nice for the silly thing to compile!
What the heck am I missing for "MyDocumentListener" ?
C:\divelog>javac -classpath C:\ CenterPanel.java
CenterPanel.java:53: cannot resolve symbol
symbol : class MyDocumentListener
location: class divelog.CenterPanel
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
^
CenterPanel.java:53: cannot resolve symbol
symbol : class MyDocumentListener
location: class divelog.CenterPanel
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
^
2 errors
package divelog;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import javax.swing.text.*;
public class CenterPanel extends JPanel implements ActionListener
{ // Opens class
static private final String newline = "\n";
private JTextArea comments;
private JScrollPane scrollpane;
private JButton saveButton, openButton;
private JLabel whiteshark;
private Box box;
private BufferedReader br ;
private String str;
private JTextArea instruct;
private File defaultDirectory = new File("C://divelog");
private File fileDirectory = null;
private File currentFile= null;
public CenterPanel()
{ // open constructor CenterPanel
setBackground(Color.white);
comments = new JTextArea("Enter comments, such as " +
"location, water conditions, sea life you observed," +
" and problems you may have encountered.", 15, 10);
comments.setLineWrap(true);
comments.setWrapStyleWord(true);
comments.setEditable(true);
comments.setFont(new Font("Times-Roman", Font.PLAIN, 14));
// add a document listener for changes to the text,
// query before opening a new file to decide if we need to save changes.
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
comments.getDocument().addDocumentListener(myDocumentListener); // create the reference for the class
// ------ Document listener class -----------
class MyDocumentListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
Calculate(e);
public void removeUpdate(DocumentEvent e) {
Calculate(e);
public void changedUpdate(DocumentEvent e) {
private void Calculate(DocumentEvent e) {
// do something here
scrollpane = new JScrollPane(comments);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
saveButton = new JButton("Save Comments", new ImageIcon("images/Save16.gif"));
saveButton.addActionListener( this );
saveButton.setToolTipText("Click this button to save the current file.");
openButton = new JButton("Open File...", new ImageIcon("images/Open16.gif"));
openButton.addActionListener( this );
openButton.setToolTipText("Click this button to open a file.");
whiteshark = new JLabel("", new ImageIcon("images/gwhite.gif"), JLabel.CENTER);
Box boxH;
boxH = Box.createHorizontalBox();
boxH.add(openButton);
boxH.add(Box.createHorizontalStrut(15));
boxH.add(saveButton);
box = Box.createVerticalBox();
box.add(scrollpane);
box.add(Box.createVerticalStrut(10));
box.add(boxH);
box.add(Box.createVerticalStrut(15));
box.add(whiteshark);
add(box);
} // closes constructor CenterPanel
public void actionPerformed( ActionEvent evt )
{ // open method actionPerformed
JFileChooser jfc = new JFileChooser();
// these do not work !!
// -- set the file types to view --
// ExtensionFileFilter filter = new ExtensionFileFilter();
// FileFilter filter = new FileFilter();
//filter.addExtension("java");
//filter.addExtension("txt");
//filter.setDescription("Text & Java Files");
//jfc.setFileFilter(filter);
//Add a custom file filter and disable the default "Accept All" file filter.
jfc.addChoosableFileFilter(new JTFilter());
jfc.setAcceptAllFileFilterUsed(false);
// -- open the default directory --
// public void setCurrentDirectory(File dir)
// jfc.setCurrentDirectory(new File("C://divelog"));
jfc.setCurrentDirectory(defaultDirectory);
jfc.setSize(400, 300);
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
Container parent = saveButton.getParent();
//========================= Test Button Actions ================================
//========================= Open Button ================================
if (evt.getSource() == openButton)
int choice = jfc.showOpenDialog(CenterPanel.this);
File file = jfc.getSelectedFile();
/* a: */
if (file != null && choice == JFileChooser.APPROVE_OPTION)
String filename = jfc.getSelectedFile().getAbsolutePath();
// -- compare the currentFile to the file chosen, alert of loosing any changes to currentFile --
// If (currentFile != filename)
// -- get the current directory name -------
// public File getCurrentDirectory( );
File f=new File(System.getProperty("user.dir"));
fileDirectory = jfc.getCurrentDirectory();
// -- remember the last directory used --
if (defaultDirectory != fileDirectory)
{defaultDirectory = fileDirectory;}
try
{ //opens try
comments.getLineCount( );
// -- clear the old data before importing the new file --
comments.selectAll();
comments.replaceSelection("");
// -- get the new data ---
br = new BufferedReader (new FileReader(file));
while ((str = br.readLine()) != null)
{//opens while
comments.append(str);
} //closes while
} // close try
catch (IOException ioe)
{ // open catch
comments.append(newline +"Open command not successful:" + ioe + newline);
} // close catch
// ---- display the values of the directory variables -----------------------
comments.append(
newline + "The f directory variable contains: " + f +
newline + "The fileDirectory variable contains: " + fileDirectory +
newline + "The defaultDirectory variable contains: " + defaultDirectory );
else
comments.append("Open command cancelled by user." + newline);
} //close if statement /* a: */
//========================= Save Button ================================
} else if (evt.getSource() == saveButton)
int choice = jfc.showSaveDialog(CenterPanel.this);
if (choice == JFileChooser.APPROVE_OPTION)
File fileName = jfc.getSelectedFile();
// -- get the current directory name -------
// public File getCurrentDirectory( );
File f=new File(System.getProperty("user.dir"));
fileDirectory = jfc.getCurrentDirectory();
// -- remember the last directory used --
if (defaultDirectory != fileDirectory)
{defaultDirectory = fileDirectory;}
//check for existing files. Warn users & ask if they want to overwrite
for(int i = 0; i < fileName.length(); i ++) {
File tmp = null;
tmp = (fileName);
if (tmp.exists()) // display pop-up alert
//public static int showConfirmDialog( Component parentComponent,
// Object message,
// String title,
// int optionType,
// int messageType,
// Icon icon);
int confirm = JOptionPane.showConfirmDialog(null,
fileName + " already exists on " + fileDirectory
+ "\n \nContinue?", // msg
"Warning! Overwrite File!", // title
JOptionPane.OK_CANCEL_OPTION, // buttons displayed
// JOptionPane.ERROR_MESSAGE
// JOptionPane.INFORMATION_MESSAGE
// JOptionPane.PLAIN_MESSAGE
// JOptionPane.QUESTION_MESSAGE
JOptionPane.WARNING_MESSAGE,
null);
if (confirm != JOptionPane.YES_OPTION)
{ //user cancels the file overwrite.
try {
jfc.cancelSelection();
break;
catch(Exception e) {}
// ----- Save the file if everything is OK ----------------------------
try
{ // opens try
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
bw.write(comments.getText());
bw.flush();
bw.close();
comments.append( newline + newline + "Saving: " + fileName.getName() + "." + newline);
break;
} // closes try
catch (IOException ioe)
{ // open catch
comments.append(newline +"Save command unsuccessful:" + ioe + newline);
} // close catch
} // if exists
} //close for loop
else
comments.append("Save command cancelled by user." + newline);
} // end-if save button
} // close method actionPerformed
} //close constructor CenterPanel
} // Closes class CenterPanelThere is no way to be able to see MyDocumentListener class in the way you wrote. The reason is because MyDocumentListener class inside the constructor itself. MyDocumentListener class is an inner class, not suppose to be inside a constructor or a method. What you need to do is simple thing, just move it from inside the constructor and place it between two methods.
that's all folks
Qusay -
PLEASE HELP: cannot resolve symbol class
it's showing me the error on the following lines 7 and 9
it says cannot resolve symbol class Name and cannot resolve symbol class Phone
I also have a package name addressBook and it contains two files Entry.java and Address.java
Here is the code:
import java.io.*;
import addressBook.*;
public class AddressDr
public static void main(String[] args)throws IOException
Name name;
Address address;
Phone phone;
Entry entry;
String first, last, middle, street, city, state, zip;
int areaCode, number;
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter outFile;
outFile=new PrintWriter(new FileWriter("Entries"));
System.out.println("Quit entered fot the first name ends the " + "application.");
System.out.print("Enter first name: ");
first=in.readLine();
while (first.compareTo("Quit") !=0)
System.out.print("Enter last name: ");
last=in.readLine();
System.out.print("Enter middle name: ");
middle=in.readLine();
name=new Name(first, last, middle);
System.out.print("Enter street address: ");
street=in.readLine();
System.out.print("Enter city: ");
city=in.readLine();
System.out.print("Enter state: ");
state=in.readLine();
System.out.print("Enter ZIP code: ");
zip=in.readLine();
address=new Address(street, city, state, zip);
System.out.print("Enter areaCode: ");
areaCode = Integer.parseInt(in.readLine());
System.out.print("Enter number: ");
number=Integer.parseInt(in.readLine());
phone=new Phone(areaCode, number);
entry= new Entry(name, address, phone);
entry.writeToFile(outFile);
System.out.print("Enter first name: ");
first=in.readLine();
outFile.close();
}OK. Here is how I did it.
I have AddressDr which is Address driver.
I have two files Address and Entry which in package addressBook.
AddressDr:
import java.io.*;
import addressBook.*;
public class AddressDr
public static void main(String[] args)throws IOException
Name name;
Address address;
Phone phone;
Entry entry;
String first, last, middle, street, city, state, zip;
int areaCode, number;
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter outFile;
outFile=new PrintWriter(new FileWriter("Entries"));
System.out.println("Quit entered fot the first name ends the " + "application.");
System.out.print("Enter first name: ");
first=in.readLine();
while (first.compareTo("Quit") !=0)
System.out.print("Enter last name: ");
last=in.readLine();
System.out.print("Enter middle name: ");
middle=in.readLine();
name=new Name(first, last, middle);
System.out.print("Enter street address: ");
street=in.readLine();
System.out.print("Enter city: ");
city=in.readLine();
System.out.print("Enter state: ");
state=in.readLine();
System.out.print("Enter ZIP code: ");
zip=in.readLine();
address=new Address(street, city, state, zip);
System.out.print("Enter areaCode: ");
areaCode = Integer.parseInt(in.readLine());
System.out.print("Enter number: ");
number=Integer.parseInt(in.readLine());
phone=new Phone(areaCode, number);
entry= new Entry(name, address, phone);
entry.writeToFile(outFile);
System.out.print("Enter first name: ");
first=in.readLine();
outFile.close();
Entry:
package addressBook;
import java.io.*;
public class Entry
Name name;
Address address;
Phone phone;
public Entry(Name newName, Address newAddress, Phone phoneNumber)
name = newName;
address = newAddress;
phone = phoneNumber;
public Name knowName()
return name;
public Address knowAddress()
return address;
public Phone knowPhone()
return phone;
public void writeToFile(PrintWriter outFile)
outFile.println(name.knowFirstName());
outFile.println(name.knowLastName());
outFile.println(name.knowMiddleName());
oufFile.println(address.knowStreet());
outFile.println(address.knowState());
outFile.println(address.knowCity());
outFile.println(address.knowZip());
outFile.println(phone.knowAreaCode());
outFile.println(phone.knowDigits());
Address:
package addressBook;
public class Address
String street;
String city;
String state;
String zipCode;
public Address(String newStreet, String newCity, String newState, String zip)
street=newStreet;
city=newCity;
state=newState;
zipCode=zip;
public String knowStreet()
return street;
public String knowCity()
return city;
public String knowState()
return state;
public String knowZip()
return zipCode;
} -
Recieving cannot resolve symbol symbol : class Serializable
I'm receiving the error:
cannot resolve symbol symbol : class Serializable
The class is as follows:
//package cscie160.hw5;
import java.io.Serializable
* @author Eddie Brodie
* @version %I%, %G%
public class AccountInfo implements Serializable
public int _accountNumber;
public int _pin;
public AccountInfo(int accountNumber, int pin)
_accountNumber = accountNumber;
_pin = pin;
I've tried importing java.*
I've also checked my classpath.
Any ideas?Try taking the import statement out of the comment block; that might help
-
Cannot resolve symbol: class OracleDriver
Attempting to compile a servlet on Apache Server using same jdeveloper jdbc libraries:
classes12.jar & nls_charset12.jar
Error message:
$compilejava2.sh ProdJobs
ProdJobs.java:361: cannot resolve symbol
symbol : class OracleDriver
location: package driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Am I missing something else?
JeffreyEnter this code into your program and then put the Oracle jar file that contains the driver in your run-time classpath.
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
catch(ClassNotFoundException cnfe) {
// driver not found
}The effect of this is that the classloader will load the Oracle driver for you then call it's static initiailizer that does a bunch of magic that results in the Java runtime knowing that there's a JDBC driver out there.
It is a little weird - but that's the way it works.
Maybe you are looking for
-
Insert french characters into the database
Hi, My user requirement is to insert french characters into the db. However he has set as per my suggestion of altering session alter session set nls_language='french' he can't insert french characters. Is this using alter session helps to retrieve o
-
Hello ! I have very often the following error message in the log file: ORA-00604: error occurred at recursive SQL level 1 ORA-01578: ORACLE data block corrupted (file # 2, block # 416) ORA-01110: data file 2: '/opt/oracle/oradata/wsdb/undotbs01.dbf'
-
Extract of entities in Hyperion Enterprise
We are running on Hyperion Enterprise 5.5.4. Please advice me how to take the dump of all the tntities and its properties to MS Excel.<BR><BR>Thanks<BR>Ravi
-
ORA-03001 "unimplemented feature" error for SQL when using view
Our ERP allows us (IT staff) to create Information Access Layers which are basically views. These can be "live" where the view is like your tradiitonal one or non-live, where a table of data is replicated on a schedule and a view is available over th
-
Sounds Wont Work (HELP PLZ)
I have 3 diff headsets and they dont work The PC (and pc only) One im using wont work It can hear Videogames Youtube Etc. But not Skype. I think the mic doesent work eather PLEASE HELP ME I NEED THIS FIXED ASAP!