I have a simple applet that I want to run locally yet java is blocking it.
The applet code is as such:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FollowMe extends JApplet
{
private int xCoord = 100, yCoord = 100;
/**
* init method
*/
public void init()
{
setBackground(Color.WHITE);
addMouseMotionListener(new MyMouseMotionListener());
}
/**
* paint method
*/
public void paint(Graphics g)
{
// Call the base class paint method.
super.paint(g);
// Draw the string at the current mouse location.
g.drawString("Hello", xCoord, yCoord);
}
/**
* Private inner class that handles mouse
* motion events.
*/
private class MyMouseMotionListener implements MouseMotionListener
{
/**
* mouseMoved method
*/
public void mouseMoved(MouseEvent e)
{
// Get the mouse pointer's X and Y coordinates.
xCoord = e.getX();
yCoord = e.getY();
// Force the paint method to execute.
repaint();
}
/**
* Unused mouseDragged method
*/
public void mouseDragged(MouseEvent e)
{
}
}
}
And of course I reference the class file in my HTML file.
I have gone to my JAVA security settings and added the following exception:
"file:///D:/Downloads/AppletsExamples%281%29/01%20-%20FollowMe%20Applet/FollowMe.html"
which as you can see is the path I open in firefox to access my Html file.
However, JAVA still blocks the applet. This is getting so frustrating and I couldn't find any help elsewhere.
Related
public class DrawST extends javax.swing.JFrame {
/**
* Creates new form DrawST
*/
public DrawST() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
Generated code
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DrawST().setVisible(true);
}
});
}
class Class01 extends JPanel{
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
class Class02 extends JPanel{
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
}
}
// Variables declaration - do not modify
// End of variables declaration
}
How can I use both Class01 and Class02 to paint in this JFrame, Class01 will draw pipes, and Class02 will draw frog(Happy Frog). I try to create Container contain = getContentPane(); and add two classes. But it work only 1 class added.If I add two classes, the JFrame won't draw anything.
You're making a common mistake: creating drawing classes that extend Swing components when they should be logical classes, not component classes:
If you're doing animation, usually only one component, often a JPanel does the drawing, meaning the paintComponent method is overridden in one component.
If you desire a class to draw a specific sprite, such as a frog, or pipes, then these sprites will be drawn in that same single drawing class described above.
Component classes, classes that extend Swing GUI components such as JPanels are usually placed into the GUI as components -- building blocks of the GUI that are placed in a limited location in the GUI, and that paint themselves and their children only.
So to do drawings where multiple sprites occupy the same drawing space, the classes that create these sprites should not extend JPanel or similar Swing components and instead should only be logical classes (classes that are not components), and then that are drawn by that single drawing JPanel.
For example
public class DrawST extends javax.swing.JFrame {
public DrawST() {
// add the DrawingPanel to the JFrame here
}
}
// this class extends JPanel and does *all* the drawing
public class DrawingPanel extends JPanel {
private Frog frog = new Frog(0, 0);
private List<Pipe> pipes = new ArrayList<>();
private Timer timer; // you'll probably need a Swing Timer to drive the animation
// a single paintComponent method is present
protected void paintComponent(Graphics g) {
super.paintComponent(g); // Don't forget this
frog.draw(g); // have this component draw a frog
for (Pipe pipe : pipes) {
pipe.draw(g); // draw all the pipes
}
}
}
// does not extend JPanel
public class Frog {
private int x;
private int y;
public Frog(int x, int y) {
this.x = x;
this.y = y;
}
public void draw(Graphics g) {
// use x, y, and g to draw a frog at x,y location
}
}
// does not extend JPanel (not sure what a pipe is, TBH)
public class Pipe {
private int x;
private int y;
// other? length, color, width?
public void draw(Graphics g) {
// use x, y, and g to draw a pipe.
// maybe also needs a length, color, width?
}
}
I have a downloaded java source code of the popular "Connect 6" game. In the user interface classes it uses "UI" in many occasions while there is no class or imported library related. I want to know the reason for that. (Link for the code : http://kevinverhoef.nl/connect6.htm)
package userinterface;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import logic.Stone;
/**
* A graphical representation of the board.
* It also handels the mouse clicks on the board for placing human player stones.
*/
public class BoardObject extends JLabel implements MouseListener {
private static final long serialVersionUID = 1L;
UI applet;
/**
* Constructor
*/
public BoardObject(UI applet) {
Icon c = new ImageIcon(getClass().getResource("field.GIF"));
this.setIcon(c);
this.setBounds(0, 0, 650, 672);
this.addMouseListener(this);
this.applet = applet;
}
/**
* Handles the mouse clicks for placing stone.
*/
public void mouseClicked(MouseEvent e) {
// Offset from the board image.
int topOffset = 16;
int leftOffset = 26;
// determine positions on the field
int x = (int) Math.floor((e.getX() - leftOffset) / 32);
int y = (int) Math.floor((e.getY() - topOffset) / 32);
if (x < 19 && y < 19) {
// Voeg toe aan bord
Stone newStone = new Stone(x, y, applet.controller.playingColor);
// Probeer te plaatsen
if (newStone.place(applet.board)) {
newStone.stoneNr = applet.controller.getNextStoneNr();
applet.drawStones();
applet.controller.addStone(newStone);
if (applet.inputEnabled) {
// Check to see next step
if (applet.controller.firstStone) {
applet.step();
}
}
}
}
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
}
Despite UI.java is not present in the sources, if you look inside the .jar file, you'll find UI.class in the same package (.jar file can be opened by any .zip archiver). If you are interested in UI.class content use javap tool or the latest vesion of Intellij Idea to decompile it.
If UI is in the same package as the class using it, it doesn't need to be explicitly imported.
Trying to do a mouse event assignment. The idea is that when the user clicks the mouse the program draws a small green dot, when the mouse is released it should create a small orange dot 5 pixels down and 5 pixels right of it. The assigment requires the three programs, Dots, DotsPanel, and DrawDots. The program should also have a counter of total dots. Right now the programs compile, but the program completely breaks and gives me tons of errors when I try to run it. I'm a bit lost right now as I'm new to this GUI and user mouseEvents. Thank you! I specifically have trouble of how to get past the casting the Dots class as a Point.
Here is a copy of the instructions:
Modify the “Dots” example. Include a Dots class that contains a constructor to initialize the color and point location of the dot. The Dots class should also include two accessor methods. The ArrayList will now contain a list of the dots to draw instead of points. When the mouse is pressed, the program draws a green circle (as in the original design). When the mouse is released, the program draws a yellow circle translated 5 pixels right and 5 pixels down from the released location. Be sure to keep track of the total number of dots. You should have three files: Dots, DotsPanel, DrawDots. (10 points)
/**
* #(#)Dots.java
*
*
* #author
* #version 1.00 2015/5/16
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Dots
{
Point p;
Color col;
public Dots(Color c, Point x)
{
p=x;
col=c;
}
public Point getPointP()
{
return p.getLocation();
}
public Color getPointC()
{
return col;
}
}
....
//represents the primary panel for the Dots program on which the
//dots are drawn
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class DotsPanel extends JPanel
{
private final int WIDTH = 300, HEIGHT = 300;
private final int RADIUS = 6;
private ArrayList<Dots> pointList;
private int count;
//Sets up this panel to listen for mouse events.
public DotsPanel()
{
pointList = new ArrayList<Dots>();
count = 0;
addMouseListener(new DotsListener());
setBackground(Color.black);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
}
//Draws all of the dots stored in the list
public void paintComponent(Graphics page)
{
super.paintComponent(page);
//Retrieve an iterator for the ArrayList of points
Iterator pointIterator = pointList.iterator();
while(pointIterator.hasNext())
{
page.setColor(Color.green);
Point drawPoint = (Point) pointIterator.next();
page.fillOval(drawPoint.x - RADIUS, drawPoint.y - RADIUS,
RADIUS * 2, RADIUS * 2);
page.setColor(Color.yellow);
Point drawPoint2 = (Point) pointIterator.next();
page.fillOval(drawPoint2.x - RADIUS+5, drawPoint2.y - RADIUS+5,
RADIUS * 2, RADIUS * 2);
}
page.drawString("Count: " + count, 5, 15);
}
//represents the lister for mouse events
private class DotsListener implements MouseListener
{
//Adds the current point to the list of points and redraws
//whenever the mouse button is pressed
public void mousePressed(MouseEvent event)
{
Dots dot1 = new Dots(Color.GREEN, event.getPoint());
pointList.add(dot1);
count++;
repaint();
}
public void mouseReleased(MouseEvent event)
{
Dots dot2 = new Dots(Color.YELLOW, event.getPoint());
pointList.add(dot2);
count++;
repaint();
}
//Provide empty definitions for unused event methods
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
}
.....
//demonstrates mouse events and drawing on a panel
import javax.swing.*;
public class DrawDots
{
//Creates and displays the application frame
public static void main(String[] args)
{
JFrame dotsFrame = new JFrame("Dots");
dotsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dotsFrame.getContentPane().add(new DotsPanel());
dotsFrame.pack();
dotsFrame.setVisible(true);
}
}
First you should use Iterator<Dots> pointIterator = pointList.iterator();. This helps the compiler to warn you in case of uncastable types (this is the first error you got). In your paintComponent method you should use Point drawPoint = pointIterator.next().getPointP(); and Point drawPoint2 = pointIterator.next().getPointP(); a view lines later.After that modifications the program runs (at least on my machine).
I have these 3 classes which is supposed to work together to create a game. But I'm getting an error in one of them where it wants me to add unimplemented methods. The class which is creating the error is called Game and looks like this.
package org.game.main;
import java.awt.Graphics2D;
public class Game extends Window {
public static void main(String[] args) {
Window window = new Game();
window.run(1.0 / 60.0);
System.exit(0);
}
public Game() {
// call game constructor
super("Test Game", 640, 480);
}
public void gameStartup() {
}
public void gameUpdate(double delta) {
}
public void gameDraw(Graphics2D g) {
}
public void gameShutdown() {
}
}
It wants me to implement the method called Update() from the Window class. The Window class looks like this.
package org.game.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import org.game.input.*;
/**
* Game that creates a window and handles input.
* #author Eric
*/
public abstract class Window extends GameLoop {
private Frame frame;
private Canvas canvas;
private BufferStrategy buffer;
private Keyboard keyboard;
private Mouse mouse;
private MouseWheel mouseWheel;
/**
* Creates a new game window.
*
* #param title title of the window.
* #param width width of the window.
* #param height height of the window.
*/
public Window(String title, int width, int height) {
/*Log.debug("Game", "Creating game " +
title + " (" + width + ", " + height + ")");*/
// create frame and canvas
frame = new Frame(title);
frame.setResizable(false);
canvas = new Canvas();
canvas.setIgnoreRepaint(true);
frame.add(canvas);
// resize canvas and make the window visible
canvas.setSize(width, height);
frame.pack();
frame.setVisible(true);
// create buffer strategy
canvas.createBufferStrategy(2);
buffer = canvas.getBufferStrategy();
// create our input classess and add them to the canvas
keyboard = new Keyboard();
mouse = new Mouse();
mouseWheel = new MouseWheel();
canvas.addKeyListener(keyboard);
canvas.addMouseListener(mouse);
canvas.addMouseMotionListener(mouse);
canvas.addMouseWheelListener(mouseWheel);
canvas.requestFocus();
}
/**
* Get the width of the window.
*
* #return the width of the window.
*/
public int getWidth()
{
return canvas.getWidth();
}
/**
* Get the height of the window.
*
* #return the height of the window.
*/
public int getHeight()
{
return canvas.getHeight();
}
/**
* Returns the title of the window.
*
* #return the title of the window.
*/
public String getTitle()
{
return frame.getTitle();
}
/**
* Returns the keyboard input manager.
* #return the keyboard.
*/
public Keyboard getKeyboard()
{
return keyboard;
}
/**
* Returns the mouse input manager.
* #return the mouse.
*/
public Mouse getMouse()
{
return mouse;
}
/**
* Returns the mouse wheel input manager.
* #return the mouse wheel.
*/
public MouseWheel getMouseWheel() {
return mouseWheel;
}
/**
* Calls gameStartup()
*/
public void startup() {
gameStartup();
}
/**
* Updates the input classes then calls gameUpdate(double).
* #param delta time difference between the last two updates.
*/
public void update(double delta) {
// call the input updates first
keyboard.update();
mouse.update();
mouseWheel.update();
// call the abstract update
gameUpdate(delta);
}
/**
* Calls gameDraw(Graphics2D) using the current Graphics2D.
*/
public void draw() {
// get the current graphics object
Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
// clear the window
g.setColor(Color.BLACK);
g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
// send the graphics object to gameDraw() for our main drawing
gameDraw(g);
// show our changes on the canvas
buffer.show();
// release the graphics resources
g.dispose();
}
/**
* Calls gameShutdown()
*/
public void shutdown() {
gameShutdown();
}
public abstract void gameStartup();
public abstract void gameUpdate(double delta);
public abstract void gameDraw(Graphics2D g);
public abstract void gameShutdown();
}
The last class is called Gameloop and looks like this.
package org.game.main;
public abstract class GameLoop {
private boolean runFlag = false;
/**
* Begin the game loop
* #param delta time between logic updates (in seconds)
*/
public void run (double delta) {
runFlag = true;
startup();
// convert the time to seconds
double nextTime = (double) System.nanoTime() / 1000000000.0;
double maxTimeDiff = 0.5;
int skippedFrames = 1;
int maxSkippedFrames = 5;
while (runFlag) {
// convert the time to seconds
double currTime = (double) System.nanoTime() / 1000000000.0;
if ((currTime - nextTime) > maxTimeDiff) nextTime = currTime;
if (currTime >= nextTime) {
// assign the time for the next update
nextTime += delta;
update();
if ((currTime < nextTime) || (skippedFrames > maxSkippedFrames)) {
draw();
skippedFrames = 1;
}
else {
skippedFrames++;
}
} else {
// calculate the time to sleep
int sleepTime = (int)(1000.0 * (nextTime - currTime));
// sanity check
if (sleepTime > 0) {
// sleep until the next update
try {
Thread.sleep(sleepTime);
}
catch(InterruptedException e) {
// do nothing
}
}
}
}
shutdown();
}
public void stop() {
runFlag = false;
}
public abstract void startup();
public abstract void shutdown();
public abstract void update();
public abstract void draw();
}
The error I'm getting in console when I run the main class looks like this.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The type Game must implement the inherited abstract method GameLoop.update()
at org.game.main.Game.update(Game.java:5)
at org.game.main.GameLoop.run(GameLoop.java:26)
at org.game.main.Game.main(Game.java:8)
I hope you can help me. I'm quite new to java.
The signature of the update method is not overriding the interface, if that's what you intended.
public void update(double delta)
You need it to match the interface
public abstract void update();
So it sounds like this simple change should help:
public abstract void update(double delta);
In GameLoop you have defined
public abstract void update();
This method must be implemented in one of the sub classes Window or Game with the same signature.
You have implement unimplemented methods of Game Window and GameLoop class
Implement abstract methods. Window class' abstract methods are following:
public abstract void gameStartup();
public abstract void gameUpdate(double delta);
public abstract void gameDraw(Graphics2D g);
public abstract void gameShutdown();
Also implement following methods of GameLoop class
public abstract void startup();
public abstract void shutdown();
public abstract void update();
public abstract void draw();
Okay i found it out with some of the help that you suggested. It was because I hadn't defined Update() in GameLoop as.
public abstract void update(double delta);
Insted of
public abstract void update();
So the method didn't get called in Window. So then it had to be called in Game. Thanks for the help, everything works as should now.
This program is about creating components and moving them randomly in JApplet and removing the components if required. Every mouse click creates a new component. After creating component we can click on it and drag it where ever we want. Double clicking on the component removes it. I was successful in creating, moving and removing components.
For example i created three components on the JApplet by clicking three times randomly at different places on the JApplet.Please click here to view created components I moved them randomly around the screen. Please click here to view JApplet after randomly moving them around screen My goal is to write the final coordinates(x,y) of their position on the screen for all components created in to a text file by clicking a write button. I have no idea about mouseReleased method. Please help me with this. Thank you. Your help is very much appreciated.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.geom.*;
import javax.swing.*;
This is my main class
public class MouseTest extends JApplet
{
public void init()
{
EventQueue.invokeLater(new Runnable() {
public void run()
{
MousePanel panel = new MousePanel();
add(panel);
}
});
}
public static void main(String[] args)
{
EventQueue.invokeLater(new mainThread());
}
}
class mainThread implements Runnable
{
public void run()
{
JPanel panel = new MousePanel();
JFrame frame = new JFrame("MouseTest");
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
frame.setVisible(true);
}
}
class MousePanel extends JPanel
{
public MousePanel()
{
squares = new ArrayList<Rectangle2D>();
current = null;
addMouseListener(new MouseHandler());
addMouseMotionListener(new MouseMotionHandler());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// draw all squares
for (Rectangle2D r : squares)
g2.draw(r);
}
/**
* Finds the first square containing a point.
* #param p a point
* #return the first square that contains p
*/
public Rectangle2D find(Point2D p)
{
for (Rectangle2D r : squares)
{
if (r.contains(p)) return r;
}
return null;
}
/**
* Adds a square to the collection.
* #param p the center of the square
*/
public void add(Point2D p)
{
double x = p.getX();
double y = p.getY();
current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH,
SIDELENGTH);
squares.add(current);
repaint();
}
/**
* Removes a square from the collection.
* #param s the square to remove
*/
public void remove(Rectangle2D s)
{
if (s == null) return;
if (s == current) current = null;
squares.remove(s);
repaint();
}
private static final int SIDELENGTH = 10;
private ArrayList<Rectangle2D> squares;
private Rectangle2D current;
// the square containing the mouse cursor
these are methods for defining and dragging and removing the object
private class MouseHandler extends MouseAdapter
{
public void mousePressed(MouseEvent event)
{
// add a new square if the cursor isn't inside a square
current = find(event.getPoint());
if (current == null) add(event.getPoint());
}
public void mouseClicked(MouseEvent event)
{
// remove the current square if double clicked
current = find(event.getPoint());
if (current != null && event.getClickCount() >= 2) remove(current);
}
}
private class MouseMotionHandler implements MouseMotionListener
{
public void mouseMoved(MouseEvent event)
{
// set the mouse cursor to cross hairs if it is inside
// a rectangle
if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor());
else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
public void mouseDragged(MouseEvent event)
{
if (current != null)
{
int x = event.getX();
int y = event.getY();
// drag the current rectangle to center it at (x, y)
current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
repaint();
}
}
}
}
Why do you keep changing the requirement???? See original question: How to find final coordinates(x & y) of the objects position in JApplet and write them to a text file
First you wanted to write out the location of the moved component after the drag was finished.
Then you wanted to write out the location of "all" components after the drag was finished.
Now you want to write out the location of all the components after a "button" is clicked.
I have no idea about mouseReleased method.
What does this have to do with anything? That was the suggestion for your requirement in your last question. Since your requirement has changed it is no longer needed.
My goal is to write the final coordinates(x,y) of their position on the screen for all components created in to a text file by clicking a write button.
Then you need to add an ActionListener to the button. You have already been given a link to the Swing tutorial on How to Write an ActionListener so I guess the question is what code should be included in the ActionListener?
In you last question you stated:
I know how to get the location of a component
I know how to write data to a file
So the only remaining problem is how to get all the components on the panel? To do this you can use the Container.getComponents() method on your panel containing all the dragged components. The basic code for your ActionListener would be something like:
for (Component component: panel.getComponents())
{
Point location = component.getLocation();
// write the location to the file
}
I'll let you add the code for opening/closing the file.