Key Released event is not working Java Swing [duplicate] - java

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

Related

Having trouble with Key Listener [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

How to click in an internal frame of JFrame, without using a button

I'm currently making an application using Internal Frames, and I don't want to use buttons in the internal frame. I want it to understand where I am clicking (specific coordinates), and complete and action based on the location of the click.
This is one of the internal frames that I am currently trying to get he mouse clicks to register on.
package com.xxemu.main;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
public class Techni extends JInternalFrame implements InternalFrameListener, MouseListener {
private static final long serialVersionUID = -7905672790566329537L;
static int openFrameCount = 0;
private ImageIcon image;
private JLabel label;
private Menu menu;
public int frame = 1;
static final int xOffset = 75, yOffset = 90;
public Techni() {
super("emu",
true, //resizable
true, //closable
true, //maximizable
true); //iconifiable
//setSize(783, 522);
setSize(400, 400);
setLocation(xOffset, yOffset);
}
public void setLayeredPane(JLayeredPane layered) {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("asdfsd");
if (e.getX() < 0 && e.getY() > 0) {
System.out.println("test");
}
}
});
}#Override
public void internalFrameActivated(InternalFrameEvent arg0) {}
#Override
public void internalFrameClosed(InternalFrameEvent arg0) {}
#Override
public void internalFrameClosing(InternalFrameEvent arg0) {}
#Override
public void internalFrameDeactivated(InternalFrameEvent arg0) {}
#Override
public void internalFrameDeiconified(InternalFrameEvent arg0) {}
#Override
public void internalFrameIconified(InternalFrameEvent arg0) {}
#Override
public void internalFrameOpened(InternalFrameEvent arg0) {}#Override
public void mouseEntered(MouseEvent e) {}#Override
public void mouseExited(MouseEvent e) {}#Override
public void mousePressed(MouseEvent e) {}#Override
public void mouseReleased(MouseEvent e) {}#Override
public void mouseClicked(MouseEvent e) {}
}
Emulator class
package com.xxemu.main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
public class Emulator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1922575930226682951L;
JDesktopPane desktop;
private boolean running = true;
private Menu menu;
private Techni techni;
public enum STATE {
techniMenu,
p5Menu,
};
public static STATE emuState = null;
public Emulator() {
super("Emu");
int inset = 50;
setBounds(inset, inset,
1000,
800);
desktop = new JDesktopPane();
setContentPane(desktop);
setJMenuBar(createMenuBar());
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
//Set up the lone menu.
JMenu menu = new JMenu("Options");
menu.setMnemonic(KeyEvent.VK_O);
menuBar.add(menu);
//Set up the first menu item.
JMenuItem menuItem = new JMenuItem("Technicolor");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_T, ActionEvent.ALT_MASK));
menuItem.setActionCommand("techni");
menuItem.addActionListener(this);
menu.add(menuItem);
//Set up the second menu item.
menuItem = new JMenuItem("P5");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_P, ActionEvent.ALT_MASK));
menuItem.setActionCommand("p5");
menuItem.addActionListener(this);
menu.add(menuItem);
//Set up the third menu item.
menuItem = new JMenuItem("Quit");
menuItem.setMnemonic(KeyEvent.VK_Q);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_Q, ActionEvent.ALT_MASK));
menuItem.setActionCommand("quit");
menuItem.addActionListener(this);
menu.add(menuItem);
return menuBar;
}
//React to menu selections.
public void actionPerformed(ActionEvent e) {
if ("techni".equals(e.getActionCommand())) { //new
emuState = STATE.techniMenu;
System.out.println("testasdfas");
createFrameTechni();
} else if ("p5".equals(e.getActionCommand())) { //new
createFrameP5();
} else {
quit();
}
}
//Create a new internal frame.
protected void createFrameTechni() {
Techni frame = new Techni();
frame.setVisible(true);
desktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {}
}
protected void createFrameP5() {
P5 frame = new P5();
frame.setVisible(true);
desktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {}
}
public synchronized void start() {
if (running) return;
running = true;
}
protected void quit() {
System.exit(0);
}
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int updates = 0;
int frames = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
tick();
updates++;
delta--;
}
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS: " + frames + " TICKS " + updates);
frames = 0;
updates = 0;
}
}
stop();
}
private void tick() {
menu.tick();
}
public synchronized void stop() {
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
Emulator frame = new Emulator();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I have a method that I used while writing a GUI that displays your mouse coordinates inside of a frame.
private static void debugMousePosition(JFrame frame) {
final JFrame box = new JFrame("Mouse Position");
box.setAlwaysOnTop(true);
box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
box.setLocation(frame.getX() + 800,frame.getY());
box.setSize(300, 100);
box.setLayout(new GridLayout(1,2));
box.setVisible(true);
final JLabel X = new JLabel();
final JLabel Y = new JLabel();
frame.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent me) {
X.setText(String.valueOf("X Position: " + me.getX()));
Y.setText(String.valueOf("Y Position: " + me.getY()));
box.repaint();
}
});
box.add(X);
box.add(Y);
}
You pass the frame you which to monitor to the debugMousePosition() method.
It seems that you want to use a MouseActionListener, to see when the user clicks, and then onClick would get the mouse information from a MouseMotionListener. So something like
frame.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e)
{
if(e.getX() == someVariable && e.getY() == anotherVariable)
{
do something here
}
}
});
If you need more functionality, like when the mouse leaves the frame, take a look at the MouseAdapter() class to see the other methods that it has.
When you implement classes, such as InternalFrameListener, you are required to override the methods included in it. Instead of this, try to just import the Adapter versions, and when you need them create a new adapter from it. Like my above code, you'd do something similar with InternalFrameAdapter.
Here is what I would suggest your class look like:
package com.xxemu.main;
import java.awt.Menu;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class Techni extends JInternalFrame
{
private static final long serialVersionUID = -7905672790566329537L;
static int openFrameCount = 0;
private ImageIcon image;
private JLabel label;
private Menu menu;
public int frame = 1;
static final int xOffset = 75, yOffset = 90;
public Techni()
{
super("emu",
true, //resizable
true, //closable
true, //maximizable
true);//iconifiable
//setSize(783, 522);
setSize(400, 400);
setLocation(xOffset, yOffset);
}
public void setLayeredPane(JLayeredPane layered)
{
addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
System.out.println("asdfsd");
if (e.getX() < 0 && e.getY() > 0)
{
System.out.println("test");
}
}
});
}
}
You can add a MouseListener to a Component instance, which has a mouseClicked event with x and y coordinates.
Example:
component.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int xOnScreen = e.getXOnScreen();
int y = e.getY();
int yOnScreen = e.getYOnScreen();
}
});

