Java Applet Adding and Removing labels - java

I am trying to make code that adds a label when I click and then removes the label when I press e. Can someone help me do this
I added the labels and I got it to compile but the label won't show up and its for my graphics project I worked on it really hard
import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import java.awt.Label;
public class Volcano_Client extends Applet implements MouseListener, KeyListener, Runnable
{
Label label1;
boolean pickE=false;
boolean play = true;
boolean makeLava=false;
Thread t;
Thread thr;
Thread th;
boolean mouseEntered;
int count;
Volcano v1;
public void init()
{
label1 = new Label("You see lava flowing down as you press e");
v1 = new Volcano();
thr=new Thread(this);
thr.start();
t=new Thread(this);
t.start();
th= new Thread(this);
count=0;
addMouseListener(this);
addKeyListener(this);
}
public void keyTyped(KeyEvent k)
{
}
public void keyReleased(KeyEvent k)
{
}
public void keyPressed(KeyEvent k)
{
if(k.getKeyCode() ==KeyEvent.VK_E)
{
pickE=true;
repaint();
k.consume();
}
}
public void mouseExited(MouseEvent me)
{
mouseEntered=false;
repaint();
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
mouseEntered=true;
repaint();
}
public void mouseClicked(MouseEvent me)
{
if(mouseEntered==true)
{
makeLava=true;
}
else
{
makeLava=false;
}
repaint();
}
public void run()
{
while(play==true)
{
try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
repaint();
}
while(true)
{
try{
Thread.sleep(20);
}
catch(Exception e){};
repaint();
}
}
public void stop()
{
}
public void start()
{
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
label1 = new Label("You see lava flowing down as you press e");
v1.makeVolcano(g2);
if(makeLava)
{
v1.makeLavaUp(g2);
g.setColor(Color.black);
g.drawString("KABOOM!!!",200,70);
add(label1);
}
else
{
g.setColor(Color.white);
g.drawString("Please Click For Eruption part 1",160,250);
}
if(pickE)
{
v1.makeLavaFlow(g2);
remove(label1);
}
else
{
//g.setColor(Color.white);
//g.drawString("Please press 'E' for Eruption part 2",160,276);
}
}
}

To display the label, below is modified init() function:
public void init()
`{`
`label1 = new Label("You see lava flowing down as you press e");`
//v1 = new Volcano();
thr=new Thread(this);
thr.start();
t=new Thread(this);
t.start();
th= new Thread(this);
count=0;
addMouseListener(this);
addKeyListener(this);
add(label1); //to display label
}

Related

In Java, why doesn't frame.repaint work in this code?

I'm not sure why the fr.repaint(); method isn't working here. If I use the set visible false, then set it true after making changes it makes the screen go black which isn't what I'm trying to do.
Any help?
This code is for a school project, so if it's possible please provide somewhat detailed explanation to understand.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
class Main {
static int startingposx;
static int startingposy;
static int endingposx;
static int endingposy;
public static void main(String[] args) {
JFrame fr = new JFrame();
fr.setBounds(10,10,512,512);
fr.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
fr.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
startingposx = e.getX();
startingposy = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
endingposx = e.getX();
endingposy = e.getY();
//fr.setVisible(false);// i tried to use this to refresh it but it makes the frame black for a second
JPanel x = new JPanel(){
#Override
public void paint(Graphics g){
g.setColor(Color.RED);
g.fillRect(startingposx-(32-15),startingposy-32,30,30);
g.setColor(Color.BLUE);
g.fillRect(endingposx-(32-15),endingposy-32,30,30);
}
};
fr.add(x);
fr.repaint();// why does this not work??
//fr.setVisible(true);
System.out.print("\033[H\033[2J");
System.out.println("starting pos: " + startingposx+ ","+ startingposy+"\n" + "ending pos: " + endingposx+ "," + endingposy);
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Frame made shorter in height purely to save space in answer
See further comments in the code. Note that the blue rectangle completely covers the red rectangle.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestCustomPaint {
// Don't use static! Make them instances of the x class and give it a constructor
static int startingposx;
static int startingposy;
static int endingposx;
static int endingposy;
public static void main(String[] args) {
JFrame fr = new JFrame();
// this is the wrong size if the content should be square
fr.setBounds(10,10,512,512);
// unused MouseMotionListener removed
fr.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) { }
#Override
public void mousePressed(MouseEvent e) {
startingposx = e.getX();
startingposy = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
endingposx = e.getX();
endingposy = e.getY();
fr.repaint();
System.out.print("\033[H\033[2J");
System.out.println("starting pos: " + startingposx+ ","+ startingposy+"\n" +
"ending pos: " + endingposx+ "," + endingposy);
}
#Override
public void mouseEntered(MouseEvent e) { }
#Override
public void mouseExited(MouseEvent e) { }
});
// This is when the panel should be created and added.
JPanel x = new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(startingposx-(32-15),startingposy-32,30,30);
g.setColor(Color.BLUE);
g.fillRect(endingposx-(32-15),endingposy-32,30,30);
}
};
fr.add(x);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

