Cannot find symbol error. java - java

I am running the following code and i am getting a cannot find symbol error at resultPane.setResult(0); am i putting the new handlerclass in wrong spot? ive tried putting
it in different spots but nothing
public class MovingLabel {
public static void main(String[] args) {
new MovingLabel();
}
public MovingLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
ResultPane resultPane = new ResultPane();
JFrame frame = new JFrame("Testing");
frame.setGlassPane(resultPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new NewPane(resultPane));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setBounds(500,300,200,200);
}
});
}
public class ResultPane extends JPanel {
private JLabel result;
private Timer timer;
private int xDelta = (Math.random() > 0.5) ? 1 : -1;
private int yDelta = (Math.random() > 0.5) ? 1 : -1;
public ResultPane() {
setOpaque(false);
setLayout(null);
result = new JLabel();
Font font = result.getFont();
font = font.deriveFont(Font.BOLD, 26f);
result.setFont(font);
add(result);
HandlerClass handler = new HandlerClass();
result.addMouseListener(handler);
result.addMouseMotionListener(handler);
timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Point point = result.getLocation();
point.x += xDelta;
point.y += yDelta;
if (point.x < 0) {
point.x = 0;
xDelta *= -1;
} else if (point.x + result.getWidth() > getWidth()) {
point.x = getWidth() - result.getWidth();
xDelta *= -1;
}
if (point.y < 0) {
point.y = 0;
yDelta *= -1;
} else if (point.y + result.getHeight() > getHeight()) {
point.y = getHeight() - result.getHeight();
yDelta *= -1;
}
result.setLocation(point);
repaint();
}
});
timer.start();
}
public void setResult(Number number) {
result.setText(NumberFormat.getNumberInstance().format(number));
result.setSize(result.getPreferredSize());
setVisible(true);
}
}
public class NewPane extends JPanel {
private final ResultPane resultPane;
public NewPane(ResultPane resultPane) {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
this.resultPane = resultPane;
JPanel buttons = new JPanel();
buttons.add(new JButton(new LabelAction()));
add(buttons, gbc);
}
public class LabelAction extends AbstractAction {
LabelAction() {
putValue(NAME, "Label");
}
#Override
public void actionPerformed(ActionEvent e) {
resultPane.setResult(123);
}
}
}
private class HandlerClass implements MouseListener, MouseMotionListener {
public void mouseClicked(MouseEvent event) {
resultPane.setResult(0);
}
public void mouseReleased(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mouseEntered(MouseEvent event) {
}
public void mouseMoved(MouseEvent event) {
}
public void mouseDragged(MouseEvent event){
}
}
}

resultPane is only defined in the scope of run(). If you want HandlerClass to have access to it you need to give it a definition.

Make resultPane instance variable. You can't access local variable outside the method.
class MovingLabel {
private ResultPane resultPane; // Declare it as instance variable
public MovingLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
...
resultPane = new ResultPane(); // Initialize the instance variable
...
}
}
}
It's a nice program.

Personally, I put every class in a new file. For me it easier to understand scope. The problem is indeed that the reference in HandlerClass is outside of it's declaration in the other classes.

Related

Cannot make notify() to work with Bouncing Balls using Threads

