Cannot resolve symbol..Swing / MDI
I'm somewhat new to Java.
I have an MDI app that I am creating. The main routine is in DeskTop.java.
When DeskTop.class is run:
1)Main creates a generic UserID class from userID.java( has two private strings and 4 methods to get userid, passwd, and set userid, passwd).
This info will be used throughout the app to connect to various MySQL Dbs.
2)Main creates the main application JFrame and a JMenu.
One of the JMenuItems, named Logon creates a JInternalFrame (basically a login box with userid and password field and JButton called continue. An ActionPerformed is added to a continue JButton.
There are many other JInternalFrames on the menu that have various DB functions.
I need to have the action performed on the ActionEvent of the continue button access the UserID class and it's setUserID() and setPasswd() methods and set the (uid, pw) fields in the object. Yet anytime I try to access this object from the Logon object, I get a Cannot resolve symbol:
This is a summary of the action performed on the continue button:
uid = txt_userID.getText();
userid = new String(uid).trim();
pw = pw_password.getPassword();
password = new String(pw).trim();
UserID.setUserID(userid); /*UserID is the other object.Error is on*/
UserID.setPasswd(password); /*the decimal point.*/
All objects have a public constructor and the methods I am trying access are declared public.
Files consist of (all in same directory):
DeskTop.java (main JFRAME)
PasswordBox.java ( JInternalFrame)
UserIDPW.java (JInternalFrame)
AddCompany.java (JInternalFrame)
etc. ( other JInternalFrames)
etc. ( other classes)
Thanks for any input. If someone has a better method of making a MDI database app in Java, some info would be great.
There will be other classes outside the gui. I am trying to build the business logic and the gui as seperate as I can.
This may sound silly to ask, but without seeing all
the code in this case you can imagine it's difficult
to say - I presume that UserID is a class (ie a
template for an object) rather than an object itself
and that setUserID, setPasswd are static functions.
The files you list dont include a UserID.java, so this
means you haven't got a PUBLIC class called UserID
(you may have one with private or package / friendly
access) - hence you can't access it from outside. I am
new myself - but this looks a likely candidate. [ I
try to answer questions so that I can learn myself,
but now I am off to bed!]Thank for the reply.
The main function creates a public UserID object and it created the main gui JFrame DeskTop object. UserID has a public constructor and public methods.
main function:
public static void main(String args[]) {
userIDPW userID = new userIDPassword();
JFrame f = new DeskTop();
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
f.setSize(screensize);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
The DeskTop object has a JMenuitem in it called Login, it opens an InternalJFrame called PasswordBox.
PasswordBox takes a userid and pw and then it needs to send the userid and pw to the userID object with two of its methods:
Methods in userID object:
public void setUserID(String userid)
{ this.userid = userid; }
public void setPasswd(String passwd)
( this.passwd = passwd; }
How doed one access this object (userID)? I have tried (from the PasswordBox) with no success:
uid = txt_userID.getText();
userid = new String(uid).trim();
pw = pw_password.getPassword();
password = new String(pw).trim();
userID.setUserID(userid); --this fails, with Cannot resolve symbol
userID.setPasswd(password); --this fails, with Cannot resolve symbol
Similar Messages
-
"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 -
Cannot resolve symbol class graphics
does anyone know what the error
cannot resolve symbol class graphics means?
with this code i can't seem to call the graphics method to draw the line....any reason why?
import javax.swing.*;
import java.*;
public class LineDraw extends JFrame {
public static void main(String[] args) {
LineDraw ld = new LineDraw();
ld.setSize(500,500);
ld.setVisible(true);
ld.enterVariables();
public void init(){
private int x1;
private int x2;
private int y1;
private int y2;
public void paint(Graphics g) {
g.GetGraphics(g);
super.paintComponent(g);
g.drawLine(x1, y1, x2, y2);
public void enterVariables() {
x1 = Integer.parseInt(JOptionPane.showInputDialog("Enter x1:"));
y1 = Integer.parseInt(JOptionPane.showInputDialog("Enter y1:"));
x2 = Integer.parseInt(JOptionPane.showInputDialog("Enter x2:"));
y2 = Integer.parseInt(JOptionPane.showInputDialog("Enter y2:"));
repaint();
}well the exact error message is ...by the way now that i think about it
if the graphics method shoudl not be part of the JFrame class then what method would i use to draw 2D Graphics?
--------------------Configuration: <Default>--------------------
C:\Documents and Settings\c1s5\My Documents\LineDraw.java:21: cannot resolve symbol
symbol : class Graphics
location: class LineDraw
public void paint(Graphics g)
^
1 error
Process completed.
and the exact code is
import javax.swing.*;
import java.*;
public class LineDraw extends JFrame {
public static void main(String[] args) {
LineDraw ld = new LineDraw();
ld.setSize(1024,500);
ld.setVisible(true);
ld.enterVariables();
private int x1;
private int x2;
private int y1;
private int y2;
public void paint(Graphics g)
super.paintComponent(g);
g.drawLine(x1, y1, x2, y2);
public void enterVariables() {
x1 = Integer.parseInt(JOptionPane.showInputDialog("Enter x1:"));
y1 = Integer.parseInt(JOptionPane.showInputDialog("Enter y1:"));
x2 = Integer.parseInt(JOptionPane.showInputDialog("Enter x2:"));
y2 = Integer.parseInt(JOptionPane.showInputDialog("Enter y2:"));
repaint();
} -
Hello,
I'm brand new to Java. Why is it that the compiler will not recognize my return variable??
Thanks
import javax.swing.*;
import java.text.*;
class BookOrder
public static void main(String[] values)
String bookCode = JOptionPane.showInputDialog("Enter your book code");
String getResults = getResults(bookCode);
System.exit(0);
//End of main
private static String getResults(String bookCode)
if(bookCode.equals("wp"))
{String codeLabel = "War and Peace";}
else if(bookCode.equals("pr"))
{String codeLabel = "Politics and Religion";}
return codeLabel;
C:\jdk1.3.1\myClasses\BookOrder.java:21: cannot resolve symbol
symbol : variable returnCode
location: class BookOrder
return returnCode;
^You are out of scope. If that does not make sense, then please pick up a book on basic programming skills and start reading in chapter one. But, here is how I would fix:
import javax.swing.*;
import java.text.*;
class BookOrder
public static void main(String[] values)
String bookCode = JOptionPane.showInputDialog("Enter your book code");
String getResults = getResults(bookCode);
System.exit(0);
//End of main
private static String getResults(String bookCode)
String codeLabel = "";
if(bookCode.equals("wp"))
{codeLabel = "War and Peace";}
else if(bookCode.equals("pr"))
{codeLabel = "Politics and Religion";}
return codeLabel;
}regards,
jarshe -
Error: Cannot Resolve symbol
Hi i have written this program but it is not compling properly. i do not know what to do to sort it. here is the code:
import java.sql.*;
import java.io.DataInputStream;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Phase1 extends JFrame implements ActionListener, MouseListener
//Create Buttons and Text areas etc for the GUI itself
JButton add, current, delete, order, all, exit;
JTextField textStockCode, textStockDesc, textCurrentLevel, textReorderLevel, textPrice;
JTextArea textarea;
JScrollPane pane1;
JLabel labelStockCode, labelStockDesc, labelCurrentLevel, labelReorderLevel, labelPrice, labelTextArea;
String stockCode, stockDesc, currentLevel, reorderLevel, price;
JLabel welcome;
//Setup database connections and statements for later use
Connection db_connection;
Statement db_statement;
public Phase1()
//Display a welcome message before loading system onto the screen
JOptionPane.showMessageDialog(null, "Welcome to the Stock Control System");
//set up the GUI environment to use a grid layout
Container content=this.getContentPane();
content.setLayout(new GridLayout(3,6));
//Inititlise buttons
add=new JButton("Add");
add.addActionListener(this);
current=new JButton("Show Current Level");
current.addActionListener(this);
delete=new JButton("Delete");
delete.addActionListener(this);
order=new JButton("Place Order");
order.addActionListener(this);
all = new JButton("Show All Entries");
all.addActionListener(this);
exit = new JButton("Exit");
exit.addActionListener(this);
//Add Buttons to the layout
content.add(add);
content.add(current);
content.add(delete);
content.add(order);
content.add(all);
content.add(exit);
//Initialise text fields for inputting data to the database and
//Add mouse listeners to clear the boxs on a click event
textStockCode = new JTextField("");
textStockCode.addMouseListener(this);
textStockDesc = new JTextField("");
textStockDesc.addMouseListener(this);
textCurrentLevel = new JTextField("");
textCurrentLevel.addMouseListener(this);
textReorderLevel = new JTextField("");
textReorderLevel.addMouseListener(this);
textPrice = new JTextField("");
textPrice.addMouseListener(this);
//Initialise the labels to label the Text Fields
labelStockCode = new JLabel("Stock Code");
labelStockDesc = new JLabel("Stock Description");
labelCurrentLevel = new JLabel("Current Level");
labelReorderLevel = new JLabel("Re-Order Level");
labelPrice = new JLabel("Price");
labelTextArea = new JLabel("All Objects");
//Add Text fields and labels to the GUI
content.add(labelStockCode);
content.add(textStockCode);
content.add(labelStockDesc);
content.add(textStockDesc);
content.add(labelCurrentLevel);
content.add(textCurrentLevel);
content.add(labelReorderLevel);
content.add(textReorderLevel);
content.add(labelPrice);
content.add(textPrice);
content.add(labelTextArea);
//Create a text area with scroll bar for showing Entries in the text area
textarea=new JTextArea();
textarea.setRows(6);
pane1=new JScrollPane(textarea);
content.add(pane1);
//Try to connect to the database through ODBC
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
//Create a URL that identifies database
String url = "jdbc:odbc:" + "stock";
//Now attempt to create a database connection
//First parameter data source, second parameter user name, third paramater
//password, the last two paramaters may be entered as "" if no username or
//pasword is used
db_connection = DriverManager.getConnection(url, "demo","");
//Create a statement to send SQL
db_statement = db_connection.createStatement();
catch (Exception ce){} //driver not found
//action performed method for button click events
public void actionPerformed(ActionEvent ev)
if(ev.getSource()==add) //If add button clicked
try
add(); //Run add() method
catch(Exception e){}
if(ev.getSource()==current)
{ //If Show Current Level Button Clicked
try
current(); //Run current() method
catch(Exception e){}
if(ev.getSource()==delete)
{ //If Show Delete Button Clicked
try
delete(); //Run delete() method
catch(Exception e){}
if(ev.getSource()==order) //If Show Order Button Clicked
try
order(); //Run order() method
catch(Exception e){}
if(ev.getSource()==all) //If Show Show All Button Clicked
try
all(); //Run all() method
catch(Exception e){}
if(ev.getSource()==exit) //If Show Exit Button Clicked
try{
exit(); //Run exit() method
catch(Exception e){}
public void add() throws Exception //add a new stock item
stockCode = textStockCode.getText();
stockDesc = textStockDesc.getText();
currentLevel = textCurrentLevel.getText();
reorderLevel = textReorderLevel.getText();
price = textPrice.getText();
if(stockCode.equals(""))
JOptionPane.showMessageDialog(null,"Ensure Stock Code is filled out");
if(stockDesc.equals(""))
JOptionPane.showMessageDialog(null,"Ensure Description is filled out");
if(price.equals(""))
JOptionPane.showMessageDialog(null,"Ensure price is filled out");
if(currentLevel.equals(""))
JOptionPane.showMessageDialog(null,"Ensure Current Level is filled out");
if(reorderLevel.equals(""))
JOptionPane.showMessageDialog(null,"Ensure Re-Order Level is filled out");
else
//Add item to database with variables set from text fields
db_statement.executeUpdate("INSERT INTO stock VALUES
('"+stockCode+"','"+stockDesc+"','"+currentLevel+"','"+reorderLevel+"','"+price+"')");
public void current() throws Exception //check a current stock level
if(textStockCode.getText().equals(""))//if no stockcode has been entered
JOptionPane.showMessageDialog(null,"Enter a Stock Code.");
else
ResultSet resultcurrent = db_statement.executeQuery("SELECT * FROM stock WHERE StockCode = '"+textStockCode.getText()+"'");
textarea.setText("");
if(resultcurrent.next())
do
textarea.setText("Stock Code: "+resultcurrent.getString("StockCode")+"\nDescription:
"+resultcurrent.getString("StockDescription")+"\nCurrent Level: "+resultcurrent.getInt("CurrentLevel")+"\nRe-Order Level:
"+resultcurrent.getInt("ReorderLevel")+"\nPrice: "+resultcurrent.getFloat("Price"));
while(resultcurrent.next());
else
//Display Current Stock Item (selected from StockCode Text field in the scrollable text area
JOptionPane.showMessageDialog(null,"Not a valid Stock Code");
public void delete() throws Exception //delete a current stock item
if(textStockCode.getText().equals("")) //Check there is a stock code entered
JOptionPane.showMessageDialog(null,"Enter a Stock Code.");
else
//Delete Item from database where Stock Code is what is in Stock Code Text Field
db_statement.executeUpdate("DELETE * FROM stock WHERE StockCode='"+textStockCode.getText()+"'");
public void order() throws Exception //check price for an order
if(textStockCode.getText().equals("")) //Check there is a stock code entered
JOptionPane.showMessageDialog(null,"Enter a Stock Code.");
else
//Set some variables to aid ordering
float price = 0;
int currentlevel = 0;
int newlevel = 0;
int reorder = 0;
String StockCode = textStockCode.getText();
//Post a message asking how many to order
String str_quantity = JOptionPane.showInputDialog(null,"Enter Quantity: ","Adder",JOptionPane.PLAIN_MESSAGE);
int quantity = Integer.parseInt(str_quantity);
//Get details from database for current item
ResultSet resultorder = db_statement.executeQuery("SELECT * FROM stock WHERE StockCode='"+StockCode+"'");
//Set variables from database to aid ordering
while (resultorder.next())
price = resultorder.getFloat("Price");
currentlevel = (resultorder.getInt("CurrentLevel"));
reorder = (resultorder.getInt("ReorderLevel"));
//Set the new level to update the database
newlevel = currentlevel - quantity;
//calculate the total price of the order
float total = price * quantity;
//If the stock quantity is 0
if(quantity == 0)
//Display a message saying there are none left in stock
JOptionPane.showMessageDialog(null,"No Stock left for this item");
//Otherwise check that the quantity ordered is more than what is lewft in stock
else if(quantity > currentlevel)
//If ordered too many display a message saying so
JOptionPane.showMessageDialog(null,"Not enough in stock, order less");
else
//Otherwise Display the total in a message box
JOptionPane.showMessageDialog(null,"Total is: "+total);
//then update the database with new values
db_statement.executeUpdate("UPDATE Stock SET CurrentLevel="+newlevel+" WHERE StockCode='"+StockCode+"'");
//Check if the new level is 0
if(newlevel == 0)
//If new level IS 0, send a message to screen saying so
JOptionPane.showMessageDialog(null,"There is now no Stock left.");
else
//otherwise if the newlevel of stock is the same as the reorder level
if(newlevel == reorder)
// display a message to say so
JOptionPane.showMessageDialog(null,"You are now at the re-order level, Get some more of this item in
stock.");
//Otherwise if the new level is lower than the reorder level,
if(newlevel < reorder)
//Display a message saying new level is below reorder level so get some more stock
JOptionPane.showMessageDialog(null,"You are now below the reorder level. Get some more of this item in
stock.");
public void all() throws Exception //show all stock items and details
//Get everthing from the database
ResultSet resultall = db_statement.executeQuery("SELECT * FROM Stock");
textarea.setText("");
while (resultall.next())
//Display all items of stock in the Text Area one after the other
textarea.setText(textarea.getText()+"Stock Code: "+resultall.getString("StockCode")+"\nDescription:
"+resultall.getString("StockDescription")+"\nCurrent Level: "+resultall.getInt("CurrentLevel")+"\nRe-Order Level:
"+resultall.getInt("ReorderLevel")+"\nPrice: "+resultall.getFloat("Price")+"\n\n");
public void exit() throws Exception //exit
//Cause the system to close the window, exiting.
db_connection.commit();
db_connection.close();
System.exit(0);
public static void main(String args[])
//Initialise a frame
JDBCFrame win=new JDBCFrame();
//Set the size to 800 pixels wide and 350 pixels high
win.setSize(900,350);
//Set the window as visible
win.setVisible(true);
win.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
//Mouse Listener Commands
public void mousePressed(MouseEvent evt)
if (evt.getSource()==textStockCode)
//Clear the Stock Code text field on clickin on it
textStockCode.setText("");
else if (evt.getSource()==textStockDesc)
//Clear the Stock Description text field on clickin on it
textStockDesc.setText("");
else if (evt.getSource()==textCurrentLevel)
textCurrentLevel.setText("");
//Clear the Current Level text field on clickin on it
else if (evt.getSource()==textReorderLevel)
textReorderLevel.setText("");
//Clear the Re-Order Level text field on clickin on it
else if (evt.getSource()==textPrice)
textPrice.setText("");
//Clear the Price text field on clickin on it
public void mouseReleased(MouseEvent evt){}
public void mouseClicked(MouseEvent evt){}
public void mouseEntered(MouseEvent evt){}
public void mouseExited(MouseEvent evt){}
}And this is the error that i get when compiling:
Phase1.java:355: cannot resolve symbol
symbol : class JDBCFrame
location: class Phase1
JDBCFrame win=new JDBCFrame();
^
Phase1.java:355: cannot resolve symbol
symbol : class JDBCFrame
location: class Phase1
JDBCFrame win=new JDBCFrame();Thanks for any help you can give meThe error is very clear here
Phase1.java:355: cannot resolve symbolsymbol : class JDBCFramelocation: class Phase1 JDBCFrame win=new JDBCFrame();
Where is this class JDBCFrame()?
Import that package or class -
Cannot resolve symbol-- data access problem
hi, everyone, i am new to java... thx for helping me.
i have two files
1) dls.java
2) SliderDemo.java
in the dls.java i have the following coding:
JPanel slider = new SliderDemo(this);
slider.framesPerSecond(0);
and in the SliderDemo.java i have following coding:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SliderDemo extends JPanel implements ActionListener {
//This label uses ImageIcon to show the doggy pictures.
JLabel picture;
dls mydls;
JSlider framesPerSecond;
int i;
public SliderDemo(dls mydls) {
this.mydls = mydls;
framesPerSecond = new JSlider(JSlider.HORIZONTAL, -10, 10, 0);
framesPerSecond.addChangeListener(new SliderListener());
//Turn on labels at major tick marks.
framesPerSecond.setMajorTickSpacing(10);
framesPerSecond.setMinorTickSpacing(1);
framesPerSecond.setPaintTicks(true);
framesPerSecond.setPaintLabels(true);
framesPerSecond.setBorder( BorderFactory.createEmptyBorder(0,0,10,0));
.....etc
when i compile the dls.java
it told me cannot resolve symbol , framePerSecond...
help!!!why i can't resolve the symbol?
thx all experts.
yours,
Terrycannot resolve symbol , framePerSecondPerhaps because you declared a variable whose name is "framesPerSecond" and then you tried to use "framePerSecond" instead of that?
-
Newbie problem: "cannot resolve symbol"
I'm working through some tutorials but I get errors even if i get the code CORRECT or I should say identical to the source code displayed on the web. For instance i get this:
E:\Java\New>javac SwingUI.java
SwingUI.java:41: not a statement
WindowListener 1 = new WindowAdapter() {
^
SwingUI.java:41: ';' expected
WindowListener 1 = new WindowAdapter() {
^
SwingUI.java:4: cannot resolve symbol
symbol : class ActionListener
location: class SwingUI
class SwingUI extends JFrame implements ActionListener {
^
SwingUI.java:25: cannot resolve symbol
symbol : class ActionEvent
location: class SwingUI
public void actionPerformed(ActionEvent event){
^
SwingUI.java:15: addActionListener(java.awt.event.ActionListener) in javax.swing.AbstractButton cannot be applied to (SwingUI)
button.addActionListener(this);
^
SwingUI.java:18: cannot resolve symbol
symbol : class Borderlayout
location: class SwingUI
panel.setLayout(new Borderlayout());
^
SwingUI.java:46: addWindowListener(java.awt.event.WindowListener) in java.awt.Window cannot be applied to (int)
frame.addWindowListener(1);
^
SwingUI.java:48: cannot resolve symbol
symbol : variable set
location: class SwingUI
frame.set.Visible(true);
^
8 errors
The beginning of the code is:
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
class SwingUI extends JFrame implements ActionListener {
JLabel text, clicked;
JButton button, clickButton;
JPanel panel;
private boolean _clickMeMode = true;
SwingUI(){
text=new JLabel("I'm a simple program");
button= new JButton("Click here!");
button.addActionListener(this);
panel =new JPanel();
panel.setLayout(new Borderlayout());
panel.setBackground(Color.white);
getContentPane().add(panel);
panel.add(BorderLayout.CENTER, text);
panel.add(BorderLayout.SOUTH, button);
To me it seems as if there is a problem with my environmental settings and/or with the "import" files, but wouldn't that yield different error messages?
I'm running j2sdk1.4.0_01 on windows2000 professional
I should say that simple programs compile without errors.
thx
/HansThe letter 'l' is very similar to the number 1 in certain fonts unfortunately.
/Hans -
Cannot Resolve Symbol Frustrations
Here is the code:
private void populateTabbedPane()
tabbedPane.addTab("Welcome", null, new HTBegin(),
"Welcome to Hot Tub");
tabbedPane.addTab("Start", null, new HTStartup(),
"Start up Tub");
Here is the error:
C:\Java\Steve>javac -d . Hottub.java
Hottub.java:44: cannot resolve symbol
symbol : method addTab (java.lang.String,<null>,hottub.HTStartup,java.lang.String)
location: class javax.swing.JTabbedPane
tabbedPane.addTab("Start", null, new HTStartup(),
...............^
1 error
Notice it is on the second addTab and NOT the first. HTBegin and HTStartup classes exist and are found when the -verbose is added to the compile. Yet this error occurs on all of the addTab functions below the first.
As an addition, If I comment out the first addTab line and just run with the second line, the same error occurs. I have deleted and re-typed the line many times.
I'm just learning this language but this seems nuts!
My path is PATH=C:\BITWARE\;C:\WINDOWS;C:\WINDOWS\COMMAND;C:\READIBMW;C:\JAVA\STEVE;C:\JAVA\BIN
Any suggestions?I think I have solved the issue with the following. As requested, HTStartup is displayed as it was when I originally posted the question. There is not much to it so I figured that wasn't the issue. Especially when the error appears to be the addTab statement from the main line class.
package hottub;
import javax.swing.*;
import java.awt.*;
public class HTStartup
{ // Open Class
} // Close Class
This is what I changed it to:
package hottub;
import javax.swing.*;
import java.awt.*;
public class HTStartup extends JPanel
{ // Open Class
} // Close Class
The compile is clean with the addition of extends JPanel. The mainline class compiles.
Thanks for the help! -
Cannot resolve symbol: method getCodeBase ()
I`m creating a dice game that makes a sound when player wins or looses. Instaed I`m getting the following error message: Cannot resolve symbol: method getCodeBase (). I think this depends on the fact that I have a separate applet launcher but cannot figure out how to solve this, please help!!
This is the applet launcher
import javax.swing.*;
import java.awt.*;
// [MC] Public class DiceApplet
public class DiceApplet extends JApplet
// [MC] Constructor.
public DiceApplet()
// [MC] Sets the contentPane property. This method is called by the constructor.
this.setContentPane(new DicePanel());
This is the die class
import java.awt.*;
import javax.swing.*;
// [MC] Public class Die
public class Die extends JPanel
// ======================================================================
// [MC] Instance variable.
private int myFaceValue; // [MC] Value that shows on face of die.
// [MC] End instance variable.
// ======================================================================
// [MC] Constructor.
// [MC] Initialises die to blue background and initial roll.
public Die()
// [MC] Sets the background colour of the die to blue.
setBackground(Color.blue);
// [MC] Sets the foreground colour of the die to gray.
setForeground(Color.gray);
// [MC] Sets the border colour of the die to white.
setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.white));
// [MC] Sets to random initial value.
roll();
} // [MC] End constructor.
// ======================================================================
// [MC] Method roll.
// [MC] Produces random roll in the range of 1 to 6.
public int roll()
int val = (int)(6*Math.random() + 1); // [MC] Range from 1 to 6.
setValue(val);
return val; // [MC] Returns a value from 1 to 6.
} // [MC] End method roll.
// [MC] Method setValue
// [MC] Sets the value of the die. Causes repaint.
public void setValue(int dots)
myFaceValue = dots;
repaint(); // [MC] Value has changed, must repaint.
} // [MC] End method setValue.
// ======================================================================
// [MC] Method getValue.
// [MC] Returns result of last roll.
public int getValue()
return myFaceValue;
} // [MC] End method getValue.
// ======================================================================
// [MC] Method paintComponent.
// [MC] Draws dots of die face.
public void paintComponent(Graphics g)
// [MC] Call superclass's paint method.
super.paintComponent(g);
// [MC] Sets panel width.
int w = getWidth();
// [MC] Sets panel height.
int h = getHeight();
// [MC] Draws border.
g.drawRect(0, 0, w-1, h-1);
// Switch
switch (myFaceValue)
case 1: drawDot(g, w/2, h/2);
break;
case 3: drawDot(g, w/2, h/2);
case 2: drawDot(g, w/4, h/4);
drawDot(g, 3*w/4, 3*h/4);
break;
case 5: drawDot(g, w/2, h/2);
case 4: drawDot(g, w/4, h/4);
drawDot(g, 3*w/4, 3*h/4);
drawDot(g, 3*w/4, h/4);
drawDot(g, w/4, 3*h/4);
break;
case 6: drawDot(g, w/4, h/4);
drawDot(g, 3*w/4, 3*h/4);
drawDot(g, 3*w/4, h/4);
drawDot(g, w/4, 3*h/4);
drawDot(g, w/4, h/2);
drawDot(g, 3*w/4, h/2);
break;
} // [MC] End switch.
} // [MC] End method paintComponent.
// [MC] Method drawDot.
/** Utility method used by paintComponent(). */
private void drawDot(Graphics g, int x, int y)
// [MC] Gets panel width.
int w = getWidth();
// [MC] Gets panel height.
int h = getHeight();
// [MC] Local variable.
int d;
// [MC] Sets diameter of dot proportional to panel size.
d = (w + h)/10;
// [MC] Sets colour for dot to white.
Color myDotColor = new Color(255, 255, 255);
g.setColor(myDotColor);
// [MC] Draws dot.
g.fillOval(x-d/2, y-d/2, d, d);
} // [MC] End method drawDot.
This is the class giving the error message
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.applet.AudioClip;
import java.applet.Applet;
import java.net.*;
// [MC] Public class DicePanel
public class DicePanel extends JPanel
// ======================================================================
// [MC] Instance variables.
// [MC] Creates new instances of the component for the die.
private Die myLeftDie; // [MC] Component for left die.
private Die myRightDie; // [MC] Component for right die.
// [MC] Creates the button (rollButton) to roll the dice.
private JButton rollButton = new JButton("Roll Dice");
// [MC] Creates the text fields. Creates new instance of JTextField.
// [MC] Creates the text field (rollNumberTextField) to display number of rolls.
private JTextField rollNumberTextField = new JTextField(20);
// [MC] Creates the text field (rollResultTextField) to display result of roll.
private JTextField rollResultTextField = new JTextField(20);
// [MC] Creates the text field (rollPointsTextField) to display the player`s points.
private JTextField rollPointsTextField = new JTextField(20);
// [MC] Creates the text field (gameFinalResultTextField) to display the final game result.
private JTextField gameFinalResultTextField = new JTextField(20);
// [MC] Initialises instance variables declared in the inner listeners.
private int result = 0, resultLeft = 0, resultRight = 0;
private int rolls = 0;
private int finalResult = 0;
private int points = 0;
private boolean first = true;
private AudioClip winClip = null;
private AudioClip looseClip = null;
// ======================================================================
// [MC] Constructor. Creates border layout panel.
DicePanel()
// [MC] Creates the dice
myLeftDie = new Die();
myRightDie = new Die();
// ======================================================================
// [MC] Creates the buttons.
// [MC] Creates the button (newGameButton) to start new game.
JButton newGameButton = new JButton("New Game");
// *[MC] Creates the button (rollButton) to roll the dice.
// *JButton rollButton = new JButton("Roll Dice");
// [MC] Sets the font of the buttons.
// [MC[ Sets the font of the button newGameButton.
newGameButton.setFont(new Font("Batang", Font.BOLD, 20));
// [MC[ Sets the font of the button rollButton.
rollButton.setFont(new Font("Batang", Font.BOLD, 20));
// [MC] Sets the button border format.
// [MC] Sets the button with compound borders.
Border compound;
// [MC] Border format local variables.
Border blackline, raisedetched, loweredetched, raisedbevel, loweredbevel, empty;
// [MC] Initialises border formats.
//blackline = BorderFactory.createLineBorder(Color.gray);
raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
raisedbevel = BorderFactory.createRaisedBevelBorder();
//loweredbevel = BorderFactory.createLoweredBevelBorder();
// [MC] Sets compound border format.
compound = BorderFactory.createCompoundBorder(raisedetched, raisedbevel);
// [MC] Sets the button (newGameButton) with compound border format.
newGameButton.setBorder(compound);
// [MC] Sets the button (rollButton) with compound border format.
rollButton.setBorder(compound);
// [MC] Adds listener.
// [MC] Adds listener to rollButton.
rollButton.addActionListener(new RollListener());
// [MC] Adds listener to newGameButton.
newGameButton.addActionListener(new NewGameListener());
// ======================================================================
// [MC] Creates the labels. Creates new instance of JLabel.
// [MC] Creates the label (rollNumberLabel) for the number of rolls.
JLabel rollNumberLabel = new JLabel("Roll Number");
// [MC] Creates the label (rollResultLabel) for the result of roll.
JLabel rollResultLabel = new JLabel("Roll Result");
// [MC] Creates the label (rollPointsLabel) for the player`s points.
JLabel rollPointsLabel = new JLabel("Player Points");
// [MC] Creates the label (gameFinalResult) for the final game result.
JLabel gameFinalResultLabel = new JLabel("Final Result");
// [MC] Sets the label font.
rollNumberLabel.setFont(new Font("Sansserif", Font.PLAIN, 10));
rollResultLabel.setFont(new Font("Sansserif", Font.PLAIN, 10));
rollPointsLabel.setFont(new Font("Sansserif", Font.PLAIN, 10));
gameFinalResultLabel.setFont(new Font("Sansserif", Font.PLAIN, 10));
// [MC] Sets the label title alignment.
rollNumberLabel.setHorizontalAlignment(JLabel.CENTER);
rollResultLabel.setHorizontalAlignment(JLabel.CENTER);
rollPointsLabel.setHorizontalAlignment(JLabel.CENTER);
gameFinalResultLabel.setHorizontalAlignment(JLabel.CENTER);
// [MC] Sets the label border format.
//rollNumberLabel.setBorder(loweredetched);
//rollResultLabel.setBorder(loweredetched);
//rollPointsLabel.setBorder(loweredetched);
//gameFinalResultLabel.setBorder(loweredetched);
// ======================================================================
// [MC] Sets the text field font.
rollNumberTextField.setFont(new Font("Sansserif", Font.PLAIN, 16));
rollResultTextField.setFont(new Font("Sansserif", Font.PLAIN, 16));
rollPointsTextField.setFont(new Font("Sansserif", Font.PLAIN, 16));
gameFinalResultTextField.setFont(new Font("Sansserif", Font.BOLD, 16));
// [MC] Sets the text field text alignment.
rollNumberTextField.setHorizontalAlignment(JTextField.CENTER);
rollResultTextField.setHorizontalAlignment(JTextField.CENTER);
rollPointsTextField.setHorizontalAlignment(JTextField.CENTER);
gameFinalResultTextField.setHorizontalAlignment(JTextField.CENTER);
// [MC] Sets the text field text colour.
gameFinalResultTextField.setForeground(Color.blue);
// [MC] Sets the text field to not editable.
rollNumberTextField.setEditable(false);
rollResultTextField.setEditable(false);
rollPointsTextField.setEditable(false);
gameFinalResultTextField.setEditable(false);
// ======================================================================
// [MC] Gets sounds.
winClip = getAudioClip(getCodeBase(), "bunny1.au");
looseClip = getAudioClip(getCodeBase(), "bunny1.au");
// ======================================================================
// [MC] Sets the layout manager (GridBagLayout) for this container.
this.setLayout(new GridBagLayout());
// [MC] Creates new instance of GridBagConstraints.
GridBagConstraints c = new GridBagConstraints();
// [MC] Makes the component fill its display area entirely.
c.fill = GridBagConstraints.BOTH;
// [MC] Layouts components.
// [MC] Adds the component newGameButton to this container.
c.gridx = 0; // [MC] Makes this component the leftmost column (column 1).
c.gridy = 0; // [MC] Makes this component the uppermost row (row 1).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 row).
c.gridwidth = 2; // [MC] Specifies the number of columns the component uses (2 columns).
this.add(newGameButton, c); // [MC] Adds the button newGameButton.
// [MC] Adds the component rollButton to this container.
c.gridx = 2; // [MC] Makes this component the third column from left (column 3).
c.gridy = 0; // [MC] Make this component the uppermost row (row 1).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 rows).
c.gridwidth = 2; // [MC] Specifies the number of columns the component uses (2 columns).
this.add(rollButton, c); // [MC] Adds the button rollButton.
// [MC] Adds the component rollNumberLabel to this container.
c.gridx = 0; // [MC] Makes this component the leftmost column (column 1).
c.gridy = 3; // [MC] Makes this component the third row from top (row 3).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 row).
c.gridwidth = 1; // [MC] Specifies the number of columns the component uses (1 column).
c.weightx = 0.1; // [MC] Requests any extra vertical (column) space.
this.add(rollNumberLabel, c); // [MC] Adds the label rollNumberLabel.
// [MC] Adds the component rollResultLabel to this container.
c.gridx = 1; // [MC] Makes this component the second column from left (column 2).
c.gridy = 3; // [MC] Makes this component the third row from top (row 3).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 row).
c.gridwidth = 1; // [MC] Specifies the number of columns the component uses (1 column).
this.add(rollResultLabel, c); // [MC] Adds the label rollResultLabel.
// [MC] Adds the component rollPointsLabel to this container.
c.gridx = 2; // [MC] Makes this component the third column from left (column 3).
c.gridy = 3; // [MC] Makes this component the third row from top (row 3).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 row).
c.gridwidth = 1; // [MC] Specifies the number of columns the component uses (1 column).
this.add(rollPointsLabel, c); // [MC] Adds the label rollPointsLabel.
// [MC] Adds the component gameFinalResultLabel to this container.
c.gridx = 3; // [MC] Makes this component the fourth column from left (column 4).
c.gridy = 3; // [MC] Makes this component the third row from top (row 3).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 row).
c.gridwidth = 1; // [MC] Specifies the number of columns the component uses (1 column).
this.add(gameFinalResultLabel, c); // [MC] Adds the label gameFinalResultLabel.
// [MC] Adds the component rollNumberTextField to this container.
c.gridx = 0; // [MC] Makes this component the leftmost column (column 1).
c.gridy = 4; // [MC] Makes this component the fourth row from top (row 4).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 row).
c.gridwidth = 1; // [MC] Specifies the number of columns the component uses (1 column).
c.weightx = 0.1; // [MC] Requests any extra vertical (column) space.
this.add(rollNumberTextField, c); // [MC] Adds the text field rollNumberTextField.
// [MC] Adds the component rollResultTextField to this container.
c.gridx = 1; // [MC] Makes this component the second column from left (column 2).
c.gridy = 4; // [MC] Makes this component the fourth row from top (row 4).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 row).
c.gridwidth = 1; // [MC] Specifies the number of columns the component uses (1 column).
this.add(rollResultTextField, c); // [MC] Adds the text field rollResultTextField.
// [MC] Adds the component rollPointsTextField to this container.
c.gridx = 2; // [MC] Makes this component the third column from left (column 3).
c.gridy = 4; // [MC] Makes this component the fourth row from top (row 4).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 row).
c.gridwidth = 1; // [MC] Specifies the number of columns the component uses (1 column).
this.add(rollPointsTextField, c); // [MC] Adds the text field rollPointsTextField.
// [MC] Adds the component gameFinalResultTextField to this container.
c.gridx = 3; // [MC] Makes this component the fourth column from left (column 4).
c.gridy = 4; // [MC] Makes this component the fourth row from top (row 4).
c.gridheight = 1; // [MC] Specifies the number of rows the component uses (1 row).
c.gridwidth = 1; // [MC] Specifies the number of columns the component uses (1 column).
this.add(gameFinalResultTextField, c); // [MC] Adds the text field gameFinalResultTextField.
// [MC] Adds the component myLeftDie to this container.
c.gridx = 0; // [MC] Makes this component the leftmost column (column 1).
c.gridy = 1; // [MC] Makes this component the second row from top (row 2).
c.gridheight = 2; // [MC] Specifies the number of rows the component uses (2 rows).
c.gridwidth = 2; // [MC] Specifies the number of columns the component uses (2 columns).
c.weightx = 1.0; // [MC] Requests any extra vertical (column) space.
c.weighty = 1.0; // [MC] Requests any extra horizontal (row) space.
this.add(myLeftDie, c); // [MC] Adds the component myLeftDie.
// [MC] Adds the component myRightDie to this container.
c.gridx = 2; // [MC] Makes this component the third column from left (column 3).
c.gridy = 1; // [MC] Makes this component the second row from top (row 2).
c.gridheight = 2; // [MC] Specifies the number of rows the component uses (2 rows).
c.gridwidth = 2; // [MC] Specifies the number of columns the component uses (2 column).
c.weightx = 1.0; // [MC] Requests any extra column (vertical) space.
c.weighty = 1.0; // [MC] Requests any extra horizontal (row) space.
this.add(myRightDie, c); // [MC] Adds the component myRightDie.
} // [MC] end constructor
// ======================================================================
// [MC] Private class RollListener
// [MC] Inner listener class for rollButton.
private class RollListener implements ActionListener
public void actionPerformed(ActionEvent e)
// [MC] Rolls the dice.
myLeftDie.roll(); // [MC] Rolls left die.
myRightDie.roll(); // [MC] Rolls right die.
finalResult = 0; // [MC] If result = 0 then game is not over.
rolls++; // [MC] Increments the number of rolls.
// [MC] Displays the roll number.
rollNumberTextField.setText(" " + rolls + " ");
// [MC] Returns the result (number of dots) of last roll.
resultLeft = myLeftDie.getValue(); // [MC] Returns the result of the left die.
resultRight = myRightDie.getValue(); // [MC] Returns the result of the right die.
result = resultLeft + resultRight; // [MC] Returns the total result of dice.
// [MC] Displays the result of last roll.
rollResultTextField.setText(" " + result + " ");
// [MC] Sets the rules for the game.
// [MC] Sets the rules for the first roll of dice.
if (first)
// [MC] If the result is 2, 3 or 12 on the first throw, the player loses.
if (result == 2 || result == 3 || result == 12)
finalResult = 2; // [MC] If result = 2 then the player loses and the game is over.
gameFinalResultTextField.setText("LOOSE");
Toolkit.getDefaultToolkit().beep();
rollButton.setEnabled(false); // [MC] Disable rollButton.
first = true; // [MC] Game over after first roll.
// [MC] If the result is 7 or 11 on the first throw, the player wins.
else if (result == 7 || result == 11)
finalResult = 1; // [MC] If result = 1 then the player wins and the game is over.
gameFinalResultTextField.setText("WIN");
//Toolkit.getDefaultToolkit().beep();
rollButton.setEnabled(false); // [MC] Disable rollButton.
first = true; // [MC] Game over after first roll.
// [MC] If the player didn`t win or lose then the results 4, 5, 6, 8, 9 or 10 become the player`s point.
else if (result == 4 || result == 5 || result == 6 || result == 8 || result == 9 || result == 10);
// [MC] Returns the player`s points.
points = result; // [MC] Returns the player`s points.
// [MC] Displays the player`s points.
rollPointsTextField.setText(" " + points + " ");
first = false; // [MC] Game is not over after first roll.
// [MC] Sets the rules for the next rolls (from second roll onwards) of the dice.
// [MC] If the result is 7, then the player loses.
else if (result == 7)
finalResult = 2; // [MC] If result = 2 then the player loses and the game is over.
gameFinalResultTextField.setText("LOOSE");
Toolkit.getDefaultToolkit().beep();
rollButton.setEnabled(false); // [MC] Disable rollButton.
// [MC] If the result is equal to the player`s point, then the player wins.
else if (result == points)
finalResult = 1; // [MC] If result = 1 then the player wins and the game is over.
gameFinalResultTextField.setText("WIN");
winClip.play();
//Toolkit.getDefaultToolkit().beep();
rollButton.setEnabled(false); // [MC] Disable rollButton.
} // [MC] End public void actionPerformed(ActionEvent e).
} // [MC] End private class RollListener.
// ======================================================================
// [MC] Private class NewGameListener
// [MC] Inner listener class for newGameButton.
private class NewGameListener implements ActionListener
public void actionPerformed(ActionEvent e)
// [MC] Initialises instance variables.
first = true; // [MC] Initialise dice roll to first roll.
rolls = 0; // [MC] Initialises number of rolls to 0.
// [MC] Initialises text fields.
rollResultTextField.setText("");
rollNumberTextField.setText("");
rollPointsTextField.setText("");
gameFinalResultTextField.setText("");
rollButton.setEnabled(true); // [MC] Enable rollButton.
} // [MC] End public void actionPerformed(ActionEvent e).
}// [MC] End private class NewGameListener implements ActionListener.
} // [MC] End public class DicePanel extends JPanel.make a backup copy before these changes
it now compiles, but I haven't run/tested it
changed constructor to init(), extending Applet, not JApplet
// [MC] Public class DiceApplet
public class DiceApplet extends Applet
// [MC] Constructor.
public void init()
// [MC] Sets the contentPane property. This method is called by the constructor.
add(new DicePanel());
}then the 'error lines' become
winClip = ((Applet)getParent()).getAudioClip(((Applet)getParent()).getCodeBase(), "bunny1.au");
looseClip = ((Applet)getParent()).getAudioClip(((Applet)getParent()).getCodeBase(), "bunny1.au");there might be additional problems when you run/test it, but this might get you started -
Please?!? Cannot Resolve Symbol Error Message
//Elizabeth Skelton Section 001 Homework Set 3
import javax.swing.JOptionPane;
public class skeltonMaxofThree
public static void main (String[] args)
//ask user for numbers
String stringnum1= JOptionPane.showInputDialog(null, "Please enter first number", "Input", JOptionPane.QUESTION_MESSAGE);
String stringnum2=JOptionPane.showInputDialog(null, "Please enter second number", "Input", JOptionPane.QUESTION_MESSAGE);
String stringnum3=JOptionPane.showInputDialog(null, "Please enter third number", "Input", JOptionPane.QUESTION_MESSAGE);
//convert to numerical
double num1=Double.parseDouble(stringnum1);
double num2=Double.parseDouble(stringnum2);
double num3=Double.parseDouble(stringnum3);
//call max method
double biggest=maximum(num1,num2,num3);
//display answer
String output = "The biggest is " + biggest;
JOptionPane.showMessageDialog(null, output, "Result", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
public static double maximum(double num1, double num2, double num3)
//determine biggest
double biggest=Math.max(num1,num2,num3);
return biggest;
Returns error:
:\My Documents\BD120\skeltonMaxofThree.java:36: cannot resolve symbol
symbol : method max (double,double,double)
location: class java.lang.Math
double biggest=Math.max(num1,num2,num3);
^
1 error
Tool completed with exit code 1the max method of the Math class requires 2 parameters not 3...to find the maximum of 3 numbers u can do something like this...
double biggest = Math.max(num1, Math.max(num2, num3)); -
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 -
"cannot resolve symbol" error when using super.paintComponent
I am trying to override the paintComponent method in a class extending a JFrame, but when I call super.paintComponent(g) from inside the overridden method I get the error
QubicGUI.java:63: cannot resolve symbol
symbol : method paintComponent (java.awt.Graphics)
location: class javax.swing.JFrame
super.paintComponent(g);
^
1 error
I can't see where I am deviating from examples I know work. It is a very small program, so I have included it here:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.net.URL;
class QubicGUI extends JFrame
private int width;
private int height;
private Image background;
public int getWidth()
{ return width; }
public int getHeight()
{ return height; }
public boolean isOpaque()
return true;
public QubicGUI()
super("Qubic"); //set title
// The following gets the default screen device for the purpose of finding the
// current settings of height and width of the screen
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = environment.getDefaultScreenDevice();
DisplayMode display = device.getDisplayMode();
width = display.getWidth();
height = display.getHeight();
// Here we set the window to cover the entire screen with a black background, and
// remove the decorations. (This includes the title bar and close, minimize and
// maximize buttons and the border)
setUndecorated(false);
setVisible(true);
setSize(width,height);
setResizable(false);
setBackground(Color.black);
// Initializes the background Image
Image background = Toolkit.getDefaultToolkit().getImage("background.gif");
// This is included for debugging with a decorated window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // end constructor
public void paintComponent(Graphics g)
super.paintComponent(g);
} // end paintComponenet
} // end QubicGUITwo things I want to know:
1. I was trying to access a variable as JLabel
myLabel; defined in the constructor of a class from
the constructor of another class. I got this error
message - "Cannot access non-static variable from a
static context". Why(When both are non-static am I
getting the message as static context)?Post some code. It's hard to pinpoint a syntax error like that without seeing the code.
Also, there may be cleaner ways of doing what you want without having classes sharing labels.
2. I am using a map to set the attributes of a font.
One of the key-value pair of the map is
TextAttributesHashMap.put(TextAttribute.FOREGROUND,Colo
.BLUE);
But when I using the statement g.drawString("First
line of the address", 40, 200); the text being
displayed is in black and not blue. Why?You need to use the drawString that takes an AttributedCharacterIterator:
import java.awt.*;
import java.awt.font.*;
import java.text.*;
import javax.swing.*;
public class Example extends JPanel {
public static void main(String[] args) {
JFrame f = new JFrame("Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = f.getContentPane();
cp.add(new Example());
f.setSize(400,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
protected void paintComponent(Graphics g) {
super.paintComponent(g);
String text = "Every good boy does fine always";
AttributedString as = new AttributedString(text);
as.addAttribute(TextAttribute.FAMILY, "Lucida Bright");
as.addAttribute(TextAttribute.SIZE, new Float(16));
as.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 0, 5);
as.addAttribute(TextAttribute.FOREGROUND, Color.GREEN, 6, 10);
as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 11, 14);
as.addAttribute(TextAttribute.FOREGROUND, Color.YELLOW, 15, 19);
as.addAttribute(TextAttribute.FOREGROUND, Color.MAGENTA, 20, 24);
as.addAttribute(TextAttribute.FOREGROUND, Color.CYAN, 25, 31);
g.drawString(as.getIterator(), 10, 20); -
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.
Maybe you are looking for
-
How to install osx on an external hard drive
Hello, I am using a mac mini and i would like to run osx and logic studio from the external hd, it is an acomdata 500gb. Please help, thanks. Alex
-
Monitoring WCI 10.3.0 & UCM 10.1.3.5 using OEM 11g R1
As part of the Service Monitoring for our OFM-OUCM environment, we have implemented OEM 11g R1. Our Dev/Test/UAT/Prod environment is comprised of SOA 10.1.3.5, WCI 10.3, UCM 10.1.3.5, multiple DB instances 10.2.0.3/10.2.0.4, IDM 10.1.4.0.1. We are ab
-
Turn off ImageBrowser in CS4 ?
How can I turn off ImageBrowser in CS4 ? Thanks.
-
I created 3 tabs when I created my application. I am using tab 1 and 2 to list the links to the forms that I want to access. Tab one has links to forms where users would enter, modify and save data. Tab two has links to forms where the administrators
-
How do I create a matrix field in a survey?