Mouselistener error
I am getting this error
G:\Java\Exam2\Prob01\Prob01.java:63: local variable label is accessed from within inner class; needs to be declared final
label.setText("CounterClockwise");
^
1 error
Tool completed with exit code 1
Here is the code
// Quincy Minor
// Exam 2 Prob01
// ITSE 2317
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Prob01
public static void main(String[] args)
new Prob01GUI();
}//end main
}//end class Prob01
class Prob01GUI
public Prob01GUI()
JFrame theFrame = new JFrame();
theFrame.setSize(200, 150);
theFrame.setTitle("Quincy Minor");
theFrame.getContentPane().setLayout(new BorderLayout());
JButton button03 = new JButton("3");
theFrame.getContentPane().add(button03, BorderLayout.EAST);
JButton button06 = new JButton("6");
theFrame.getContentPane().add(button06, BorderLayout.SOUTH);
JButton button09 = new JButton("9");
theFrame.getContentPane().add(button09, BorderLayout.WEST);
JButton button12 = new JButton("12");
theFrame.getContentPane().add(button12, BorderLayout.NORTH);
JLabel label = new JLabel(" Clockwise");
label.setName("label1");
theFrame.getContentPane().add(label, BorderLayout.CENTER);
String plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
try
UIManager.setLookAndFeel(plaf);
SwingUtilities.updateComponentTreeUI(theFrame);
catch(Exception exception)
System.out.println(exception);
theFrame.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent event)
System.exit(0);
label.addMouseListener(new MouseAdapter()
public void mousePressed(MouseEvent mouseevent)
label.setText("CounterClockwise");
theFrame.show();//display frame
}//end GUI
}//end class Prob01GUII don't understand this error because the variable label changes on mousePressed therefore it cannot be declared final
final JLabel label = new JLabel(" Clockwise");
The variable 'label' always refers to the same label. One of the attributes of the label changes (the text), but the variable always references the same object.
You could also make 'label' an instance variable instead of a local variable also. Just move the declaration outside the method.
Similar Messages
-
TableSorter errors when adding new data
so here is the deal:
I am using the TableSorter.java helper class with DefaultTableModel
from: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
It works great when the data is static and I get it for the first time. however, occationally, when adding new data I get a NullPointerException error.
in use:
DefaultTableModel.addRow()
DefaultTableModel.removeRow() and
DefaultTableModel.insertRow() methods.
Error:
java.lang.ArrayIndexOutOfBoundsException: 5
at com.shared.model.TableSorter.modelIndex(TableSorter.java:294)
at com.shared.model.TableSorter.getValueAt(TableSorter.java:340)
at javax.swing.JTable.getValueAt(Unknown Source)
at javax.swing.JTable.prepareRenderer(Unknown Source)...
code problem I:
public Object getValueAt(int row, int column)
return tableModel.getValueAt(modelIndex(row), column);
}code problem II:
public int modelIndex(int viewIndex)
return getViewToModel()[viewIndex].modelIndex;
}TableSroter class:
package com.shared.model;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
* TableSorter is a decorator for TableModels; adding sorting
* functionality to a supplied TableModel. TableSorter does
* not store or copy the data in its TableModel; instead it maintains
* a map from the row indexes of the view to the row indexes of the
* model. As requests are made of the sorter (like getValueAt(row, col))
* they are passed to the underlying model after the row numbers
* have been translated via the internal mapping array. This way,
* the TableSorter appears to hold another copy of the table
* with the rows in a different order.
* <p/>
* TableSorter registers itself as a listener to the underlying model,
* just as the JTable itself would. Events recieved from the model
* are examined, sometimes manipulated (typically widened), and then
* passed on to the TableSorter's listeners (typically the JTable).
* If a change to the model has invalidated the order of TableSorter's
* rows, a note of this is made and the sorter will resort the
* rows the next time a value is requested.
* <p/>
* When the tableHeader property is set, either by using the
* setTableHeader() method or the two argument constructor, the
* table header may be used as a complete UI for TableSorter.
* The default renderer of the tableHeader is decorated with a renderer
* that indicates the sorting status of each column. In addition,
* a mouse listener is installed with the following behavior:
* <ul>
* <li>
* Mouse-click: Clears the sorting status of all other columns
* and advances the sorting status of that column through three
* values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
* NOT_SORTED again).
* <li>
* SHIFT-mouse-click: Clears the sorting status of all other columns
* and cycles the sorting status of the column through the same
* three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
* <li>
* CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
* that the changes to the column do not cancel the statuses of columns
* that are already sorting - giving a way to initiate a compound
* sort.
* </ul>
* <p/>
* This is a long overdue rewrite of a class of the same name that
* first appeared in the swing table demos in 1997.
* @author Philip Milne
* @author Brendon McLean
* @author Dan van Enckevort
* @author Parwinder Sekhon
* @version 2.0 02/27/04
public class TableSorter extends AbstractTableModel
protected TableModel tableModel;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator()
public int compare(Object o1, Object o2)
return ((Comparable) o1).compareTo(o2);
public static final Comparator LEXICAL_COMPARATOR = new Comparator()
public int compare(Object o1, Object o2)
return o1.toString().compareTo(o2.toString());
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map columnComparators = new HashMap();
private List sortingColumns = new ArrayList();
public TableSorter()
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
public TableSorter(TableModel tableModel)
this();
setTableModel(tableModel);
public TableSorter(TableModel tableModel, JTableHeader tableHeader)
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
private void clearSortingState()
viewToModel = null;
modelToView = null;
public TableModel getTableModel()
return tableModel;
public void setTableModel(TableModel tableModel)
if (this.tableModel != null)
this.tableModel.removeTableModelListener(tableModelListener);
this.tableModel = tableModel;
if (this.tableModel != null)
this.tableModel.addTableModelListener(tableModelListener);
clearSortingState();
fireTableStructureChanged();
public JTableHeader getTableHeader()
return tableHeader;
public void setTableHeader(JTableHeader tableHeader)
if (this.tableHeader != null)
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer)
this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
this.tableHeader = tableHeader;
if (this.tableHeader != null)
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer())
public boolean isSorting()
return sortingColumns.size() != 0;
private Directive getDirective(int column)
for (int i = 0; i < sortingColumns.size(); i++)
Directive directive = (Directive)sortingColumns.get(i);
if (directive.column == column)
return directive;
return EMPTY_DIRECTIVE;
public int getSortingStatus(int column)
return getDirective(column).direction;
private void sortingStatusChanged()
clearSortingState();
fireTableDataChanged();
if (tableHeader != null)
tableHeader.repaint();
public void setSortingStatus(int column, int status)
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE)
sortingColumns.remove(directive);
if (status != NOT_SORTED)
sortingColumns.add(new Directive(column, status));
sortingStatusChanged();
protected Icon getHeaderRendererIcon(int column, int size)
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE)
return null;
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
private void cancelSorting()
sortingColumns.clear();
sortingStatusChanged();
public void setColumnComparator(Class type, Comparator comparator)
if (comparator == null)
columnComparators.remove(type);
else
columnComparators.put(type, comparator);
protected Comparator getComparator(int column)
Class columnType = tableModel.getColumnClass(column);
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null)
return comparator;
if (Comparable.class.isAssignableFrom(columnType))
return COMPARABLE_COMAPRATOR;
return LEXICAL_COMPARATOR;
private Row[] getViewToModel()
if (viewToModel == null)
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++)
viewToModel[row] = new Row(row);
if (isSorting())
Arrays.sort(viewToModel);
return viewToModel;
public int modelIndex(int viewIndex)
return getViewToModel()[viewIndex].modelIndex;
private int[] getModelToView()
if (modelToView == null)
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++)
modelToView[modelIndex(i)] = i;
return modelToView;
// TableModel interface methods
public int getRowCount()
return (tableModel == null) ? 0 : tableModel.getRowCount();
public int getColumnCount()
return (tableModel == null) ? 0 : tableModel.getColumnCount();
public String getColumnName(int column)
return tableModel.getColumnName(column);
public Class getColumnClass(int column)
return tableModel.getColumnClass(column);
public boolean isCellEditable(int row, int column)
return tableModel.isCellEditable(modelIndex(row), column);
public Object getValueAt(int row, int column)
return tableModel.getValueAt(modelIndex(row), column);
public void setValueAt(Object aValue, int row, int column)
tableModel.setValueAt(aValue, modelIndex(row), column);
// Helper classes
private class Row implements Comparable
private int modelIndex;
public Row(int index)
this.modelIndex = index;
public int compareTo(Object o)
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator it = sortingColumns.iterator(); it.hasNext();)
Directive directive = (Directive) it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison = 0;
// Define null less than everything, except null.
if (o1 == null && o2 == null)
comparison = 0;
} else if (o1 == null)
comparison = -1;
} else if (o2 == null)
comparison = 1;
} else {
comparison = getComparator(column).compare(o1, o2);
if (comparison != 0)
return directive.direction == DESCENDING ? -comparison : comparison;
return 0;
private class TableModelHandler implements TableModelListener
public void tableChanged(TableModelEvent e)
// If we're not sorting by anything, just pass the event along.
if (!isSorting())
clearSortingState();
fireTableChanged(e);
return;
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW)
cancelSorting();
fireTableChanged(e);
return;
// We can map a cell event through to the view without widening
// when the following conditions apply:
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null)
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
private class MouseHandler extends MouseAdapter
public void mouseClicked(MouseEvent e)
JTableHeader h = (JTableHeader) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1)
int status = getSortingStatus(column);
if (!e.isControlDown())
cancelSorting();
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
private static class Arrow implements Icon
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority)
this.descending = descending;
this.size = size;
this.priority = priority;
public void paintIcon(Component c, Graphics g, int x, int y)
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
public int getIconWidth()
return size;
public int getIconHeight()
return size;
private class SortableHeaderRenderer implements TableCellRenderer
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer)
this.tableCellRenderer = tableCellRenderer;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition(JLabel.LEFT);
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
return c;
private static class Directive
private int column;
private int direction;
public Directive(int column, int direction)
this.column = column;
this.direction = direction;
}any input will be appreciated.
thanks
PeterThe code you posted doesn't help us at all. Its just a duplicate of the code from the tutorial. The custom code is what you have written. For example do you update the TableModel from the Event Thread? Do you update the SortModel or the DefaultTableModel? If you actually provide your test code and somebody has already downloaded the sort classes, then maybe they will test your code against the classes. But I doubt if people will download the sort classes and create a test program just to see if they can duplicate your results (at least I know I'm not about to).
-
HELP! Run-time Error with this code.
I'm having problem with the code below. But if I were to remove the writer class and instances of it (writeman), then there are no problems. Can some1 pls tell me why the writer class is giving problems. Btw, no compilation errors, only errors at run-time..........
import java.applet.*;
import java.awt.*;
import java.awt.event.MouseListener;
import java.awt.event.*;
public class HelloWorld extends Applet
public static String MyString = new String("Hello");
Graphics f;
public void init()
Changer Changer1 = new Changer();
writer writeman = new writer();
setBackground(Color.red);
setForeground(Color.green);
addMouseListener(Changer1);
writeman.paintit(f);
public void paint(Graphics g)
g.drawString(MyString,10 ,10);
public class Changer implements MouseListener
public void mouseEntered(MouseEvent e)
setBackground(Color.blue);
MyString = "HI";
paint(f);
repaint();
public void mouseExited(MouseEvent e)
setBackground(Color.red);
repaint();
public void mousePressed(MouseEvent e){};
public void mouseReleased(MouseEvent e){};
public void mouseClicked(MouseEvent e){};
public class writer
public void paintit(Graphics brush)
brush.drawString("can u see me", 20, 20);I assume the exception you are getting is a NullPointerException...
When you applet is loaded, it is initialised with a call to init... the following will then occur...
HelloWorld.init()
writeman.paintit(f)
// f has not been initialised, so is null
brush.drawString("can u see me", 20, 20)
// brush == f == null, accessing a null object causes a NullPointerException!
The simplest way to rectify this is to not maintain your own reference to the Graphics object. Move the writer.paintit(f) method to the HelloWorld.paint(g) method, and pass in the given Graphics object. Also, change the paint(f) call in Changer to repaint(), which will cause the paint method to be called with a valid Graphics object - which will then be passed correctly to writer.
Hope this helps,
-Troy -
Is there a error with this code
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class ClickMe extends Applet implements MouseListener {
private Spot spot = null;
private static final int RADIUS = 7;
public void init() {
addMouseListener(this);
public void paint(Graphics g) {
//draw a black border and a white background
g.setColor(Color.white);
g.fillRect(0, 0, getSize().width - 1, getSize().height - 1);
g.setColor(Color.black);
g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
//draw the spot
g.setColor(Color.red);
if (spot != null) {
g.fillOval(spot.x - RADIUS, spot.y - RADIUS, RADIUS * 2, RADIUS * 2);
public void mousePressed(MouseEvent event) {
if (spot == null) {
spot = new Spot(RADIUS);
spot.x = event.getX();
spot.y = event.getY();
repaint();
public void mouseClicked(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
When I compile the the code I get a "cannot resolve symbol"
private Spot spot = null;
spot = new Spot(RADIUS);
I don't know if these are errors in the code'cannot resolve symbol' errors usually mean a problem with the declarations and initialisations at the start of your class. This is specifically to do with your line private Spot spot = null;
i haven`t much time to look at your code, but i would suggest getting rid of the null initialisation here, and do you ever actually change this value? after a quick look it seems that you only query it to see if the variable spot is null. if you never affect this value, then it will always be null and only one if statement will ever be executed.
but as i said i haven`t any time, so could be off here
boutye - boss is coming bak argh! -
Hi I am getting a no such file error though I am calling functions correctly. I am able to compile successfully but getting these runtime errors.
Can anybody point out what mistake I am doing:-
Here are the error lines:-
java.io.FileNotFoundException: (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:137)
at java.io.FileInputStream.<init>(FileInputStream.java:96)
at java.io.FileReader.<init>(FileReader.java:58)
at Clamando$Roger3.readFile(Clamando.java:96)
at Clamando$Roger3.<init>(Clamando.java:85)
at Clamando.main(Clamando.java:260)
java.io.FileNotFoundException: (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:137)
at java.io.FileInputStream.<init>(FileInputStream.java:96)
at java.io.FileReader.<init>(FileReader.java:58)
at Clamando$Roger3.readFile(Clamando.java:96)
at Clamando$Roger3.<init>(Clamando.java:85)
at Clamando.<init>(Clamando.java:50)
at Clamando$1.run(Clamando.java:265)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:226)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:602)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)readFile(filename); line 85
BufferedReader fh = new BufferedReader(new FileReader(filename)); line 96
getContentPane().add(paintPanel, BorderLayout.CENTER);
new Clamando(0, 0, 0, 0, null, null).setVisible(true);
public class Clamando extends JFrame {
public Color color;
public int top;
public int fixvalue1;
public int fixvalue2;
public int width;
public String text;
public int end;
public int value1;
public int value2;
public int mywidth;
private JPanel Roger3;
public Clamando(int top, int fixvalue1, int width, int fixvalue2, Color c,String text) {
this.color = c;
this.top = top;
this.fixvalue1 = fixvalue1;
this.width = width;
this.fixvalue2 = fixvalue2;
this.text = text;
setDefaultCloseOperation(EXIT_ON_CLOSE);
setMinimumSize(new Dimension(1000, 200));
Roger3 = new Roger3();
getContentPane().add(Roger3, BorderLayout.CENTER);
pack();
static class Roger3 extends JPanel implements MouseMotionListener, MouseListener {
public List<Glyph> glyphs;
public int top;
public int bottom;
public int width;
public String f[];
public int value1;
public int value2;
BufferedImage image;
Graphics2D g2d;
Point startPoint = null;
Point endPoint = null;
public int start;
public int x;
public int y;
int scaledvalue;
public int end;
public String filename = new String();
public Roger3(){
super();
addMouseMotionListener(this);
addMouseListener(this);
boolean mouseClicked = false;
readFile(filename);
System.out.println(filename);
public void readFile(String filename){
this.filename = filename;
glyphs = new ArrayList<Glyph>();
String n = null;
try{
BufferedReader fh = new BufferedReader(new FileReader(filename));
while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){
f = n.split("\t");
value1 = Integer.parseInt(f[5].trim());
value2 = Integer.parseInt(f[6].trim());
top = value1 / 1;
bottom = value2 / 1;
width = bottom - top;
String text = f[5];
Color color = new Color(Integer.parseInt(f[7]));
int fixvalue1 = 60;
int fixvalue2 = 27;
glyphs.add(new Glyph(top, fixvalue1, width, fixvalue2, color, text));
fh.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
public void paintComponent(Graphics g) {
public void mousePressed(MouseEvent e) {
public void mouseDragged(MouseEvent e) {
public void mouseReleased(MouseEvent e) {
public void mouseMoved(MouseEvent e) {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
static class Glyph {
private Rectangle bounds;
private Color color;
private Paint paint;
private String label;
private boolean showLabel = false;
public Glyph(int x, int y, int width, int height, Color color, String label) {
bounds = new Rectangle(x, y, width, height);
this.color = color;
this.paint = new GradientPaint(x, y, color, x, y+height, Color.WHITE);
this.label = label;
public void draw(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(paint);
g2.fill(bounds);
if (showLabel){
g2.setColor(Color.BLACK);
int labelWidth = g2.getFontMetrics().stringWidth(label);
int fontHeight = g2.getFontMetrics().getHeight();
g2.drawString( label,
(int)(bounds.getX()),
(int)(bounds.getY()));
public boolean contains(int x, int y){
return bounds.contains(x,y);
public void showLabel(boolean show){
showLabel = show;
public static void main(String args[]) {
Roger3 hhh = new Roger3();
hhh.readFile(args[0]);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Clamando(0, 0, 0, 0, null, null).setVisible(true);
public Color getColor(){
return color;
public String toString() {
return String.format("Color=%s,top=%d,bottom=%d,width=%d", color.toString(), top, fixvalue1, width, fixvalue2, text);
}ThanksI tried the same thing like this and it works perfectly but why its not working in the above code ?
Here is the code that works:-
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.*;
public class Testwow {
public String filename = new String();
public int one;
public int two;
public String f[];
public Testwow(){
readFile(filename);
System.out.println(filename);
public void readFile(String filename){
this.filename = filename;
System.out.println(filename);
String n = null;
BufferedReader fh;
try{
fh = new BufferedReader(new FileReader(filename));
while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){
f = n.split("\t");
one = Integer.parseInt(f[5].trim());
two = Integer.parseInt(f[6].trim());
System.out.println(one);
System.out.print( two);
fh.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
public static void main(String args[]){
Testwow wow = new Testwow();
wow.readFile(args[0]);
} -
What's wrong with my code? compliation error
There is a compilation error in my program
but i follow others sample prog. to do, but i can't do it
Please help me, thanks!!!
private int selectedRow, selectedCol;
final JTable table = new JTable(new MyTableModel());
public temp() {
super(new GridLayout(1, 0));
table.setPreferredScrollableViewportSize(new Dimension(600, 200));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel rowSM = table.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
//Ignore extra messages.
if (e.getValueIsAdjusting()) return;
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
if (lsm.isSelectionEmpty()) {
System.out.println("No rows are selected.");
else {
selectedRow = lsm.getMinSelectionIndex();
System.out.println("Row " + selectedRow+ " is now selected.");
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
createPopupMenu();
public void createPopupMenu() {
//Create the popup menu.
JPopupMenu popup = new JPopupMenu();
// display item
JMenuItem menuItem = new JMenuItem("Delete selected");
popup.add(menuItem);
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Display selected.");
System.out.println("ClientID: "+table.getValueAt(selectedRow,0));
int index = table.getSelectedColumn();
table.removeRow(index); <-------------------------------compliation error
}}); //what's wrong with my code? can anyone tell
//me what careless mistake i made?
MouseListener popupListener = new PopupListener(popup);
table.addMouseListener(popupListener);
public class MyTableModel extends AbstractTableModel {
private String[] columnNames = { "ClientID", "Name", "Administrator" };
private Vector data = new Vector();
class Row{
public Row(String c, String n, String a){
clientid = c;
name = n;
admin = a;
private String clientid;
private String name;
private String admin;
public MyTableModel(){}
public void removeRow(int r) {
data.removeElementAt(r);
fireTableChanged(null);
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.size();
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return "";
public boolean isCellEditable(int row, int col) {
return false;
public void setValueAt(Object value, int row, int col) {}
}Inside your table model you use a Vector to hold your data. Create a method on your table model
public void removeRow(int rowIndex)
data.remove(rowIndex); // Remove the row from the vector
fireTableRowDeleted(rowIndex, rowIndex); // Inform the table that the rwo has gone
[/data]
In the class that from which you wish to call the above you will need to add a reference to your table model. -
First , I defined a mouselistener like
jButton2.addMouseListener(new MouseAdapter()
public void mousePressed(MouseEvent e)
jButton2_mousePressed(e);
});but when I use this code
private void jButton2_mousePressed(MouseEvent e) throws IOException
setFiles();
compress();
}then it compiles with an error says
Error(74,32): unreported exception: java.io.IOException; must be caught or declared to be thrownwhere line 47 contains
public void mousePressed(MouseEvent e)Note : I have to add "throws IOException" because I deal with files in those functions.
Is there any solution?and you need to start using actions:
http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html -
Error method : mouseClicked();
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at PnlSimulacion.mouseClicked(PnlSimulacion.java:816)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:21
1)
at java.awt.Component.processMouseEvent(Component.java:5491)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
at java.awt.Component.processEvent(Component.java:5253)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3955)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3901)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1774)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
read.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)Here is my class Simulacion:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.Locale;
import java.util.ArrayList;
import java.util.Date;
import java.text.SimpleDateFormat;
//import java.applet.*;
import sun.audio.*;
import java.io.*;
public class PnlSimulacion extends JInternalFrame implements ActionListener,MouseListener {
// Declaraci�n de variables
JPanel pnlTragam,
pnlTxtCredito,pnlTxtCoins,pnlTxtGanancia;
JLabel lblTragamonedas,
lblGirar, lblApostUno, lblApostMax,lblAceptar,
//Labels que contendr�n las im�genes de los rodillos
lblRod1,lblRod2,lblRod3,
lblGirando,
//arreglo de labels(para los numeros
lbl[]=new JLabel[10],lbl1[]=new JLabel[3],lbl2[]=new JLabel[10];
JButton btnAceptar;
ImageIcon girarIn,girarOut,girarPush,apuestaMaximaIn,apuestaMaximaOut,
apuestaMaximaPush,apostarUnoIn,apostarUnoOut,apostarUnoPush;
JTextArea txtS;
//ArrayList de imagenes
ArrayList<ImageIcon> arrImagenes = new ArrayList<ImageIcon>();
//SOLO para la prueba, cambie la variable de moneda
double moneda=50.0;
//variable global de coins
double coins=0;
Timer timer;
//cuenta cuantas veces a giado el rodillo
int girosRod1,girosRod2,girosRod3;
//indice de la imagen que se ve en cada rodillo
int indRodillo1, indRodillo2, indRodillo3;
SimpleDateFormat sdf;
// AudioClip sonido1,betOne,betMax,winBig; esto es para JApplets
// //Creacion del Imput para sonido en JFrame o aplicaciones no Applet
// InputStream in = new FileInputStream("Spin.wav");
// InputStream sonido1 = new FileInputStream("Spin.wav");
// InputStream betOne = new FileInputStream("BetOne.wav");
// InputStream betMax = new FileInputStream("BetMax.wav");
// InputStream winBig = new FileInputStream("WinBig.wav");
// InputStream csonido1 = new FileInputStream("Spin.wav");
//referencia al frame
private MnuPanel m;
public Sonido s; // <-------------------------- THIS COULD BE THE ERROR?
// Crea la interfaz gr�fica de usuario
public PnlSimulacion(MnuPanel m) {
// AudioStream as = new AudioStream(in);
// AudioData data = as.getData();
// ContinuousAudioDataStream cas = new ContinuousAudioDataStream (data);
// AudioStream betOne = new AudioStream(betOne);
// AudioStream betMax = new AudioStream(betMax);
// AudioStream winBig = new AudioStream(winBig);
getContentPane().setLayout(null);
// sonido1=getAudioClip(getDocumentBase(),);
// betOne=getAudioClip(getDocumentBase(),"BetOne.wav");
// betMax=getAudioClip(getDocumentBase(),"BetMax.wav");
// winBig=getAudioClip(getDocumentBase(),"WinBig.wav");
Date d = new Date();
//para fomratear adecuadamente
//SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yy");
sdf=new SimpleDateFormat("dd/MM/yy hh:mm:ss");
//crea el timer, ajustarlo segun se kiera
timer= new Timer(40,this);
//PANEL TRAGAMONEDAS
//Panel del tragamonedas
pnlTragam=new JPanel();
pnlTragam.setLayout(null);
pnlTragam.setBounds(0,0,800,640);
pnlTragam.setVisible(true);
getContentPane().add(pnlTragam);
// textArea para el ticket
txtS=new JTextArea();
txtS.setBounds(635,240,152,230);
txtS.setEditable(false);
pnlTragam.add(txtS);
//crea un label que es el que contendr� la imag�n del simulador
lblTragamonedas=new JLabel(
new ImageIcon(getClass().getResource("FondoTragamonedas.png")));
lblTragamonedas.setBounds(0,0,800,640);
pnlTragam.add(lblTragamonedas);
//BOTON aceptar del ticket
btnAceptar=new JButton(
new ImageIcon(getClass().getResource("aceptar.jpg")));
btnAceptar.setBounds(682,483,72,21);
btnAceptar.addActionListener(this);
pnlTragam.add(btnAceptar);
//imagenes de los botones para cargar
girarIn = new ImageIcon(
getClass().getResource("girarIn.jpg"));
girarOut = new ImageIcon(
getClass().getResource("girarOut.jpg"));
girarPush = new ImageIcon(
getClass().getResource("girarPush.jpg"));
apuestaMaximaIn = new ImageIcon(
getClass().getResource("apuestaMaximaIn.jpg"));
apuestaMaximaOut = new ImageIcon(
getClass().getResource("apuestaMaximaOut.jpg"));
apuestaMaximaPush = new ImageIcon(
getClass().getResource("apuestaMaximaPush.jpg"));
apostarUnoIn = new ImageIcon(
getClass().getResource("apostarUnoIn.jpg"));
apostarUnoOut = new ImageIcon(
getClass().getResource("apostarUnoOut.jpg"));
apostarUnoPush = new ImageIcon(
getClass().getResource("apostarUnoPush.jpg"));
//lblGirar
lblGirar=new JLabel(girarOut);
lblGirar.setBounds(451,517,66,42);
lblGirar.addMouseListener(this);
lblGirar.setToolTipText("presione para girar los rodillos");
lblGirar.setCursor(new Cursor(Cursor.HAND_CURSOR));
pnlTragam.add(lblGirar);
//lbl de apuesta "uno por uno"
lblApostUno=new JLabel(apostarUnoOut);
lblApostUno.setBounds(375,518,61,41);
lblApostUno.addMouseListener(this);
lblApostUno.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblApostUno.setToolTipText("presione para apostar solo una moneda");
pnlTragam.add(lblApostUno);
//BOTON de apuesta "maxima" (2 soles)
lblApostMax=new JLabel(apuestaMaximaOut);
lblApostMax.setBounds(528,518,67,41);
lblApostMax.addMouseListener(this);
lblApostMax.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblApostMax.setToolTipText("presione para reaizar la maxima apuesta");
pnlTragam.add(lblApostMax);
//gif GIRANDO...
lblGirando = new JLabel(new ImageIcon(
getClass().getResource("girando.gif")));
lblGirando.setBounds(400,598,69,17);
lblGirando.setVisible(false);
lblTragamonedas.add(lblGirando);
//PANEL MUESTRA_CREDITO
//este es un peque�o panel que contiene imagenes de mumeros
pnlTxtCredito=new JPanel();
pnlTxtCredito.setLayout(null);
pnlTxtCredito.setBounds(408,470,102,19);
pnlTxtCredito.setVisible(true);
lblTragamonedas.add(pnlTxtCredito);
//PANEL MUESTRA_MONEDAS_INSERTADAS(COINS)
//este es un peque�o panel que contiene imagenes de mumeros
pnlTxtCoins=new JPanel();
pnlTxtCoins.setLayout(null);
pnlTxtCoins.setBounds(539,427,25,19);
pnlTxtCoins.setVisible(true);
lblTragamonedas.add(pnlTxtCoins);
//PANEL MUESTRA_GANANCIA
//este es un peque�o panel que contiene imagenes de mumeros
pnlTxtGanancia=new JPanel();
pnlTxtGanancia.setLayout(null);
pnlTxtGanancia.setBounds(272,470,102,19);
pnlTxtGanancia.setVisible(true);
lblTragamonedas.add(pnlTxtGanancia);
//labels que muestran las imagenes de los rodillos-------------
lblRod1=new JLabel();
lblRod1.setBounds(255,343,80,110);
pnlTragam.add(lblRod1);
lblRod2=new JLabel();
lblRod2.setBounds(342,343,80,110);
pnlTragam.add(lblRod2);
lblRod3=new JLabel();
lblRod3.setBounds(429,343,80,110);
pnlTragam.add(lblRod3);
//metodos a mostrar cuando inicia el programa
mostrarNada();
mostrarNada1();
mostrarNada2();
procesarCredito(moneda);
cargaImagenes();
lblRod1.setIcon(arrImagenes.get(0));
lblRod2.setIcon(arrImagenes.get(0));
lblRod3.setIcon(arrImagenes.get(0));
//muestra la imagen
// Procesa eventos de tipo ActionEvent
public void actionPerformed( ActionEvent e ){
//cuando el timer esta activo
if(e.getSource()==timer){
//esto suceder� cada 100milisegundos
girar();
//desactiva las acciones de los Botones (labels)
if(e.getSource()==lblApostUno){//no hace nada
if(e.getSource()==lblApostMax){//no hace nada
if(e.getSource()==lblGirar){//no hace nada
if(e.getSource()==btnAceptar){
txtS.setText("");
}//fin de action performed
//METODOS PROPIOS
int aleatorio(int min,int max){
return (int)((max-min+1)*Math.random()+min);
//PANEL MUESTRA_CREDITO
void procesarCredito(double numero){
String num=numero +"0";
limpiar();
int pos=0;
char caracter;
for(int i=num.length()-1;i>=0;i--){
caracter=num.charAt(i);
if(caracter=='.'){
lbl[pos].setIcon(new ImageIcon(getClass().getResource(
"im10.jpg")));
pos++;
}else{
lbl[pos].setIcon(new ImageIcon(getClass().getResource(
"im"+caracter+".jpg")));
pos++;
}//fin del for
}//fin de muestraCredito
void limpiar(){
for(int i=0;i<10;i++){
lbl.setIcon(new ImageIcon(getClass().getResource(
"imSin.jpg")));
void mostrarNada(){
for(int i=0;i<2;i++){
lbl[i]=new JLabel(new ImageIcon(getClass().getResource(
"im0.jpg")));
lbl[i].setBounds(91-i*11,0,11,19);
pnlTxtCredito.add(lbl[i]);
lbl[2]=new JLabel(new ImageIcon(getClass().getResource(
"im10.jpg")));//rep el punto
lbl[2].setBounds(77,0,3,19);
pnlTxtCredito.add(lbl[2]);
for(int i=3;i<10;i++){
lbl[i]=new JLabel(new ImageIcon(getClass().getResource(
"imSin.jpg")));
lbl[i].setBounds(99-i*11,0,11,19);
pnlTxtCredito.add(lbl[i]);
}//fin de mostarNada
//MUESTRA COINS
void procesarCoins(double numero){
String num=""+numero;
limpiar1();
int pos=0;
char caracter;
for(int i=num.length()-1;i>=0;i--){
caracter=num.charAt(i);
if(caracter=='.'){
lbl1[pos].setIcon(new ImageIcon(getClass().getResource(
"im10.jpg")));
pos++;
}else{
lbl1[pos].setIcon(new ImageIcon(getClass().getResource(
"im"+caracter+".jpg")));
pos++;
}//fin del for
}//fin de procesarCoins
void limpiar1(){
for(int i=0;i<3;i++){
lbl1[i].setIcon(new ImageIcon(getClass().getResource(
"imSin.jpg")));
void mostrarNada1(){
lbl1[0]=new JLabel(new ImageIcon(getClass().getResource("im0.jpg")));
lbl1[0].setBounds(14,0,11,19);
pnlTxtCoins.add(lbl1[0]);
lbl1[1]=new JLabel(new ImageIcon(getClass().getResource("im10.jpg")));
lbl1[1].setBounds(11,0,3,19);
pnlTxtCoins.add(lbl1[1]);
lbl1[2]=new JLabel(new ImageIcon(getClass().getResource("im0.jpg")));
lbl1[2].setBounds(0,0,11,19);
pnlTxtCoins.add(lbl1[2]);
//MUESTRA_GANANCIA
void procesarGanancia(double numero){
String num=numero+"0";
limpiar2();
int pos=0;
char caracter;
for(int i=num.length()-1;i>=0;i--){
caracter=num.charAt(i);
if(caracter=='.'){
lbl2[pos].setIcon(new ImageIcon(getClass().getResource(
"im10.jpg")));
pos++;
}else{
lbl2[pos].setIcon(new ImageIcon(getClass().getResource(
"im"+caracter+".jpg")));
pos++;
}//fin del for
}//fin de procesarGanancia
void limpiar2(){
for(int i=0;i<10;i++){
lbl2[i].setIcon(new ImageIcon(getClass().getResource(
"imSin.jpg")));
}//fin de for
void mostrarNada2(){
for(int i=0;i<2;i++){
lbl2[i]=new JLabel(new ImageIcon(getClass().getResource(
"im0.jpg")));
lbl2[i].setBounds(91-i*11,0,11,19);
pnlTxtGanancia.add(lbl2[i]);
lbl2[2]=new JLabel(new ImageIcon(getClass().getResource(
"im10.jpg")));
lbl2[2].setBounds(77,0,3,19);
pnlTxtGanancia.add(lbl2[2]);
for(int i=3;i<10;i++){
lbl2[i]=new JLabel(new ImageIcon(getClass().getResource(
"imSin.jpg")));
lbl2[i].setBounds(99-i*11,0,11,19);
pnlTxtGanancia.add(lbl2[i]);
void pasarCredito(){
//restamos 0.50 a moneda por cada presionada de boton "Apostar Uno"
moneda-=0.5;
//aumentamos 0.5 a la apuesta
coins+=0.5;
//solo puede apostarse 2.00 como m�ximo.validamos:
//Si la apuesta llega a 2.5
if(coins==2.5){
//entonces devolvemos los 2.5 a moneda
moneda+=2.50;
//y cambiamos cois a cero
coins=0.0;
}//fin de if
}//fin de pasarCredito
void pasarMaximoMonedas(){
for(double i=coins;i<2.0;i+=0.5){
coins+=0.5;
moneda-=0.5;
void girar(){
//limpia el panel de ganancia
procesarGanancia(0);
//si los rodillos dejaron de girar
if( (girosRod1+girosRod2+girosRod3)==0){
//detiene el timer
lblGirando.setVisible(false);
timer.stop();
// AudioPlayer.player.stop(sonido1);
// String spin = "spin.wav";
// try {
// URL clipUrl = new URL("file:" + spin);
// AudioClip audioClip = Applet.newAudioClip("spin.wav");
// audioClip.play();
// Thread.currentThread().sleep(3000);
// } catch (Exception e) {
// e.printStackTrace();
//comprueba los resultados
comprovarResultados(indRodillo1,indRodillo2,indRodillo3 );
}else{
// sonido1.loop();
// AudioPlayer.player.start (csonido1);
lblGirando.setVisible(true);
//Giran los rodillos seg�n la cantidad de rotaciones aleatorias
//verifica si falta rodar un rodillo
if(girosRod1>0){
//cambiar la imagen y almacenar el indice de la que se encuentra
indRodillo1=girarImagen(lblRod1,indRodillo1);
//decrementar el numero de rotaciones del rodillo
girosRod1--;
if(girosRod2>0){
//cambiar la imagen y almacenar el indice de la que se encuentra
indRodillo2=girarImagen(lblRod2,indRodillo2);
//decrementar el numero de rotaciones del rodillo
girosRod2--;
if(girosRod3>0){
//cambiar la imagen y almacenar el indice de la que se encuentra
indRodillo3=girarImagen(lblRod3,indRodillo3);
//decrementar el numero de rotaciones del rodillo
girosRod3--;
}//fin de else
}//fin del m�todo girar
void comprovarResultados(int var1,int var2,int var3 ){
String result=""+ var1+ var2+ var3;
//si sali� las tres imagenes bar*1
if(result.equals("222")){
// AudioPlayer.player.start(winBig);
// winBig.play();
moneda=moneda +coins*20;
procesarCredito(moneda);
procesarGanancia(coins*20);
imprimirTicket(20);
mensaje("ud. a ganado :"+coins*20);
coins=0;
procesarCoins(coins);
//si sali� las tres imagenes bar*2
}else if(result.equals("444")){
// AudioPlayer.player.start(winBig);
// winBig.play();
moneda=moneda +coins*40;
procesarCredito(moneda);
procesarGanancia(coins*40);
imprimirTicket(40);
mensaje("ud. a ganado :"+coins*40);
coins=0;
procesarCoins(coins);
//si sali� las tres imagenes bar*3
}else if(result.equals("888")){
// AudioPlayer.player.start(winBig);
// winBig.play();
moneda=moneda +coins*80;
procesarCredito(moneda);
procesarGanancia(coins*80);
imprimirTicket(80);
mensaje("ud. a ganado :"+coins*80);
coins=0;
procesarCoins(coins);
//si sali� las tres imagenes dolar
}else if(result.equals("000")){
// AudioPlayer.player.start(winBig);
// winBig.play();
moneda=moneda +coins*1000;
procesarCredito(moneda);
procesarGanancia(coins*1000);
imprimirTicket(1000);
mensaje("ud. a ganado :"+coins*1000);
coins=0;
procesarCoins(coins);
//si sali� las tres imagenes cereza
}else if(result.equals("666")){
// AudioPlayer.player.start(winBig);
// winBig.play();
moneda=moneda +coins*160;
procesarCredito(moneda);
procesarGanancia(coins*160);
imprimirTicket(106);
mensaje("ud. a ganado :"+coins*160);
coins=0;
procesarCoins(coins);
//si salieron 3 bares cualquiera
}else if(
result.equals("224") || result.equals("228") ||
result.equals("242") || result.equals("244") ||
result.equals("248") || result.equals("282") ||
result.equals("284") || result.equals("288") ||
result.equals("422") || result.equals("424") ||
result.equals("428") || result.equals("442") ||
result.equals("448") || result.equals("482") ||
result.equals("484") || result.equals("488") ||
result.equals("822") || result.equals("824") ||
result.equals("828") || result.equals("842") ||
result.equals("844") || result.equals("848") ||
result.equals("882") || result.equals("884")
// AudioPlayer.player.start(winBig);
// winBig.play();
moneda=moneda + coins*10;
procesarCredito(moneda);
procesarGanancia(coins*10);
mensaje("ud. a ganado :"+coins*10);
imprimirTicket(10);
coins=0;
procesarCoins(coins);
//si sale dos cerezas
}else if(
result.matches("[6][6][0-9]")||
result.matches("[0-9][6][6]")||
result.matches("[6][0-9][6]")
// AudioPlayer.player.start(winBig);
// winBig.play();
moneda=moneda + coins*5;
procesarCredito(moneda);
procesarGanancia(coins*5);
imprimirTicket(5);
mensaje("ud. a ganado :"+coins*5);
coins=0;
procesarCoins(coins);
//si sale una cereza
}else if( result.matches("[6][0-9][0-9]")||
result.matches("[0-9][6][0-9]")||
result.matches("[0-9][0-9][6]")
// AudioPlayer.player.start(winBig);
// winBig.play();
moneda=moneda + coins*2;
procesarCredito(moneda);
procesarGanancia(coins*2);
imprimirTicket(2);
mensaje("ud. a ganado :"+coins*2);
coins=0;
procesarCoins(coins);
} else {
coins=0;
procesarCoins(coins);
procesarGanancia(0);
int girarImagen(JLabel lblImagen, int indiceImagenActual){
// Si la imagen que se ve actualmente es la �ltima se
// debe mostrar la primera (0)
if( indiceImagenActual == 9){
indiceImagenActual = -1;
// Mostrar la siguiente imagen seg�n el indice actual
lblImagen.setIcon(arrImagenes.get(indiceImagenActual+1));
return indiceImagenActual+1;
void cargaImagenes(){
//Carga las im�genes de los rodillos
for(int i=0; i<10; i++){
arrImagenes.add(new ImageIcon(
getClass().getResource("imag"+i+".png")
void imprimirTicket(int producto){
Date d = new Date();
txtS.setText(" TRAGAMONEDAS \n");
txtS.append(" CIBERTEC\n ");
txtS.append("******************************\n");
txtS.append("Gan� \t: S/. "+coins*producto +"\n");
txtS.append("Credito actual\t: S/. "+moneda +"\n");
txtS.append("****************************** \n");
txtS.append("Gracias por jugar \n ");
txtS.append(""+ sdf.format(d));
void mensaje(String text1){
JOptionPane.showMessageDialog(this,text1,"Mensaje",1);
//---------------------METODOS PARA EVENTOS DE MOUSE-------------------
public void mousePressed(MouseEvent e) {
if(e.getSource()==lblGirar){
lblGirar.setIcon(girarPush);
if(e.getSource()==lblApostUno){
lblApostUno.setIcon(apostarUnoPush);
if(e.getSource()==lblApostMax){
lblApostMax.setIcon(apuestaMaximaPush);
public void mouseReleased(MouseEvent e) {
if(e.getSource()==lblGirar){
lblGirar.setIcon(girarIn);
if(e.getSource()==lblApostUno){
lblApostUno.setIcon(apostarUnoIn);
if(e.getSource()==lblApostMax){
lblApostMax.setIcon(apuestaMaximaIn);
public void mouseEntered(MouseEvent e) {
if(e.getSource()==lblGirar){
lblGirar.setIcon(girarIn);
if(e.getSource()==lblApostMax){
lblApostMax.setIcon(apuestaMaximaIn);
if(e.getSource()==lblApostUno){
lblApostUno.setIcon(apostarUnoIn);
public void mouseExited(MouseEvent e) {
if(e.getSource()==lblGirar){
lblGirar.setIcon(girarOut);
if(e.getSource()==lblApostMax){
lblApostMax.setIcon(apuestaMaximaOut);
if(e.getSource()==lblApostUno){
lblApostUno.setIcon(apostarUnoOut);
// AudioPlayer.player.stop(betOne);
public void mouseClicked(MouseEvent e) {
//Se ejecuta al darle click al JLabel lblGirar
if(e.getSource()==lblGirar){
if(coins==0){
JOptionPane.showMessageDialog(this,"ingrese una moneda",
"Mensaje",1);
}else if(moneda<0){
JOptionPane.showMessageDialog(this,"Recargue su tarjeta",
"Mensaje",1);
}else{
//mediante los numeros aleatorios generamos el n�mero de giros
//que dara cada rodillo
girosRod1=aleatorio(10,40);
girosRod2=aleatorio(girosRod1+10,girosRod1+40);
girosRod3=aleatorio(girosRod2+10,girosRod2+40);
//inicia el Timer
timer.start();
}//fin de btn girar
//boton Apostar Uno
if(e.getSource()==lblApostUno){
// AudioPlayer.player.start(betOne);
// betOne.play();
//si no se tiene credito muestra un mensaje
if(moneda<=0){
JOptionPane.showMessageDialog(this,"Recargue su tarjeta",
"Mensaje",1);
//si se tiene credito
}else{
pasarCredito();
procesarCoins(coins);
procesarCredito(moneda);
}//fin de apostar uno
//si se presiona el boton de apuesta m�xima
if(e.getSource()==lblApostMax){
s.playBetMax();
// AudioPlayer.player.start(betMax);
// betMax.play();
//si tiene 2 o mas soles se puede efectuar la apuesta maxima
if(moneda>=2){
pasarMaximoMonedas();
procesarCoins(coins);
procesarCredito(moneda);
}//sino se muestra un mensaje
else{
JOptionPane.showMessageDialog(this,
"No cuenta con cr�dito suficiente para efectuar una"+
"apuesta m�xima ", "Mensaje",1);
}//fin de apuesta m�xima
}//fin de public
}//fin de la clase
and my class Sonido:
import java.net.URL;
import java.io.FileInputStream;
import sun.audio.*;
public class Sonido {
public AudioData spinData,betOneData,betMaxData,winBigData;
public AudioDataStream spinStream, betOneStream, betMaxStream, winBigStream ;
public ContinuousAudioDataStream continuousSpinStream,continuousBetOneStream,continuousBetMaxStream,continuousWinBigStream;
static int length;
public Sonido (URL url) throws java.io.IOException {//ITS ALL CORRECTLY? WHERE I HAVE TO PUT THE URL CLASSES/"FILE.WAV"
spinData = new AudioStream (url.openStream()).getData();
betOneData = new AudioStream (url.openStream()).getData();
betMaxData = new AudioStream (url.openStream()).getData();
winBigData = new AudioStream (url.openStream()).getData();
spinStream = null;
betOneStream = null;
betMaxStream = null;
winBigStream = null;
continuousSpinStream = null;
continuousBetOneStream = null;
continuousBetMaxStream = null;
continuousWinBigStream = null;
public Sonido (String Spin,String WinBig,String BetOne,String BetMax ) throws java.io.IOException {
FileInputStream spin = new FileInputStream (Spin);
FileInputStream winBig = new FileInputStream (WinBig);
FileInputStream betOne = new FileInputStream (BetOne);
FileInputStream betMax = new FileInputStream (BetMax);
AudioStream spinStream = new AudioStream (spin);
AudioStream betOneStream = new AudioStream (winBig);
AudioStream betMaxStream = new AudioStream (betOne);
AudioStream winBigStream = new AudioStream (betMax);
spinData = spinStream.getData();
betOneData = betOneStream.getData();
betMaxData = betMaxStream.getData();
winBigData = winBigStream.getData();
spinStream = null;
betOneStream = null;
betMaxStream = null;
winBigStream = null;
continuousSpinStream = null;
continuousBetOneStream = null;
continuousBetMaxStream = null;
continuousWinBigStream = null;
public void playSpin() {
spinStream = new AudioDataStream (spinData);
AudioPlayer.player.start (spinStream);
public void loopSpin() {
continuousSpinStream = new ContinuousAudioDataStream (spinData);
AudioPlayer.player.start (continuousSpinStream);
public void stopSpin() {
if (spinStream != null)
AudioPlayer.player.stop (spinStream);
if (continuousSpinStream != null)
AudioPlayer.player.stop (continuousSpinStream);
public void playBetOne() {
betOneStream = new AudioDataStream (betOneData);
AudioPlayer.player.start (betOneStream);
public void loopBetOne() {
continuousBetOneStream = new ContinuousAudioDataStream (betOneData);
AudioPlayer.player.start (continuousBetOneStream);
public void stopBetOne() {
if (betOneStream != null)
AudioPlayer.player.stop (betOneStream);
if (continuousBetOneStream != null)
AudioPlayer.player.stop (continuousBetOneStream);
public void playBetMax() {
betMaxStream = new AudioDataStream (betMaxData);
AudioPlayer.player.start (betMaxStream);
public void loopBetMax() {
continuousSpinStream = new ContinuousAudioDataStream (spinData);
AudioPlayer.player.start (continuousSpinStream);
public void stopBetMax() {
if (betMaxStream != null)
AudioPlayer.player.stop (betMaxStream);
if (continuousBetMaxStream != null)
AudioPlayer.player.stop (continuousBetMaxStream);
public void playWinBig () {
winBigStream = new AudioDataStream (winBigData);
AudioPlayer.player.start (winBigStream);
public void loopWinBig () {
continuousWinBigStream = new ContinuousAudioDataStream (spinData);
AudioPlayer.player.start (continuousWinBigStream);
public void stopWinBig () {
if (winBigStream != null)
AudioPlayer.player.stop (winBigStream);
if (continuousWinBigStream != null)
AudioPlayer.player.stop (continuousWinBigStream);
// public static void main (String args[]) throws Exception {
// URL url1 = new URL ("http://localhost:8080/audio/1.au");
// URL url2 = new URL ("http://localhost:8080/audio/2.au");
// PruebaSonido sac1 = new PruebaSonido (url1);
// PruebaSonido sac2 = new PruebaSonido (url2);
// PruebaSonido sac3 = new PruebaSonido ("1.au");
// sac1.play ();
// sac2.loop ();
// sac3.play ();
// try {// Delay for loop
// Thread.sleep (2000);
// } catch (InterruptedException ie) {}
// sac2.stop();
}uhmmmmmm that's all someone know why dont play my .wav files? thanks a lotin the tutorial the code of the class Sonido is like this:, i cant find a constructor, you can?
import java.net.URL;
import java.io.FileInputStream;
import sun.audio.*;
public class SunAudioClip {
private AudioData audiodata;
private AudioDataStream audiostream;
private ContinuousAudioDataStream continuousaudiostream;
static int length;
public SunAudioClip (URL url) throws java.io.IOException {
audiodata = new AudioStream (url.openStream()).getData();
audiostream = null;
continuousaudiostream = null;
public SunAudioClip (String Spin) throws java.io.IOException {
FileInputStream fis = new FileInputStream (Spin);
AudioStream audioStream = new AudioStream (fis);
audiodata = audioStream.getData();
audiostream = null;
continuousaudiostream = null;
public void play () {
audiostream = new AudioDataStream (audiodata);
AudioPlayer.player.start (audiostream);
public void loop () {
continuousaudiostream = new ContinuousAudioDataStream (audiodata);
AudioPlayer.player.start (continuousaudiostream);
public void stop () {
if (audiostream != null)
AudioPlayer.player.stop (audiostream);
if (continuousaudiostream != null)
AudioPlayer.player.stop (continuousaudiostream);
public static void main (String args[]) throws Exception {
URL url1 = new URL ("http://localhost:8080/audio/1.au");
URL url2 = new URL ("http://localhost:8080/audio/2.au");
SunAudioClip sac1 = new SunAudioClip (url1);
SunAudioClip sac2 = new SunAudioClip (url2);
SunAudioClip sac3 = new SunAudioClip ("1.au");
sac1.play ();
sac2.loop ();
sac3.play ();
try {// Delay for loop
Thread.sleep (2000);
} catch (InterruptedException ie) {}
sac2.stop();
} -
MouseListener for mousedown function in sub-menu buttons
Hello people, sorry to ask this as i am quite new to using AS
in flash, im using AS2.
Basically i have a menu which appears on a mouseover on a
button, on this menu i have some buttons. These buttons need to
have the function that when the user clicks and holds down the
mouse button it moves through an animation frame by frame.
i understand the basica principal of:
var mouseListener:object = newObject ();
then calling it
mouseListener.onMouseDown = function() {
imgBar.prevFrame();
if you see my attached code you will see this is basically
it, i will attach the code that i have on the top level of my flash
file, the onPress functions currently work but i need them replaced
with onMouseDown.
As i said i am quite new to this so i appologise if this is a
noobish error.
Thanks for you time and help.I'm not sure what "i-apps" is. Could you let me know?
iPhoto, iTunes, iDVD, iMovie, etc.
I tried to do the two suggestions at the link from Glo H. First, I dragged out the song and then the background music that was in there. When I clicked on the black audio icon, no sound waves appeared.
I think it is just this sub-menu in this one particular theme that is having a problem.
Drag the music of your choice to the audio well, and look at the slider for menu volume. Is it to the far left, for "minimum"? If it is, move it to the middle.
If the problem persists, give this basic remedy a try. Quit iDVD and delete your iDVD preferences. To do this, go to your username> library> preferences> com.apple.idvd.plist. Delete this file. Then reopen iDVD; it will create a new preference file with all of the default settings. -
The problem about MouseListener,MouseMotionListener
When I compile my program I face a problem with the compiled informatioin:
XYZApp.java:137: DisplayPanel should be declared abstract; it does not define mouseDragged(java.awt.event.MouseEvent) in DisplayPanel
class DisplayPanel extends JPanel implements MouseListener,MouseMotionListener
And the DisplayPanel class is below:
class DisplayPanel extends JPanel implements MouseListener,MouseMotionListener
DisplayPanel()
{}//constructor
//Add or remove the mouse response
public void PanelremoveMouseListener()
removeMouseListener(this);
public void PanelremoveMouseMotionListener()
removeMouseMotionListener(this);
public void PaneladdMouseListener()
addMouseListener(this);
public void PaneladdMouseMotionListener()
addMouseMotionListener(this);
public void MouseClicked(MouseEvent e)
JOptionPane.showMessageDialog(this,"能响应鼠标");
public void MousePressed(MouseEvent e)
public void MouseReleaseed(MouseEvent e)
public void MouseEntered(MouseEvent e)
public void MouseExited(MouseEvent e)
public void MouseDraggeded(MouseEvent e)
public void MouseMoved(MouseEvent e)
What is the problem?When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].
Error messages are really cool; they'll generally do a real good job of telling you what's wrong. Learn to read them - it's essential you understand them if you want to improve as a programmer. -
Hi!
My navigation goes wrong, but perhaps it's an easy answer to it?
In my application I have a JFrame with BorderLayout.
In West I have a JPanel with some JLabels ( let's call them A, B and C)
creating a menu with 3 alternatives and in Center I have ( in the start )
a JPanel 'aPanel' with many components with different LayoutManagers.
Then the user clicks on B 'bPanel' with it's content is to be shown
in Center and the same for the C alternative. I use MouseListener for
the mouse click on the labels.
In the mouseClicked method I invoke one of three open methods for the choice and
inside thoose to make the change I use:
container.remove(aPanel)
and after making some changes to the components to be shown:
container.add(bPanel, Border....)
Many of the components are used in all three alternative JPanels.
What's my problem?
Click B - 'bPanel' appears, click C - 'cPanel' appears, good,
then click any of the alternative and everything goes wrong, only some of
the components in the panel are shown and perhaps on the wrong place. Why?
If I hardcode the invoke of the methods (not using users choice) I can walk
around a, b, c, b, a, c and everything in shown perfectly!!!!
If you have any idea, please help me!thanks for reply
getting below error hencecanot assign p*nts
An error has occured while assigning points. Please refresh the thread view and try again. -
Errors dont know what is wrong!
Errors dont know what is wrong!
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.event.MouseListener;
import java.awt.event.*;
public class SquareShape extends Piece
{private Rectangle2D.Double _square1, _square2, _square3, _square4;
private int xLoc=80, yLoc=0, size=19, space=1;
private smallPiece [][] rectangle;
public SquareShape(smallPiece[][] rect)
{super(Color.red);
_square1 = new Rectangle2D.Double(xLoc,yLoc,size,size);
_square2 = new Rectangle2D.Double(xLoc,yLoc+size+space,size,size);
_square3 = new Rectangle2D.Double(xLoc+size+space,yLoc,size,size);
_square4 = new Rectangle2D.Double(xLoc+size+space,yLoc+size+space,size,size);
rectangle= rect;}
public void setXLocation(int x)
{_square1.setFrame(xLoc+x,yLoc,size,size);
_square2.setFrame(xLoc+x,yLoc+size+space,size,size);
_square3.setFrame(xLoc+size+space+x,yLoc,size,size);
_square4.setFrame(xLoc+size+space+x,yLoc+size+space,size,size);
xLoc=xLoc+x;}
public void setYLocation(int y)
{_square1.setFrame(xLoc,yLoc+y,size,size);
_square2.setFrame(xLoc,yLoc+size+space+y,size,size);
_square3.setFrame(xLoc+size+space,yLoc+y,size,size);
_square4.setFrame(xLoc+size+space,yLoc+size+space+y,size,size);
yLoc=yLoc+y;}
public boolean moveOneStep()
{if(_square2.getY()+size>=440||_square4.getY()>=440)
return false;
else
if(rectangle[21-((int)(_square2.getY()+1))/20][9-((int)(_square2.getX()+1))/20]!=null || rectangle[21-((int)(_square4.getY()+1))/20][9-((int)(_square4.getX()+1))/20]!=null)
{return false;}
else
{setYLocation(20);
return true;}}
public int[][] getLocs()
{int[][] locs= new int[4][2];
locs[0][0]= ((int)(_square1.getY()+1))/20;
locs[0][1]= ((int)(_square1.getX()+1))/20;
locs[1][0]= ((int)(_square2.getY()+1))/20;
locs[1][1]= ((int)(_square2.getX()+1))/20;
locs[2][0]= ((int)(_square3.getY()+1))/20;
locs[2][1]= ((int)(_square3.getX()+1))/20;
locs[3][0]= ((int)(_square4.getY()+1))/20;
locs[3][1]= ((int)(_square4.getX()+1))/20;
System.out.println(locs[0][0]+" "+locs[0][1]+" "+locs[1][0]+" "+locs[1][1]+" "+locs[2][0]+" "+locs[2][1]+ " "+locs[3][0]+" "+locs[3][1]);
return locs;}
public boolean contains(int x, int y)
{if(_square3.contains(x,y)||_square4.contains(x,y))
return true;
else
return false;}
public void fill(Graphics2D g2)
super.fill(g2);
g2.fill(_square1);
g2.fill(_square2);
g2.fill(_square3);
g2.fill(_square4);}
import java.awt.geom.*;
import java.awt.*;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.*;
public class TetrisPanel extends JPanel
{private Factory _pieceFact;
private Piece currentPiece;
private Timer _timer;
private int Interval =500;
private smallPiece [][] locationArray;
public TetrisPanel()
{setBackground(Color.white);
locationArray = new smallPiece[22][10];
_pieceFact = new Factory(locationArray);
currentPiece = _pieceFact.newPiece();
_timer = new Timer(Interval, new TimerListener());
_timer.start();
public void paintComponent(Graphics g)
{super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
currentPiece.fill(g2);
for(int row =0; row<22; row++)
for(int col =0; col<10; col++)
if(locationArray[row][col]!=null)
{locationArray[row][col].fill(g2);}}
public void createPiece()
{currentPiece =_pieceFact.newPiece();
repaint();}
public class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e)
if(currentPiece.moveOneStep()==true)
{repaint();
currentPiece.getLocs();}
else
{int[][]ar = currentPiece.getLocs();
for(int rows=0; rows<ar.length; rows++)
{locationArray[22-ar[rows][0]][10-ar[rows][1]] = new smallPiece(ar[rows][1]*20,ar[rows][0]*20, currentPiece.getColor());}
createPiece();
repaint();}
}the error
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 22
at TetrisPanel$TimerListener.actionPerformed(TetrisPanel.java:51)
at javax.swing.Timer.fireActionPerformed(Timer.java:271)
at javax.swing.Timer$DoPostEvent.run(Timer.java:201)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 22
at SquareShape.moveOneStep(SquareShape.java:38)
at TetrisPanel$TimerListener.actionPerformed(TetrisPanel.java:45)
at javax.swing.Timer.fireActionPerformed(Timer.java:271)
at javax.swing.Timer$DoPostEvent.run(Timer.java:201)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)Errors dont know what is wrong!You read the stack trace from the top down, looking out for the first line that refers to your code.
java.lang.ArrayIndexOutOfBoundsException: 22This means that you are using something as an array index (some variable, perhaps) and it has a value of 22, but the array itself is not that big.
at TetrisPanel$TimerListener.actionPerformed(TetrisPanel.java:51This tells you exactly where the bad array access is taking place. Only you know which line 51 is - and it's good form to tell the rest of us when you post - but, at a wild guess, I'd say it was that line within the for loop that assigns new values to the locationArray.
Use System.out.println() to check the values of the variables (or expressions) you use to access the array. Also check the length of the various arrays involved.
(If I were you, I'd consider using a bit more indentation in your code. Especially where constructs are nested.) -
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class ClickMe extends Applet implements MouseListener {
private Spot spot = null;
private static final int RADIUS = 7;
public void init() {
addMouseListener(this);
public void paint(Graphics g) {
//draw a black border and a white background
g.setColor(Color.white);
g.fillRect(0, 0, getSize().width - 1, getSize().height - 1);
g.setColor(Color.black);
g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
//draw the spot
g.setColor(Color.red);
if (spot != null) {
g.fillOval(spot.x - RADIUS, spot.y - RADIUS, RADIUS * 2, RADIUS * 2);
public void mousePressed(MouseEvent event) {
if (spot == null) {
spot = new Spot(RADIUS);
spot.x = event.getX();
spot.y = event.getY();
repaint();
public void mouseClicked(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
When I compile the the code I get a "cannot resolve symbol"
private Spot spot = null;
spot = new Spot(RADIUS);
I'm new to programming and I don't know if these are errors in the codeThe compiler doesn't know what "Spot" is. It isn't in any of the packages you imported (java.awt.*, etc), so I'm assuming it's another class you wrote. At compile time, the compiler must be able to find that class, so it's looking for a file named Spot.class in your CLASSPATH. I think you just have a simple classpath problem that all beginners run into. If you don't have a Spot class, then it's a different problem. Maybe you meant to declare the "spot" variable as a different thing?
-
Compile error in paint() method while trying to draw graphics
Hi ,
I am trying to draw two lines given the sceen coordinated through a mouse click. I am getting the following error
Pos.java:90: illegal start of expression
public void paint(Graphics g)
^
Pos.java:102: ';' expected
^
2 errors
My code is as follows:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
public class Pos extends Container {
//public void paint(Graphics);
public static void main(String args[]) {
Pos p = new Pos();
p.getPosition();
JButton bn = new JButton("Draw Line");
int posx=0;
int posy=0;
int i=0;
int x[] = new int[4];
int y[] = new int[4];
public void getPosition() {
JFrame frame = new JFrame("Mouse Position");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
/*MouseMotionListener mouseMotionListener = new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
public void mouseMoved(MouseEvent e) {
MouseListener mouseListener = new MouseListener(){
public void mouseEntered(MouseEvent evnt){
public void mouseExited(MouseEvent evnt){
public void mousePressed(MouseEvent evnt){
public void mouseReleased(MouseEvent evnt){
public void mouseClicked(MouseEvent evnt) {
showMousePos(evnt);
//mon.setText("("+MouseInfo.getPointerInfo().getLocation().x+","+
//MouseInfo.getPointerInfo().getLocation().y+")");
private void showMousePos(MouseEvent evnt) {
JLabel src = (JLabel)evnt.getComponent();
posx = MouseInfo.getPointerInfo().getLocation().x;
posy = MouseInfo.getPointerInfo().getLocation().y;
System.out.println("x-coordinate="+posx);
System.out.println("y-coordinate="+posy);
x=posx;
y[i]=posy;
i=i+1;
label.addMouseMotionListener(mouseMotionListener);
label.addMouseListener(mouseListener);
label.addActionListener(actionListener);
frame.add(label, BorderLayout.CENTER);
bn.setSize(10,10);
frame.add(bn, BorderLayout.NORTH);
frame.setSize(300, 300);
frame.setVisible(true);
ActionListener actionListener = new ActionListener(){
public void actionPerformed(ActionEvent ae)
Object o = ae.getSource();
if (o==button)
public void paint(Graphics g)
Graphics2D g2D = (Graphics2D)g;
//int p[]=new int[4];
g2D.setColor(Color.red);
//for (int j=0;j<2;j++)
//Point2D.Int p[j]= new Point2D.Int(x[j],y[j]);
//Line2D line = new Line2D.Int(p[0],p[1]);
g2D.drawline(x[0],y[0],x[1],y[1]);
i=0;
Please tell me what the mistake is.
lakkiThank you all for the sggestions. The error was exactly due to what you mentioned above. I fixed that by drawing the lines on another JPanel and it is working now.
But I have a bigger problem. How to make a JPanel transparent. I have to draw lines on a video. The panel for drawing lines is opaque and so I can draw lines only if I am able to see the video. setOpaque(false) does not seem to work. I am posting my code below. Please see if you can help me out.
import javax.media.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.lang.Math;
import javax.media.control.FramePositioningControl;
import javax.media.protocol.*;
import javax.swing.*;
class MPEGPlayer2 extends JFrame implements ActionListener,ControllerListener,ItemListener
Player player;
Component vc, cc;
boolean first = true, loop = false;
String currentDirectory;
int mediatime;
BufferedWriter out;
FileWriter fos;
String filename = "";
Object waitSync = new Object();
boolean stateTransitionOK = true;
JButton bn = new JButton("DrawLine");
MPEGPlayer2 (String title)
super (title);
addWindowListener(new WindowAdapter ()
public void windowClosing (WindowEvent e)
dispose ();
public void windowClosed (WindowEvent e)
if (player != null)
player.close ();
System.exit (0);
Menu m = new Menu ("File");
MenuItem mi = new MenuItem ("Open...");
mi.addActionListener (this);
m.add (mi);
m.addSeparator ();
CheckboxMenuItem cbmi = new CheckboxMenuItem ("Loop", false);
cbmi.addItemListener (this);
m.add (cbmi);
m.addSeparator ();
mi = new MenuItem ("Exit");
mi.addActionListener (this);
m.add (mi);
MenuBar mb = new MenuBar ();
mb.add (m);
setMenuBar (mb);
setSize (500, 500);
setVisible (true);
public void actionPerformed (ActionEvent ae)
FileDialog fd = new FileDialog (this, "Open File",FileDialog.LOAD);
fd.setDirectory (currentDirectory);
fd.show ();
if (fd.getFile () == null)
return;
currentDirectory = fd.getDirectory ();
try
player = Manager.createPlayer (new MediaLocator("file:" +fd.getDirectory () +fd.getFile ()));
filename = fd.getFile();
catch (Exception exe)
System.out.println(exe);
if (player == null)
System.out.println ("Trouble creating a player.");
return;
setTitle (fd.getFile ());
player.addControllerListener (this);
player.prefetch ();
}// end of action performed
public void controllerUpdate (ControllerEvent e)
if (e instanceof EndOfMediaEvent)
if (loop)
player.setMediaTime (new Time (0));
player.start ();
return;
if (e instanceof PrefetchCompleteEvent)
player.start ();
return;
if (e instanceof RealizeCompleteEvent)
vc = player.getVisualComponent ();
if (vc != null)
add (vc);
cc = player.getControlPanelComponent ();
if (cc != null)
add (cc, BorderLayout.SOUTH);
add(new MyPanel());
pack ();
public void itemStateChanged(ItemEvent ee)
public static void main (String [] args)
MPEGPlayer2 mp = new MPEGPlayer2 ("Media Player 2.0");
System.out.println("111111");
class MyPanel extends JPanel
int i=0,j;
public int xc[]= new int[100];
public int yc[]= new int[100];
int a,b,c,d;
public MyPanel()
setOpaque(false);
setBorder(BorderFactory.createLineBorder(Color.black));
JButton bn = new JButton("DrawLine");
this.add(bn);
bn.addActionListener(actionListener);
setBackground(Color.CYAN);
addMouseListener(new MouseAdapter()
public void mouseClicked(MouseEvent e)
saveCoordinates(e.getX(),e.getY());
ActionListener actionListener = new ActionListener()
public void actionPerformed(ActionEvent aae)
repaint();
public void saveCoordinates(int x, int y)
System.out.println("x-coordinate="+x);
System.out.println("y-coordinate="+y);
xc=x;
yc[i]=y;
System.out.println("i="+i);
i=i+1;
public Dimension getPreferredSize()
return new Dimension(500,500);
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2D = (Graphics2D)g;
//g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
g2D.setColor(Color.GREEN);
for (j=0;j<i;j=j+2)
g2D.drawLine(xc[j],yc[j],xc[j+1],yc[j+1]); -
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
Maybe you are looking for
-
How can you print a receipt from an i-tunes account purchase
how can you print a recieipt from an i-tunes purchase ?
-
How to save as AI file in same location with all text curves?
Hi Guys, I am also looking for a script. Here are the details.... I do have lot of AI files (from different paths), which are completly work done. So I just need to make them (all files) a copy with all text curves in the same path should create fo
-
Hi Guys! I'm using Oracle9ias 9.0.3. When I execute $opmnctl startall, I get the next error in all instances (<instance>.default_island.1): java.net.BindException: Address already in use at java.net.PlainSocketImpl.socketBind(Native Method) I have 3
-
I recently archived and installed OSX Leopard and pulled my accounts and apps back in. Now I notice there is an "Unknown" user account on the system and I can't delete it when running as admin. I am thinking of nuking and paving the hard drive with a
-
Difference between InDesign and Photoshop PDFs for printing?
Hi, rather new to the whole printing business, forgive me. I have both InDesign and Photoshop, but I am better versed in Photoshop. Is there a significant difference between the capabilities for saving a PDF for print between the two? Also, would som