I am trying to use one thread to control bouncing balls. I can add balls, delete balls, suspend the movement but when i try to resume the movement of bouncing balls, notify()/notifyAll() is not working. I want only one thread to control the movement of balls that are being added in a List. I would appreciate a simple explanation as I am a complete novice. Here is the code:
************************************************
public class BounceBallApp extends JApplet {
public BounceBallApp() {
add(new BallControl());
}
public static void main(String[] args) {
BounceBallApp applet = new BounceBallApp();
JFrame frame = new JFrame();
frame.add(applet); //new line added as per the reference
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Assig_1_Base");
frame.add(applet, BorderLayout.CENTER);
frame.setSize(400, 320);
frame.setVisible(true);
}
}
***************************************************************
public class BallControl extends JPanel {
private BallPanel ballPanel = new BallPanel();
private JButton jbtSuspend = new JButton("Suspend");
private JButton jbtResume = new JButton("Resume");
private JScrollBar jsbDelay = new JScrollBar();
private JButton jbtAddBall = new JButton("+1");
private JButton jbtDeleteBall = new JButton("-1");
public BallControl() {
JPanel panel = new JPanel();
panel.add(jbtSuspend);
panel.add(jbtResume);
panel.add(jbtAddBall);
panel.add(jbtDeleteBall);
ballPanel.add();
ballPanel.setBorder(new javax.swing.border.LineBorder(Color.red));
jsbDelay.setOrientation(JScrollBar.HORIZONTAL);
ballPanel.setDelay(jsbDelay.getMaximum());
setLayout(new BorderLayout());
add(jsbDelay, BorderLayout.NORTH);
add(ballPanel, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
// Register listeners
jbtSuspend.addActionListener(new ActionListener() {
#Override
public synchronized void actionPerformed(ActionEvent e) {
ballPanel.suspend();
}
});
jbtResume.addActionListener(new ActionListener() {
#Override
public synchronized void actionPerformed(ActionEvent e) {
ballPanel.resume();
}
});
jbtAddBall.addActionListener(new ActionListener() {
#Override
public synchronized void actionPerformed(ActionEvent e) {
ballPanel.add();
}
});
jbtDeleteBall.addActionListener(new ActionListener() {
#Override
public synchronized void actionPerformed(ActionEvent e) {
ballPanel.delete();
}
});
jsbDelay.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
ballPanel.setDelay(jsbDelay.getMaximum() - e.getValue());
}
});
}
}
public class BallPanel extends JPanel {
private int delay = 10;
private List<Ball> ballsArray = Collections.synchronizedList(new ArrayList());
//protected List<Ball> ballsArray = new ArrayList<>();
private int radius = 5;
boolean threadSuspended = false;
public BallPanel() {
start();
}
protected void start(){
Thread t;
t = new Thread(){
#Override
public void run(){
System.out.println("*************");
while (true){
repaint();
try {
Thread.sleep(delay);
synchronized(this){
if (threadSuspended==true) {wait();}
}
} catch (InterruptedException e){
e.getMessage();
}
}
}
};
t.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Ball ball : ballsArray){
g.setColor(ball.color);
if (ball.x < 0 || ball.x > getWidth())
ball.dx *= -1;
if (ball.y < 0 || ball.y > getHeight())
ball.dy *= -1;
ball.x += ball.dx;
ball.y += ball.dy;
g.fillOval(ball.x - radius, ball.y - radius, radius * 2, radius * 2);
}
}
public synchronized void suspend() {
threadSuspended = true;
}
public synchronized void resume() {
threadSuspended = false;
notify();
}
public void setDelay(int delay) {
this.delay = delay;
}
public void add(){
if (threadSuspended==false) ballsArray.add(new Ball());
}
public void delete(){
if (ballsArray.size() > 0 && threadSuspended==false)
ballsArray.remove(ballsArray.size() - 1); // Remove the last ball
}
}
**************************************************
public class Ball {
int x = 0;
int y = 0;
int dx = 2;
int dy = 2;
Color color = new Color(random(255),random(255),random(255));
public static int random(int maxRange) {
return (int) Math.round((Math.random() * maxRange));
}
}
You have a "context" issue...
You declare the Thread within the context of the BallPane...
So, when you call wait(), you are actually calling wait() on t
Thread t;
t = new Thread(){
#Override
public void run(){
/*...*/
// this = t
synchronized(this){
// This is the same as saying
// this.wait() or t.wait();
if (threadSuspended==true) {wait();}
}
}
};
But when you call notify, you are calling BallPane's notify method...
public synchronized void resume() {
threadSuspended = false;
// This is the same as this.notify or BallPane.this.notify()
notify();
}
So, t is waiting on t's monitor lock and you call BallPane's notify on it's monitor lock...meaning t will never be notified.
It would be better if you used a shared lock instead...
public class BallPanel extends JPanel {
protected static final Object SUSPEND_LOCK = new Object();
/*...*/
Thread t;
t = new Thread(){
#Override
public void run(){
/*...*/
synchronized(SUSPEND_LOCK ){
if (threadSuspended==true) {SUSPEND_LOCK.wait();}
}
}
};
/*...*/
public void resume() {
synchronized(SUSPEND_LOCK){
threadSuspended = false;
SUSPEND_LOCK.notify();
}
}

Animations when using Gridbag Layout.

I have recently started Java and wondered if it was possible to make Animations whilst using GridBag Layout.
Are these possible and how? Any tutorials, help and such would be greatly appreciated :)
In order to perform any kind of animation of this nature, you're going to need some kind of proxy layout manager.
It needs to determine the current position of all the components, the position that the layout manager would like them to have and then move them into position.
The following example demonstrates the basic idea. The animation engine use is VERY basic and does not include features like slow-in and slow-out fundamentals, but uses a linear approach.
public class TestAnimatedLayout {
public static void main(String[] args) {
new TestAnimatedLayout();
}
public TestAnimatedLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestAnimatedLayoutPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestAnimatedLayoutPane extends JPanel {
public TestAnimatedLayoutPane() {
setLayout(new AnimatedLayout(new GridBagLayout()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("Value:"), gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(new JComboBox(), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridwidth = 2;
add(new JScrollPane(new JTextArea()), gbc);
gbc.gridwidth = 0;
gbc.gridy++;
gbc.gridx++;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
add(new JButton("Click"), gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class AnimatedLayout implements LayoutManager2 {
private LayoutManager2 proxy;
private Map<Component, Rectangle> mapStart;
private Map<Component, Rectangle> mapTarget;
private Map<Container, Timer> mapTrips;
private Map<Container, Animator> mapAnimators;
public AnimatedLayout(LayoutManager2 proxy) {
this.proxy = proxy;
mapTrips = new WeakHashMap<>(5);
mapAnimators = new WeakHashMap<>(5);
}
#Override
public void addLayoutComponent(String name, Component comp) {
proxy.addLayoutComponent(name, comp);
}
#Override
public void removeLayoutComponent(Component comp) {
proxy.removeLayoutComponent(comp);
}
#Override
public Dimension preferredLayoutSize(Container parent) {
return proxy.preferredLayoutSize(parent);
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return proxy.minimumLayoutSize(parent);
}
#Override
public void layoutContainer(Container parent) {
Timer timer = mapTrips.get(parent);
if (timer == null) {
System.out.println("...create new trip");
timer = new Timer(125, new TripAction(parent));
timer.setRepeats(false);
timer.setCoalesce(false);
mapTrips.put(parent, timer);
}
System.out.println("trip...");
timer.restart();
}
protected void doLayout(Container parent) {
System.out.println("doLayout...");
mapStart = new HashMap<>(parent.getComponentCount());
for (Component comp : parent.getComponents()) {
mapStart.put(comp, (Rectangle) comp.getBounds().clone());
}
proxy.layoutContainer(parent);
LayoutConstraints constraints = new LayoutConstraints();
for (Component comp : parent.getComponents()) {
Rectangle bounds = comp.getBounds();
Rectangle startBounds = mapStart.get(comp);
if (!mapStart.get(comp).equals(bounds)) {
comp.setBounds(startBounds);
constraints.add(comp, startBounds, bounds);
}
}
System.out.println("Items to layout " + constraints.size());
if (constraints.size() > 0) {
Animator animator = mapAnimators.get(parent);
if (animator == null) {
animator = new Animator(parent, constraints);
mapAnimators.put(parent, animator);
} else {
animator.setConstraints(constraints);
}
animator.restart();
} else {
if (mapAnimators.containsKey(parent)) {
Animator animator = mapAnimators.get(parent);
animator.stop();
mapAnimators.remove(parent);
}
}
}
#Override
public void addLayoutComponent(Component comp, Object constraints) {
proxy.addLayoutComponent(comp, constraints);
}
#Override
public Dimension maximumLayoutSize(Container target) {
return proxy.maximumLayoutSize(target);
}
#Override
public float getLayoutAlignmentX(Container target) {
return proxy.getLayoutAlignmentX(target);
}
#Override
public float getLayoutAlignmentY(Container target) {
return proxy.getLayoutAlignmentY(target);
}
#Override
public void invalidateLayout(Container target) {
proxy.invalidateLayout(target);
}
protected class TripAction implements ActionListener {
private Container container;
public TripAction(Container container) {
this.container = container;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("...trip");
mapTrips.remove(container);
doLayout(container);
}
}
}
public class LayoutConstraints {
private List<AnimationBounds> animationBounds;
public LayoutConstraints() {
animationBounds = new ArrayList<AnimationBounds>(25);
}
public void add(Component comp, Rectangle startBounds, Rectangle targetBounds) {
add(new AnimationBounds(comp, startBounds, targetBounds));
}
public void add(AnimationBounds bounds) {
animationBounds.add(bounds);
}
public int size() {
return animationBounds.size();
}
public AnimationBounds[] getAnimationBounds() {
return animationBounds.toArray(new AnimationBounds[animationBounds.size()]);
}
}
public class AnimationBounds {
private Component component;
private Rectangle startBounds;
private Rectangle targetBounds;
public AnimationBounds(Component component, Rectangle startBounds, Rectangle targetBounds) {
this.component = component;
this.startBounds = startBounds;
this.targetBounds = targetBounds;
}
public Rectangle getStartBounds() {
return startBounds;
}
public Rectangle getTargetBounds() {
return targetBounds;
}
public Component getComponent() {
return component;
}
public Rectangle getBounds(float progress) {
return calculateProgress(getStartBounds(), getTargetBounds(), progress);
}
}
public static Rectangle calculateProgress(Rectangle startBounds, Rectangle targetBounds, float progress) {
Rectangle bounds = new Rectangle();
if (startBounds != null && targetBounds != null) {
bounds.setLocation(calculateProgress(startBounds.getLocation(), targetBounds.getLocation(), progress));
bounds.setSize(calculateProgress(startBounds.getSize(), targetBounds.getSize(), progress));
}
return bounds;
}
public static Point calculateProgress(Point startPoint, Point targetPoint, float progress) {
Point point = new Point();
if (startPoint != null && targetPoint != null) {
point.x = calculateProgress(startPoint.x, targetPoint.x, progress);
point.y = calculateProgress(startPoint.y, targetPoint.y, progress);
}
return point;
}
public static Dimension calculateProgress(Dimension startSize, Dimension targetSize, float progress) {
Dimension size = new Dimension();
if (startSize != null && targetSize != null) {
size.width = calculateProgress(startSize.width, targetSize.width, progress);
size.height = calculateProgress(startSize.height, targetSize.height, progress);
}
return size;
}
public static int calculateProgress(int startValue, int endValue, float fraction) {
int value = 0;
int distance = endValue - startValue;
value = (int) ((float) distance * fraction);
value += startValue;
return value;
}
public class Animator implements ActionListener {
private Timer timer;
private LayoutConstraints constraints;
private int tick;
private Container parent;
public Animator(Container parent, LayoutConstraints constraints) {
setConstraints(constraints);
timer = new Timer(16, this);
timer.setRepeats(true);
timer.setCoalesce(true);
this.parent = parent;
}
private void setConstraints(LayoutConstraints constraints) {
this.constraints = constraints;
}
public void restart() {
tick = 0;
timer.restart();
}
protected void stop() {
timer.stop();
tick = 0;
}
#Override
public void actionPerformed(ActionEvent e) {
tick += 16;
float progress = (float)tick / (float)1000;
if (progress >= 1f) {
progress = 1f;
timer.stop();
}
for (AnimationBounds ab : constraints.getAnimationBounds()) {
Rectangle bounds = ab.getBounds(progress);
Component comp = ab.getComponent();
comp.setBounds(bounds);
comp.invalidate();
comp.repaint();
}
parent.repaint();
}
}
}
Update
You could also take a look at AurelianRibbon/Sliding-Layout
This is the program which i did long time back when i just started my Java classes.I did simple animations on different tabs on JTabbedPane (change the path of images/sound file as required),hope this helps:
UPDATE:
Sorry about not following concurrency in Swing.
Here is updated answer:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ClassTestHello extends JApplet {
private static JPanel j1;
private JLabel jl;
private JPanel j2;
private Timer timer;
private int i = 0;
private int[] a = new int[10];
#Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
start();
paint();
}
});
}
public void paint() {
jl = new JLabel("hiii");
j1.add(jl);
a[0] = 1000;
a[1] = 800;
a[2] = 900;
a[3] = 2000;
a[4] = 500;
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if(i % 2 == 0)
jl.setText("hiii");
else
jl.setText("byee");
i++;
if(i > 4)
i=0;
timer.setDelay(a[i]);
}
};
timer = new Timer(a[i], actionListener);
timer.setInitialDelay(0);
timer.start();
}
#Override
public void start() {
j1 = new JPanel();
j2 = new JPanel();
JTabbedPane jt1 = new JTabbedPane();
ImageIcon ic = new ImageIcon("e:/guitar.gif");
JLabel jLabel3 = new JLabel(ic);
j2.add(jLabel3);
jt1.add("one", j1);
jt1.addTab("hii", j2);
getContentPane().add(jt1);
}
}