Is java swing not working in java 8 update 45?

The following code is working in jdk 1.8 update 45 and in java 1.8 update 31 but NOT in java 1.8 update 45.
The program is a button moving back and forth until the user presses the button and makes it stop and the text is changed to "MOVE". When the button is pressed again, the button starts moving and the text is changed to "STOP".
In java 8 update 45, the button does not start moving but the text changes. Why?
package mainpackage;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class mainPanel implements ActionListener {
JFrame frame1;
JPanel panel1;
JButton button = new JButton("STOP");
boolean buttonPressed = false;
boolean move = true;
// 0 = left & 1 = right
int direction = 1;
int x = 0;
public static void main(String[] args) {
new mainPanel().loadGUI();
}
public void loadGUI() {
frame1 = new JFrame("Moving button");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
frame1.setSize(300, 58);
frame1.setResizable(false);
panel1 = new JPanel(); // Xwidth=294, Yheight=272
panel1.setSize(300, 30);
panel1.setLayout(null);
frame1.add(panel1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame1.setLocation(dim.width/2-frame1.getSize().width/2, dim.height/2-frame1.getSize().height/2);
button.setSize(80, 30); //X, Y
panel1.add(button);
button.addActionListener(this);
while(true) moveButton();
}
public void moveButton() {
while(move == true) {
switch(direction) {
// left
case 0: {
while(x > 0) {
if(move == false) break;
button.setLocation(x, 0);
x--;
panel1.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(mainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(buttonPressed == true) {
direction = 0;
buttonPressed = false;
} else if(buttonPressed == false) {
direction = 1;
buttonPressed = false;
}
}
// right
case 1: {
while(x < panel1.getWidth() - button.getWidth()) {
if(move == false) break;
button.setLocation(x, 0);
x++;
panel1.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(mainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(buttonPressed == true) {
direction = 1;
buttonPressed=false;
} else if(buttonPressed == false) {
direction=0;
buttonPressed=false;
}
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
if (move == true){
move=false;
} else if (move == false) {
move=true;
}
buttonPressed = true;
if((button.getText()).equals("STOP")) {
button.setText("MOVE");
} else button.setText("STOP");
}
}
Yours is broken code to begin with since it ignores Swing threading rules, and frankly I'm surprised that it worked in previous versions of Java. You're calling a while (true) loop that will tie up any thread that it is called in. Java 8 is correctly trying to start your Swing GUI on the Swing event thread, something that all Swing programs should do. If you get rid of the while (true) loops that risk being called on the Swing event dispatch thread, and instead use a Swing Timer your code should work. The Timer will run a loop in a background thread, but all code called repeatedly in its ActionListener will be called on the Swing event thread.
For example:
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MyMainPanel extends JPanel {
private static final int PREF_W = 300;
private static final int PREF_H = 30;
private static final int TIMER_DELAY = 20;
public static final int DELTA_X = 3;
private JButton moveButton = new JButton(new MoveButtonAction("Move"));
private Timer moveTimer = new Timer(TIMER_DELAY, new MoveTimerListener());
private boolean moveRight = true;
public MyMainPanel() {
moveButton.setSize(moveButton.getPreferredSize());
int y = (getPreferredSize().height - moveButton.getPreferredSize().height) / 2;
moveButton.setLocation(0, y);
setLayout(null); // !! lord I hate this
add(moveButton);
moveTimer.start();
}
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class MoveButtonAction extends AbstractAction {
public MoveButtonAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
moveRight = !moveRight;
}
}
private class MoveTimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (moveRight) {
if (moveButton.getLocation().x + moveButton.getWidth() >= getWidth()) {
moveRight = false;
}
} else {
if (moveButton.getLocation().x <= 0) {
moveRight = true;
}
}
int x = moveButton.getLocation().x + (moveRight ? DELTA_X : -DELTA_X);
int y = moveButton.getLocation().y;
moveButton.setLocation(new Point(x, y));
repaint();
}
}
private static void createAndShowGui() {
MyMainPanel mainPanel = new MyMainPanel();
JFrame frame = new JFrame("GUI Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You will want to read up on Swing thread safety to see why your program is failing. See Lesson: Concurrency in Swing to see more on this.
Edit: code that stops and starts movement:
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyMainPanel extends JPanel {
private static final String MOVE = "Move";
private static final String STOP = "Stop";
private static final int PREF_W = 300;
private static final int PREF_H = 30;
private static final int TIMER_DELAY = 20;
public static final int DELTA_X = 3;
private MoveButtonAction moveButtonAction = new MoveButtonAction(STOP);
private JButton moveButton = new JButton(moveButtonAction);
private Timer moveTimer = new Timer(TIMER_DELAY, new MoveTimerListener());
private boolean moveRight = true;
public MyMainPanel() {
moveButton.setSize(moveButton.getPreferredSize());
int y = (getPreferredSize().height - moveButton.getPreferredSize().height) / 2;
moveButton.setLocation(0, y);
setLayout(null); // !! lord I hate this
add(moveButton);
moveTimer.start();
}
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class MoveButtonAction extends AbstractAction {
public MoveButtonAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (MOVE.equals(getValue(NAME))) {
moveTimer.start();
putValue(NAME, STOP);
int mnemonic = (int) STOP.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
} else {
moveTimer.stop();
putValue(NAME, MOVE);
int mnemonic = (int) MOVE.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
AbstractButton button = (AbstractButton) e.getSource();
button.setSize(button.getPreferredSize());
repaint();
}
}
private class MoveTimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (moveRight) {
if (moveButton.getLocation().x + moveButton.getWidth() >= getWidth()) {
moveRight = false;
}
} else {
if (moveButton.getLocation().x <= 0) {
moveRight = true;
}
}
int x = moveButton.getLocation().x + (moveRight ? DELTA_X : -DELTA_X);
int y = moveButton.getLocation().y;
moveButton.setLocation(new Point(x, y));
repaint();
}
}
private static void createAndShowGui() {
MyMainPanel mainPanel = new MyMainPanel();
JFrame frame = new JFrame("GUI Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Just added some methods and fixed some lines in your code, you can try it now:
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class mainPanel implements ActionListener {
JFrame frame1;
JPanel panel1;
JButton button = new JButton("START");
boolean buttonPressed = false;
boolean move = false;
Timer timer;
int direction = 1;
int x = 0;
public static void main(String[] args) {
new mainPanel().loadGUI();
}
public void loadGUI() {
frame1 = new JFrame("Moving button");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
frame1.setSize(300, 58);
frame1.setResizable(false);
panel1 = new JPanel(); // Xwidth=294, Yheight=272
panel1.setSize(300, 30);
panel1.setLayout(null);
frame1.add(panel1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame1.setLocation(dim.width / 2 - frame1.getSize().width / 2, dim.height / 2 - frame1.getSize().height / 2);
button.setSize(80, 30); //X, Y
panel1.add(button);
button.addActionListener(this);
moveButton();
}
public void moveButton() {
if (timer == null) {
initTimer();
}
move = !move;
if (move) {
button.setText("STOP");
direction = (direction == 0) ? 1 : 0;
timer.start();
} else {
button.setText("MOVE");
timer.stop();
}
}
public void initTimer() {
timer = new Timer(10, (e) -> {
switch (direction) {
case 0: // right
x++;
if (x >= panel1.getWidth() - button.getWidth()) {
direction = 1;
}
break;
case 1: // left
x--;
if (x <= 0) {
direction = 0;
}
break;
}
button.setLocation(x, 0);
panel1.repaint();
});
}
#Override
public void actionPerformed(ActionEvent e) {
moveButton();
}
}

timer t = new timer(50, b); t.stop(); is not working

My t.stop(); method is not working. I am going crazy trying to figure out why my stop method is not working.
I'm using the a timer in my code and I can't get it to stop. Can anyone take a look at it and tell me what's going on?:
/*Gilberto Rose*/
package homework2;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MultipleBalls extends JFrame implements ActionListener
{
int dx = 2;
int dy = 2;
int x = 1;
int y = 1;
int i = 0;
public static void main(String[] args)
{
Runnable balls = new Ball2();
Thread thread1 = new Thread(balls);
thread1.run();
}
#Override
public void actionPerformed(ActionEvent arg0)
{
repaint();
System.out.println(i++);
}
}// End of Ball class
class Ball2 extends JPanel implements Runnable
{
MultipleBalls b = new MultipleBalls();
JButton g = new JButton("resume");
JButton f = new JButton("suspend");
JButton e = new JButton("-1");
JButton d = new JButton("+1");
List<Ball2> L = new ArrayList<Ball2>();
Timer t = new Timer(50, b);
public int x = 6;
public void loopstop()
{
t.stop();
}// end of loopstop method
Ball2()
{
controller4();
controller3();
controller2();
controller();
add(d);
add(e);
add(f);
add(g);
}// End of Ball2 constructor
public void run()
{
Ball2 c = new Ball2();
b.setSize(500, 500);
b.setVisible(true);
b.add(c);
t.start();
} // End of run method
public void controller()
{
d.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
L.add(new Ball2());
}
});
}// End of controller
public void controller2()
{
e.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("subtracter");
L.remove(L.size()-1);
}
});
}// End of controller2
public void controller3()
{
f.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
loopstop();
}
});
}// End of controller3
public void controller4()
{
g.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Resume");
}
});
}// End of controller4
public void paintComponent(Graphics g)
{
if(L.size() > 0)
{
int i = 0;
do
{
g.fillOval(L.get(i).ballx(), L.get(i).bally(), 90, 90);
i++;
}while(i < L.size() && true ); // End of Do while loop
}// End of if statement
}// End of paintComponent
MultipleBalls bb = new MultipleBalls();
public int ballx()
{
if (bb.x == 0 || bb.x == 500)
{
bb.dx *= -1;
} // End of if statement
bb.x += bb.dx;
return bb.x;
}
public int bally()
{
if (bb.y == 0 || bb.y == 500 )
{
bb.dy *= -1;
}// end of if statement
bb.y += bb.dy;
return bb.y;
}// End of bally
}// End of Ball2 class
Your code is extremely convoluted, I believe that it's suffering from something called cyclomatic complexity, so much so, it is difficult for you or us to see what object is creating what other object, and what is running what. And this is your problem. You have at least two MultipleBall objects, two Ball2 objects, and you're starting the Timer for one of the Ball2 objects and stopping it for the other.
The solution: simplify this code greatly.
Create one MultipleBalls object, just one.
Don't have MultipleBalls implement ActionListener. Rather use an anonymous inner class for your ActionListener and create it on the spot where you need it.
Create just one Ball2 object, just one.
Also note that you almost never call run() on a Thread object but rather start(), but having said that, I'm not even sure that you should be using a Thread object where you're using it.
Edit
My main class would be simple, and would simply have a main method and supporting method that gets things started. Something like:
public class MultipleBalls {
private static void createAndShowGui() {
BallsPanel mainPanel = new BallsPanel();
JFrame frame = new JFrame("Multiple Balls");
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
For an example of a separation of concerns:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.*;
public class MultipleBallsZ {
private static void createAndShowGui() {
BallsPanelZ ballsPanel = new BallsPanelZ();
new Control(ballsPanel);
JFrame frame = new JFrame("Multiple Balls");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(ballsPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class BallsPanelZ extends JPanel {
private static final int TIMER_DELAY = 200;
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private Timer timer = new Timer(TIMER_DELAY, new TimerListener());
private int counter = 0;
private Control control = null;
public BallsPanelZ() {
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public Timer getTimer() {
return timer;
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
System.out.printf("Count: %03d%n", counter);
}
}
public void setControl(Control control) {
this.control = control;
for (Action action : control) {
add(new JButton(action));
}
}
}
#SuppressWarnings("serial")
class Control implements Iterable<Action> {
private List<Action> actionList = new ArrayList<>();
private BallsPanelZ ballsPanel;
public Control(BallsPanelZ ballsPanel) {
actionList.add(new PauseAction());
actionList.add(new ResumeAction());
this.ballsPanel = ballsPanel;
ballsPanel.setControl(this);
}
private class PauseAction extends AbstractAction {
public PauseAction() {
super ("Timer Pause");
putValue(MNEMONIC_KEY, KeyEvent.VK_P);
}
#Override
public void actionPerformed(ActionEvent e) {
ballsPanel.getTimer().stop();
}
}
private class ResumeAction extends AbstractAction {
public ResumeAction() {
super("Timer Resume");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
putValue(DISPLAYED_MNEMONIC_INDEX_KEY, 6);
}
#Override
public void actionPerformed(ActionEvent e) {
ballsPanel.getTimer().restart();
}
}
#Override
public Iterator<Action> iterator() {
return actionList.iterator();
}
}

Hiding and showing Panel during runtime

I'm trying to show and hide a panel during run time, so I call the methods from another class:
Con.Action(1);
to this method:
public void Action(int whichPanel) {
if (whichPanel == 1) {
if (frame.Data.isVisible()) {
frame.Data.setVisible(false);
// frame.splitPaneSec.remove(frame.Data);
} else {
System.out.println(".....");
//frame.Data.setVisible(false);
frame.Data.setVisible(true);
//frame.getContentPane().validate();
//frame.revalidate();
//frame.repaint();
//frame.pack();
}
}
So far i'm able to hide a panel but I can't show it again once I hidden it.
I've tried many ways some of them are commented out.
Any help is appreciated, cheers
I think I would rather remove and add it back.
parent.remove(dataPanel);
parent.validate();
parent.repaint();
parent.add(dataPanel);
parent.validate();
parent.repaint();
I highly recommed you to use enums for Tasks like this:
public void Action(int whichPanel) {
if (whichPanel == 1) {}
//Better;
public void Action(enumType myPanel){
if(myPanel == enumType.LoginScreen){}
with `
public enum enumType
{
LoginScreen,EditScreen //...
}`
You can hide and show Enums if you perfom the setVisible method directly on the Panel you want to show:
public void showLoginScreen()
{
loginPanel.setVisible(true);
registerMenu.setVisible(false);
}
The issue was because after setting the component back to visible
it was required to GUIClass.splitPane.setDividerLocation(157);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class HidePanel extends JFrame {
private static final int PANEL_HEIGHT = 50;
private static final int INITIAL_PANEL_WIDTH = 50;
private static final int TIMER_INTERVAL = 1;
private static final int PIXEL_DELTA = 2;
private Dimension panelDimension = new Dimension(INITIAL_PANEL_WIDTH, PANEL_HEIGHT);
private int vertOffset = -PANEL_HEIGHT;
private Timer showTimer = new HidePanel.ShowPanelTimer();
private Timer hideTimer = new HidePanel.HidePanelTimer();
static JLayeredPane lpane = new JLayeredPane();
JPanel panel = new JPanel();
public HidePanel() {
setBackground(Color.BLACK);
setLayout(null);
panel.setBounds(1200, 50, 100, 600);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Hide"));
panel.add(new JButton("Click Me"));
lpane.add(panel);//, //new Integer(0), 0);
add(panel);
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
final int height = e.getY() - 100 ;
if (height < 50 && !showTimer.isRunning() && !panel.isVisible()) {
showTimer.start();
} else if (height > PANEL_HEIGHT + 5 && !hideTimer.isRunning() && panel.isVisible()) {
hideTimer.start();
}
}
});
}
public static void main(String args[]) {
HidePanel h = new HidePanel();
h.setSize(1350, 700);
h.setVisible(true);
h.add(lpane, BorderLayout.CENTER);
}
private void positionPanel(final int offset) {
int panelWidth = getWidth();
System.out.println(" offset = " + offset);
panelDimension.setSize(panelWidth, PANEL_HEIGHT);
//panel.setBounds(insets.left, offset + insets.top, size.width, size.height);
}
private class ShowPanelTimer extends Timer implements ActionListener {
ShowPanelTimer() {
super(TIMER_INTERVAL, null);
addActionListener(this);
}
public void start() {
vertOffset = -PANEL_HEIGHT;
panel.setVisible(true);
super.start();
}
public void actionPerformed(ActionEvent e) {
if (vertOffset <= 0) {
positionPanel(vertOffset);
} else {
showTimer.stop();
}
vertOffset += PIXEL_DELTA;
}
}
private class HidePanelTimer extends Timer implements ActionListener {
HidePanelTimer() {
super(TIMER_INTERVAL, null);
addActionListener(this);
}
public void stop() {
panel.setVisible(false);
super.stop();
}
public void actionPerformed(ActionEvent e) {
if (vertOffset >= (-PANEL_HEIGHT)) {
vertOffset -= PIXEL_DELTA;
positionPanel(vertOffset);
} else {
hideTimer.stop();
}
}
}
}

Categories