How do I move an object using Keyboard Control? [duplicate]

I have written a sample code using KeyListener in Java,
I have created a JPanel, then set its focusable to true, I have created a KeyListener, requested a focus and then added the KeyListener to my panel. But the methods for the keyListener are never called. It seems although I have requested focus, it does not focus.
Can anyone help?
listener = new KeyLis();
this.setFocusable(true);
this.requestFocus();
this.addKeyListener(listener);
class KeyLis implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
currentver += 5;
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : if(horizontalyInBounds()) currentPos-= 5;
break;
case KeyEvent.VK_RIGHT: if(horizontalyInBounds()) currentPos+= 5;
break;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
}
}
If any runnable code should be needed:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class test extends JFrame {
private AreaOfGame areaOfGame;
public test()
{
super("");
setVisible(true);
this.setBackground(Color.darkGray);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
setLayout(null);
setBounds(200, 10, 400, 700);
areaOfGame = new AreaOfGame();
this.add(areaOfGame);
startGame();
}
public int generateNext()
{
Random r = new Random();
int n = r.nextInt(7);
return n;
}
public void startGame()
{
while(!areaOfGame.GameOver())
{
areaOfGame.startGame(generateNext());
}
}
public static void main(String[] args) {
new MainFrame();
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JPanel;
public class AreaOfGame extends JPanel {
private static final int rightside = 370;
private int bottom;
private int top;
private int currentPos;
private int currentver;
private KeyLis listener;
public AreaOfGame()
{
super();
bottom = 650;
top = 50;
setLayout(null);
setBounds(20, 50, 350, 600);
setVisible(true);
this.setBackground(Color.lightGray);
listener = new KeyLis();
this.setFocusable(true);
if(this.requestFocus(true))
System.out.println("true");;
this.addKeyListener(listener);
currentPos = 150;
currentver=0;
}
public void startGame(int n)
{
while(verticallyInBound()){
System.out.println("anything");
}
}
public boolean verticallyInBound()
{
if(currentPos<= bottom -50)
return true;
return false;
}
public boolean GameOver()
{
if(top>= bottom){
System.out.println("game over");
return true;
}
else return false;
}
public boolean horizontalyInBounds()
{
if(currentPos<=rightside && currentPos>= 20)
return true;
else return false;
}
class KeyLis implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
System.out.println("called");
currentver += 5;
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : if(horizontalyInBounds()) currentPos-= 5; break;
case KeyEvent.VK_RIGHT: if(horizontalyInBounds()) currentPos+= 5; break;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("called 3");
}
}
}
I'll bet that you're requesting focus before the JPanel has been rendered (before the top level window has either had pack() or setVisible(true) called), and if so, this won't work. Focus request will only be possibly granted after components have been rendered. Have you checked what your call to requestFocus() has returned? It must return true for your call to have any chance for a success. Also it's better to use requestFocusInWindow() rather than requestFocus().
But more importantly, you shouldn't be using KeyListeners for this but rather key bindings, a higher level concept that Swing itself uses to respond to key presses.
Edit
An example of an SSCCE:
import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.*;
public class TestKeyListener extends JPanel {
private KeyLis listener;
public TestKeyListener() {
add(new JButton("Foo")); // something to draw off focus
listener = new KeyLis();
this.setFocusable(true);
this.requestFocus();
this.addKeyListener(listener);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
private class KeyLis extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
System.out.println("VK_LEFT pressed");
break;
case KeyEvent.VK_RIGHT:
System.out.println("VK_RIGHT pressed");
break;
}
}
}
private static void createAndShowGui() {
TestKeyListener mainPanel = new TestKeyListener();
JFrame frame = new JFrame("TestKeyListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit 2
And the equivalent SSCCE using Key Bindings:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestKeyBindings extends JPanel {
public TestKeyBindings() {
add(new JButton("Foo")); // something to draw off focus
setKeyBindings();
}
private void setKeyBindings() {
ActionMap actionMap = getActionMap();
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = getInputMap(condition );
String vkLeft = "VK_LEFT";
String vkRight = "VK_RIGHT";
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), vkLeft);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), vkRight);
actionMap.put(vkLeft, new KeyAction(vkLeft));
actionMap.put(vkRight, new KeyAction(vkRight));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
private class KeyAction extends AbstractAction {
public KeyAction(String actionCommand) {
putValue(ACTION_COMMAND_KEY, actionCommand);
}
#Override
public void actionPerformed(ActionEvent actionEvt) {
System.out.println(actionEvt.getActionCommand() + " pressed");
}
}
private static void createAndShowGui() {
TestKeyBindings mainPanel = new TestKeyBindings();
JFrame frame = new JFrame("TestKeyListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit 3
Regarding your recent SSCCE, your while (true) loops are blocking your Swing event thread and may prevent user interaction or painting from happening. Better to use a Swing Timer rather than while (true). For example:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class BbbTest extends JFrame {
private AreaOfGame areaOfGame;
public BbbTest() {
super("");
// setVisible(true);
this.setBackground(Color.darkGray);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
setLayout(null);
setBounds(200, 10, 400, 700);
areaOfGame = new AreaOfGame();
this.add(areaOfGame);
setVisible(true);
startGame();
}
public int generateNext() {
Random r = new Random();
int n = r.nextInt(7);
return n;
}
public void startGame() {
// while (!areaOfGame.GameOver()) {
// areaOfGame.startGame(generateNext());
// }
areaOfGame.startGame(generateNext());
}
public static void main(String[] args) {
new BbbTest();
}
class AreaOfGame extends JPanel {
private static final int rightside = 370;
private int bottom;
private int top;
private int currentPos;
private int currentver;
private KeyLis listener;
public AreaOfGame() {
super();
bottom = 650;
top = 50;
setLayout(null);
setBounds(20, 50, 350, 600);
setVisible(true);
this.setBackground(Color.lightGray);
listener = new KeyLis();
this.setFocusable(true);
if (this.requestFocus(true))
System.out.println("true");
;
this.addKeyListener(listener);
currentPos = 150;
currentver = 0;
}
public void startGame(int n) {
// while (verticallyInBound()) {
// System.out.println("anything");
// }
int timeDelay = 50; // msecs delay
new Timer(timeDelay , new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("anything");
}
}).start();
}
public boolean verticallyInBound() {
if (currentPos <= bottom - 50)
return true;
return false;
}
public boolean GameOver() {
if (top >= bottom) {
System.out.println("game over");
return true;
}
else
return false;
}
public boolean horizontalyInBounds() {
if (currentPos <= rightside && currentPos >= 20)
return true;
else
return false;
}
class KeyLis implements KeyListener {
#Override
public void keyPressed(KeyEvent e) {
System.out.println("called");
currentver += 5;
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if (horizontalyInBounds())
currentPos -= 5;
break;
case KeyEvent.VK_RIGHT:
if (horizontalyInBounds())
currentPos += 5;
break;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("called 3");
}
}
}
}
It's possible to use the "TAB" button to switch between the buttons and the key listener.
I have a program with one button that after I press it, the key listener does not work.
I realized that if you press the "TAB" button, the "Attention" or "focus" of the program returns to the key listener.
maybe this will help: http://docstore.mik.ua/orelly/java-ent/jfc/ch03_08.htm