Hold button for spinning images

I'm trying to create a hold button on Java for my bandit machine, when pressed it will hold that image and the other 2 images will keep spinning. Anyone know the code to allow that to happen?
if (e.getSource()== btnaddcash){
txtbalance.setForeground(Color.red);
cash = cash + 100;
txtbalance.setText(cash + "");
if (e.getSource() == btnpic1){
The basic concept is, you want to spin an image (or take some action) while the button is "armed".
A way by which you can achieve this is to add a ChangeListener to the button and monitor the ButtonModel#isArmed state.
public class ChangeButton {
public static void main(String[] args) {
new ChangeButton();
}
public ChangeButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SlotPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SlotPaneextends JPanel {
private SpinPane spinPane;
private JButton button;
public SlotPane() {
spinPane = new SpinPane();
button = new JButton("Press");
// I've attached directly to the model, I don't
// think this is required, simply attaching a change
// listener to the button achieve the same result.
button.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
spinPane.setSpinning(button.getModel().isArmed());
}
});
setLayout(new BorderLayout());
add(spinPane);
add(button, BorderLayout.SOUTH);
}
}
public class SpinPane extends JPanel {
private BufferedImage mole;
private Timer timer;
private float angel = 0;
public SpinPane() {
try {
mole = ImageIO.read(new File("mole.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
timer = new Timer(15, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
angel += 15;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
}
#Override
public Dimension getPreferredSize() {
return mole == null ? super.getPreferredSize() : new Dimension(mole.getWidth(), mole.getHeight());
}
public void setSpinning(boolean spinning) {
if (spinning) {
if (!timer.isRunning()) {
timer.restart();
}
} else {
timer.stop();
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (mole != null) {
int x = (getWidth() - mole.getWidth()) / 2;
int y = (getHeight() - mole.getHeight()) / 2;
Graphics2D g2d = (Graphics2D) g.create();
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angel), getWidth() / 2, getHeight() / 2));
g2d.drawImage(mole, x, y, this);
g2d.dispose();
}
}
}
}

Java Paint (yes I know but I searched..), ActionListeners

thank you so much but I need Listener methods and solved it now.. But now I cant see the buttons until I hover on them! I think its just a small mistake but I couldnt figure it out!! Now my code is like below...
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class PaintMain extends JFrame
{
JPanel colorPanel = new JPanel();
JPanel drawPanel = new JPanel();
JPanel selectPanel = new JPanel();
JButton[][] randomColors = new JButton[5][5];
Color selectedColor = Color.BLACK;
Random colorGenerator = new Random();
int curx = drawPanel.getX();
int cury = drawPanel.getY();
public PaintMain()
{
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
colorPanel.setLayout(new GridLayout(5,5));
drawPanel.setLayout(new BorderLayout());
drawPanel.setBackground(Color.WHITE);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
randomColors[i][j]=new JButton();
randomColors[i][j].setBackground(getRandomColor());
randomColors[i][j].addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if( e.getSource() instanceof JButton)
{
selectedColor=((JButton)e.getSource()).getBackground();
System.out.println(selectedColor);
}
}
});
colorPanel.add(randomColors[i][j]);
}
}
this.addMouseMotionListener(new MouseLsnr());
add(colorPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.CENTER);
setVisible(true);
pack();
}
public Color getRandomColor()
{
return new Color(colorGenerator.nextInt(256), colorGenerator.nextInt(256), colorGenerator.nextInt(256));
}
public static void main(String[] args)
{
new PaintMain();
}
public void paint(Graphics g)
{
//super.paint(g);
g.setColor(selectedColor);
g.drawRect(curx, cury, 2, 1);
}
class MouseLsnr implements MouseMotionListener
{
public void mouseDragged(MouseEvent arg0) {
System.out.println(arg0.getX()+":"+arg0.getY());
curx=arg0.getX();
cury=arg0.getY();
repaint();
}
public void mouseMoved(MouseEvent arg0)
{
}
}
}
You'll want to take a closer look at Custom Painting
The you might want to take a read through How to Write a Mouse Listener
public class RandomColorPane {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new RandomColorPane();
}
public RandomColorPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
JPanel colorPanel = new JPanel();
JPanel drawPanel = new DrawPane();
JPanel selectPanel = new JPanel();
JPanel[][] randomColors = new JPanel[5][5];
Color selectedColor = Color.BLACK;
Random colorGenerator = new Random();
int curx = drawPanel.getX();
int cury = drawPanel.getY();
public MainPane() {
setLayout(new BorderLayout());
colorPanel.setLayout(new GridLayout(5, 5));
drawPanel.setLayout(new BorderLayout());
drawPanel.setBackground(Color.WHITE);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
randomColors[i][j] = new JPanel();
randomColors[i][j].setPreferredSize(new Dimension(25, 25));
randomColors[i][j].setBackground(getRandomColor());
// randomColors[i][j].addActionListener(new ActionListener() {
// #Override
// public void actionPerformed(ActionEvent e) {
// if (e.getSource() instanceof JButton) {
// selectedColor = ((JButton) e.getSource()).getBackground();
// drawPanel.setForeground(selectedColor);
// drawPanel.repaint();
// }
// }
//
// });
randomColors[i][j].addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
drawPanel.setForeground(((JPanel)e.getSource()).getBackground());
drawPanel.repaint();
}
});
colorPanel.add(randomColors[i][j]);
}
}
add(colorPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.CENTER);
}
public Color getRandomColor() {
return new Color(colorGenerator.nextInt(256), colorGenerator.nextInt(256), colorGenerator.nextInt(256));
}
}
public class DrawPane extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - 10) / 2;
int y = (getHeight() - 10) / 2;
g.setColor(getForeground());
g.fillRect(x, y, 20, 20);
}
}
}