Adding a keylistener to main() not working

I'm making a game in Java where a ball moves forward constantly with no user control, but the user can control the vertical movement of the ball, using the up and down arrow keys, however I'm stuck on adding the keylistener class/whatever it is to my JFrame, through my main method. Basically, I do add(keylistener_class/method), and Java (quite rightly), complains that my class or method is not a component. My question, then, is how AM I supposed to add the keylistener into my Jframe?
Cheers,
Matt
Code:
package org.ultraluminous.vertiball;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JPanel{
static int x = 0;
static int y = 0;
static int ys = 0;
private static void shift(){
x+=1;
y+=ys;
}
public static void event(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP){
ys = 1;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN){
ys = -1;
}
}
public class key{
public void Listen() {
KeyListener listener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
};
addKeyListener(listener);
setFocusable(true);
}
}
#Override
public void paint(Graphics g){
super.paint(g);
Graphics2D Graph = (Graphics2D) g;
Graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Graph.setColor(Color.BLUE);
Graph.drawOval(x, y, 50, 50);
Graph.fillOval(x, y, 50, 50);
}
public static void main (String[] args){
JFrame Win = new JFrame("Pong");
Game game = new Game();
Win.add(new Game());
//Win.add... add what? I need to add the key listener here
//but seem to be unable to.
Win.setResizable(false);
Win.setSize(900, 600);
Win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Win.setVisible(true);
while (true) {
shift();
Win.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
I got it to work by adding the KeyListener to your JFrame. Alternatively you could create a separate class for the KeyListener and add it that way (instead of using an anonymous inner class). Here is what I added:
public static void main (String[] args){
JFrame Win = new JFrame("Pong");
Game game = new Game();
Win.add(new Game());
Win.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
ys = -1;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN){
ys = 1;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Win.setResizable(false);
Win.setSize(900, 600);
Win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Win.setVisible(true);
while (true) {
shift();
Win.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
You can add KeyListener to your JPanel by this way:
addKeyListener(new KeyListener(){
...//all the methods.
});
Alternatively, you can use KeyAdpater, if do not use all the methods.
addKeyListener(new KeyAdapter(){
...//Only the methods you want.
});

Java mouseevent error - "method already defined in class"

I am trying to implement a click and drag method, for which I need mousePressed and mouseReleased events. I will also be using mouseClicked events, so I implemented MouseMotionListener and MouseListener.
However, when I go to write mousePressed, mouseReleased, mouseEntered, mouseExited methods I get the following error:
method mousePressed(MouseEvent) is already defined in class BoingPanel
Here is the entire class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JPanel;
public class BoingPanel extends JPanel implements MouseMotionListener, MouseListener {
private int width;
private int height;
private int updateRate=40;
ArrayList<Ball> balls;
ArrayList<Line> lines;
private Container box;
private boolean drag = false;
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public BoingPanel()
{
balls = new ArrayList<Ball>();
balls.add(new Ball(100,0)); // adds test ball
balls.get(0).setXVelocity(5);
balls.add(new Ball(100,0));
balls.add(new Ball(400,50));
lines = new ArrayList<Line>();
lines.add(new Line(0, height, width, height));
gameStart();
}
public BoingPanel(int x, int y)
{
width=x;
height=y;
balls = new ArrayList<Ball>();
balls.add(new Ball(100,0)); // adds test ball
balls.get(0).setXVelocity(5);
balls.add(new Ball(100,0));
balls.add(new Ball(400,50));
lines = new ArrayList<Line>();
box = new Container(width, height);
gameStart();
}
#Override
public void mouseDragged(MouseEvent me) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public void gameStart() {
// Run the game logic in its own thread.
Thread gameThread = new Thread() {
public void run() {
while (true) {
// Execute one time-step for the game
update();
// Refresh the display
repaint();
// Delay and give other thread a chance
try {
Thread.sleep(1000 /updateRate);
} catch (InterruptedException ex) {}
}
}
};
gameThread.start(); // Invoke GaemThread.run()
}
private void update()
{
for(Ball a:balls) //calls balls updated position
{
a.update(box);
}
}
public void paintComponent(Graphics g)
{
box.paint(g);
for(Ball a:balls) //calls balls updated position
{
a.paint(g);
}
for(Line b:lines) //draws lines
{
b.paint(g);
}
}
public void actionPerformed(ActionEvent e)
{
update(); //changes ball position
repaint(); //refreshes image
}
}
What is causing this error? Thanks!
I would suggest this, just below your variable declarations and before you constructor, isn't helping...
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
You've basically implemented these methods twice. Just before and after the constructor.
Simply remove on of these groups of declarations...
please remove public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { } and then try

Clear painted screen at each click of the mouse?

Can't seem to figure out how to only show one circle. Was trying to //g.clearRect(0, 0, 400, 400); but that clears the background too. Was also trying to just fill the background with yellow again but couldn't get that working either. Any suggestions?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JMouseFrame extends JFrame
implements MouseListener {
Container con = null;
int x, y;
int size;
public JMouseFrame() {
setTitle("JMouseFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
con = this.getContentPane();
addMouseListener(this);
}
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseClicked(MouseEvent e) {
int whichButton = e.getButton();
if (whichButton == MouseEvent.BUTTON1) {
size = 15;
} else if (whichButton == MouseEvent.BUTTON3) {
size = 4;
}
repaint();
}
public void mouseEntered(MouseEvent e) {
con.setBackground(Color.yellow);
}
public void mouseExited(MouseEvent e) {
con.setBackground(Color.black);
}
public void paint(Graphics g) {
//g.clearRect(0, 0, 400, 400);
g.drawOval(x - size, y - size, size * 3, size * 3);
}
public static void main(String[] args) {
JMouseFrame mFrame = new JMouseFrame();
mFrame.setSize(400, 400);
mFrame.setVisible(true);
}
public void mouseReleased(MouseEvent e) {
}
}
It looks like you're mixing AWT and Swing painting. Instead, override paintComponent(), as suggested in the example below. See Painting in AWT and Swing for details.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/questions/3898775 */
public class MousePanel extends JPanel {
private static final int SIZE = 20;
Point p = new Point(Short.MAX_VALUE, Short.MAX_VALUE);
public MousePanel() {
this.setPreferredSize(new Dimension(400, 400));
this.setBackground(Color.yellow);
this.addMouseListener(new MouseHandler());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawOval(p.x - SIZE, p.y - SIZE, SIZE * 2, SIZE * 2);
}
private final class MouseHandler extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
p = e.getPoint();
repaint();
}
}
private void display() {
JFrame f = new JFrame("MousePanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MousePanel().display();
}
});
}
}
Addendum:
I can't figure out how to make the code you posted work with what I have...
You can restore your mouse methods to the MouseHandler almost verbatim. The only difference is the need to qualify this, e.g.
#Override
public void mouseClicked(MouseEvent e) {
int whichButton = e.getButton();
if (whichButton == MouseEvent.BUTTON1) {
MousePanel.this.size = 15;
} else if (whichButton == MouseEvent.BUTTON3) {
MousePanel.this.size = 4;
}
repaint();
}
#Override
public void mouseEntered(MouseEvent e) {
MousePanel.this.setBackground(Color.yellow);
}
#Override
public void mouseExited(MouseEvent e) {
MousePanel.this.setBackground(Color.black);
}

Categories

Resources