Press and Drag in One Click?

I have a program where I am creating a JLabel on a click and then dragging that to another portion of the interface.
What I want is to click somewhere in the JPanel, have it drop a JLabel there, and then drag another JLabel all in the same click.
I am able to do this, but it takes multiple clicks. Can I do it in one click?
To illustrate what I mean, I created this sample program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragTest extends JFrame implements MouseMotionListener,
MouseListener {
private JPanel panel = new JPanel(null);
private JLabel dragLabel = new JLabel("drag");;
private final JWindow window = new JWindow();
public DragTest() {
this.add(panel);
panel.addMouseListener(this);
dragLabel.setFont(new Font("Serif", Font.BOLD, 48));
}
#Override
public void mouseDragged(MouseEvent me) {
dragLabel = new JLabel("drag");
dragLabel.setFont(new Font("Serif", Font.BOLD, 48));
int x = me.getPoint().x;
int y = me.getPoint().y;
window.add(dragLabel);
window.pack();
Point pt = new Point(x, y);
Component c = (Component) me.getSource();
SwingUtilities.convertPointToScreen(pt, c);
window.setLocation(pt);
window.setVisible(true);
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
JLabel dropLabel = new JLabel("drop");
panel.add(dropLabel);
dropLabel.setForeground(Color.RED);
dropLabel.setFont(new Font("Serif", Font.BOLD, 48));
dropLabel.setBounds(e.getX(), e.getY(), 100, 60);
dropLabel.addMouseMotionListener(this);
dropLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
dragLabel.setVisible(false);
window.setVisible(false);
}
});
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
DragTest frame = new DragTest();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
So the initial click creates the "drop" JLabel, and then clicking on and dragging on the "drop" JLabel will create a "drag" JLabel that follows the mouse around.
How can I do this in one click and drag?
Don't create a new JLabel in the mouseDragged method but rather use the same JLabel. For example:
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class DragTest2 extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = 400;
private static final float LABEL_PTS = 24f;
private static final String LABEL_TEXT = "My Label";
private JLabel label = null;
public DragTest2() {
setLayout(null);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
label = new JLabel(LABEL_TEXT);
label.setFont(label.getFont().deriveFont(LABEL_PTS));
Dimension labelSize = label.getPreferredSize();
label.setSize(labelSize);
int x = e.getX() - labelSize.width / 2;
int y = e.getY() - labelSize.height / 2;
label.setLocation(x , y);
add(label);
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
if (label != null) {
Dimension labelSize = label.getPreferredSize();
int x = e.getX() - labelSize.width / 2;
int y = e.getY() - labelSize.height / 2;
label.setLocation(x , y);
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (label != null) {
Dimension labelSize = label.getPreferredSize();
int x = e.getX() - labelSize.width / 2;
int y = e.getY() - labelSize.height / 2;
label.setLocation(x , y);
repaint();
label = null;
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("DragTest2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DragTest2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories

Resources