Here what I want is that when the Buttons are clicked the shapes should appear immediately, but the shapes does not appear unless the JFrame is minimized and restored.
package tutorial;
public class Tutorial extends JPanel{
JButton b1,b2,b3,b4,b5;
boolean nodeA, nodeB,communicate, key, acknowledge = false;
public Tutorial(){
b1 = new JButton("Node A");
add(b1);
b2 = new JButton("Node B");
add(b2);
b3 = new JButton("Communicate");
add(b3);
b4 = new JButton("send key");
add(b4);
b5 = new JButton("Request B");
add(b5);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(300, 100,100, 50);
g.setColor(Color.red);
g.drawString("KDC/KMC",320,130);
b1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
nodeA = true;
}
});
if(nodeA == true){
g.setColor(Color.green);
g.fillOval(100, 300, 70, 70);
g.setColor(Color.red);
g.drawString("Node A", 113, 340);
g.drawString("Node A added",150,220);
g.drawLine(150, 300, 300, 150);
}
b2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
nodeB = true;
}
});
if(nodeB == true){
g.setColor(Color.green);
g.fillOval(530, 300, 70, 70);
g.setColor(Color.red);
g.drawString("Node B",545,340);
g.drawString("Node B added",473,220);
g.drawLine(550, 300, 400, 150);
}
b3.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(nodeA == true && nodeB == true)
communicate = true;
}
});
if(communicate == true){
g.drawString("A requests for B's Session Key", 230,260);
g.drawLine(165, 310, 325, 150);
}
b4.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(communicate == true)
key = true;
}
});
if(key == true){
g.drawString("A's key is 4",210,175);
g.drawString("B's key is 5",430,175);
}
b5.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(key == true)
acknowledge = true;
}
});
if(acknowledge == true){
g.drawLine(170,325,530,325);
g.drawString("A sends part of session key to B", 260, 320);
g.drawLine(170,350,530,350);
g.drawString("if sessiion key match then B sent Acknowledgement", 215, 365);
}}
public static void main(String[] args) {
Tutorial t = new Tutorial();
JFrame jf = new JFrame("Assignment");
jf.setSize(1200,900);
jf.add(t);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Here it looks like when clicked but not minimized enter image description here
and here it looks like when JFrame is minimized and restoredenter image description here
I assume you do something to add that green node later? If you modify classes directly without them being Swing classes, I think you manually have to issue a repaint() on your Swing class/container or Swing doesn't know that the components needs to be updated on the screen (Swing classes do this automatically when they are changed, so you don't have to do it when you call add() for example). – markspace
Related: Repaint() vs. Revalidate() stackoverflow.com/questions/1097366/… Do some searches too to understand how Swing's repaint system works (lots of tutorials). – markspace
Related
So I am currently working on the graphics for a game, and I wanted to include a fade effect to add depth to the game. I am also using JButtons, but the problem is, my fade effect is fading everything, including my JButtons. I want to make it so that only the black rectangle I imported fades, and that the JButtons remain visible throughout. The background images are fine, it is just the JButtons. The JButtons fade, and then reappear when I hover over them. Any ideas on how to fix the issue?
My code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
// playButton.setContentAreaFilled(false);
// playButton.setEnabled(false);
public class Frame extends JPanel implements ActionListener, KeyListener, MouseListener{
JButton playButton;
JButton instructionButton;
JButton lvlOneButton;
JButton lvlTwoButton;
JButton lvlThreeButton;
JButton backButton;
//Music mainTheme = new Music("Hyrule Field.wav");
BufferedImage instructions = null;
boolean onInstructions = false;
BufferedImage home = null;
boolean onHome = true;
BufferedImage levels = null;
boolean onLevels = false;
//Image fadeRectangle = new ImageIcon("black rectangle.png").getImage();
BufferedImage fadeRectangle = null;
Timer timer = new Timer(10, this);
float alpha = 1f;
Frame(){
loadImage();
timer.start();
playButton = new JButton();
playButton.setBounds(310, 320, 150, 70);
playButton.addActionListener(this);
playButton.addMouseListener(this);
playButton.setText("Play");
playButton.setFocusable(false);
playButton.setFont(new Font("Dialog", Font.BOLD, 40));
playButton.setForeground(Color.white);
playButton.setBackground(new Color(255, 115, 115));
playButton.setBorder(BorderFactory.createLineBorder(Color.white, 5));
playButton.setVisible(true);
instructionButton = new JButton();
instructionButton.setBounds(310, 400, 150, 70);
instructionButton.addActionListener(this);
instructionButton.addMouseListener(this);
instructionButton.setText("Instructions");
instructionButton.setFocusable(false);
instructionButton.setFont(new Font("Dialog", Font.BOLD, 20));
instructionButton.setForeground(Color.white);
instructionButton.setBackground(new Color(255, 115, 115));
instructionButton.setBorder(BorderFactory.createLineBorder(Color.white, 5));
instructionButton.setVisible(true);
lvlOneButton = new JButton();
lvlOneButton.setBounds(110, 250, 150, 150);
lvlOneButton.addActionListener(this);
lvlOneButton.addMouseListener(this);
lvlOneButton.setText("1");
lvlOneButton.setFocusable(false);
lvlOneButton.setFont(new Font("Dialog", Font.BOLD, 80));
lvlOneButton.setForeground(Color.white);
lvlOneButton.setBackground(new Color(255, 115, 115));
lvlOneButton.setBorder(BorderFactory.createLineBorder(Color.white, 5));
lvlOneButton.setVisible(false);
lvlTwoButton = new JButton();
lvlTwoButton.setBounds(310, 250, 150, 150);
lvlTwoButton.addActionListener(this);
lvlTwoButton.addMouseListener(this);
lvlTwoButton.setText("2");
lvlTwoButton.setFocusable(false);
lvlTwoButton.setFont(new Font("Dialog", Font.BOLD, 80));
lvlTwoButton.setForeground(Color.white);
lvlTwoButton.setBackground(new Color(255, 115, 115));
lvlTwoButton.setBorder(BorderFactory.createLineBorder(Color.white, 5));
lvlTwoButton.setVisible(false);
lvlThreeButton = new JButton();
lvlThreeButton.setBounds(510, 250, 150, 150);
lvlThreeButton.addActionListener(this);
lvlThreeButton.addMouseListener(this);
lvlThreeButton.setText("3");
lvlThreeButton.setFocusable(false);
lvlThreeButton.setFont(new Font("Dialog", Font.BOLD, 80));
lvlThreeButton.setForeground(Color.white);
lvlThreeButton.setBackground(new Color(255, 115, 115));
lvlThreeButton.setBorder(BorderFactory.createLineBorder(Color.white, 5));
lvlThreeButton.setVisible(false);
backButton = new JButton();
backButton.setBounds(10, 10, 150, 70);
backButton.addActionListener(this);
backButton.addMouseListener(this);
backButton.setText("Back");
backButton.setFocusable(false);
backButton.setFont(new Font("Dialog", Font.BOLD, 40));
backButton.setForeground(Color.white);
backButton.setBackground(new Color(255, 115, 115));
backButton.setBorder(BorderFactory.createLineBorder(Color.white, 5));
backButton.setVisible(false);
this.setLayout(null);
this.addMouseListener(this);
this.addKeyListener(this);
this.add(playButton);
this.add(instructionButton);
this.add(lvlOneButton);
this.add(lvlTwoButton);
this.add(lvlThreeButton);
this.add(backButton);
}
public void loadImage(){
try {
fadeRectangle = ImageIO.read(getClass().getClassLoader().getResource("black rectangle.png"));
instructions = ImageIO.read(getClass().getClassLoader().getResource("instructions.png"));
home = ImageIO.read(getClass().getClassLoader().getResource("home screen.png"));
levels = ImageIO.read(getClass().getClassLoader().getResource("level screen.png"));
} catch (IOException e) {
}
}
#Override
public void actionPerformed(ActionEvent event) {
alpha += -0.01f;
repaint();
if (alpha <= 0) {
alpha = 0;
timer.stop();
}
if (event.getSource() == playButton) {
fadeOut();
onHome = false;
onLevels = true;
playButton.setVisible(false);
instructionButton.setVisible(false);
lvlThreeButton.setVisible(true);
lvlTwoButton.setVisible(true);
lvlOneButton.setVisible(true);
backButton.setVisible(true);
}
if (event.getSource() == instructionButton) {
fadeOut();
onHome = false;
onInstructions = true;
playButton.setVisible(false);
instructionButton.setVisible(false);
backButton.setVisible(true);
}
if (event.getSource() == backButton) {
fadeOut();
onHome = true;
onInstructions = false;
onLevels = false;
playButton.setVisible(true);
instructionButton.setVisible(true);
lvlThreeButton.setVisible(false);
lvlTwoButton.setVisible(false);
lvlOneButton.setVisible(false);
backButton.setVisible(false);
}
if (event.getSource() == lvlOneButton) {
fadeOut();
lvlThreeButton.setVisible(false);
lvlTwoButton.setVisible(false);
lvlOneButton.setVisible(false);
backButton.setVisible(false);
//do level one stuff here fjkdsnfkjdsnn
}
}
public void fadeOut(){
loadImage();
alpha = 1;
timer.start();
alpha += -0.01f;
repaint();
if (alpha <= 0) {
alpha = 0;
timer.stop();
}
}
#Override
public void keyTyped(KeyEvent event) {
}
#Override
public void keyPressed(KeyEvent event) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent event) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
//makes button color lighter when hovering over
public void mouseEntered(MouseEvent e) {
if (e.getSource() == playButton){
playButton.setBackground(new Color(253, 214, 214));
}
if (e.getSource() == lvlOneButton){
lvlOneButton.setBackground(new Color(253, 214, 214));
}
if (e.getSource() == lvlTwoButton){
lvlTwoButton.setBackground(new Color(253, 214, 214));
}
if (e.getSource() == lvlThreeButton){
lvlThreeButton.setBackground(new Color(253, 214, 214));
}
if (e.getSource() == backButton){
backButton.setBackground(new Color(253, 214, 214));
}
if (e.getSource() == instructionButton){
instructionButton.setBackground(new Color(253, 214, 214));
}
}
#Override
//returns button color to original when not hovering
public void mouseExited(MouseEvent e) {
if (e.getSource() == playButton){
playButton.setBackground(new Color(255, 115, 115));
}
if (e.getSource() == lvlOneButton){
lvlOneButton.setBackground(new Color(255, 115, 115));
}
if (e.getSource() == lvlTwoButton){
lvlTwoButton.setBackground(new Color(255, 115, 115));
}
if (e.getSource() == lvlThreeButton){
lvlThreeButton.setBackground(new Color(255, 115, 115));
}
if (e.getSource() == backButton){
backButton.setBackground(new Color(255, 115, 115));
}
if (e.getSource() == instructionButton){
instructionButton.setBackground(new Color(255, 115, 115));
}
}
#Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (onInstructions){
g2d.setComposite(AlphaComposite.SrcOver);
g2d.drawImage(instructions, 0, 0, 800, 600, null);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2d.drawImage(fadeRectangle, 0, 0, null);
}
if (onHome){
g2d.setComposite(AlphaComposite.SrcOver);
g2d.drawImage(home, 0, 0, 800, 600, null);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2d.drawImage(fadeRectangle, 0, 0, null);
}
if (onLevels){
g2d.setComposite(AlphaComposite.SrcOver);
g2d.drawImage(levels, 0, 0, 800, 600, null);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2d.drawImage(fadeRectangle, 0, 0, null);
}
super.paint(g);
}
public static void main(String args[]){
JFrame frame = new JFrame();
frame.add(new Frame());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
frame.setResizable(false);
}
}
I tried to put super.paint(g); at the end but that did not fix it. I want to find a way to edit JButton properties in the paintComponent.
learning the basics here.
I just want to know how would I have to arrange the code such that the paint method runs at the beginning of the program and not when you click a button.
or am I forgetting something important?
i know that paint method is automatically called when you set the visibility to true but other than that, im not sure.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Triangle extends JFrame implements ActionListener
{
private JButton b1 = new JButton ("Blue");
private JButton b2 = new JButton ("Red");
private boolean color = true;
public Triangle()
{
setLayout(new FlowLayout());
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setTitle("Triangle");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,400);
setLocation(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
if(color == true)
{
super.paint(g);
g.setColor(Color.white);
g.drawLine(100, 70, 100, 250);
g.drawLine(100, 250, 400, 250);
g.drawLine(100,70,400,250);
getContentPane().setBackground(Color.red);
}
else
{
super.paint(g);
g.setColor(Color.white);
g.drawLine(100, 70, 100, 250);
g.drawLine(100, 250, 400, 250);
g.drawLine(100,70,400,250);
getContentPane().setBackground(Color.BLUE);
}
}
public void actionPerformed(ActionEvent a)
{
if(a.getSource() == b2)
{
color = true;
repaint();
}
else
{
color = false;
repaint();
}
}
}
my paint method was originally like this
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.white);
g.drawLine(100, 70, 100, 250);
g.drawLine(100, 250, 400, 250);
g.drawLine(100,70,400,250);
if(color == true)
{
getContentPane().setBackground(Color.red);
}
else
{
getContentPane().setBackground(Color.BLUE);
}
}
This is a simple class I would like to add to an applet, but how do I do it?
These are the variables being used:
int force = 1;
int distance = 50/force;
int x = distance*60;
int WIDTH = 300 - x;
This is the paint method:
public void paint(Graphics g){
g.setColor(Color.GRAY);
g.drawString("Use the buttons to control the input force", 100, 25);
g.fillRect(300, 250, 300, 25);
g.fillRect(x, 250, WIDTH, 25);
If I should change what method these buttons are located in, please tell me. (Currently are in the paint method)
JButton subtract = new JButton("-");
JButton add = new JButton("+");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
force++;
}
});
subtract.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
force--;
}
});
add.setSize(50, 25);
subtract.setSize(50, 25);
if(force<=0){
force =1 ;
}
add.setLocation(0,0);
subtract.setLocation(51, 0);
LApplet app = new LApplet();
app.add(add);
app.add(subtract);
app.setBackground(Color.BLACK);
}}
Alright, I figured out everything that I got but now I am really stuck. Every time you choose a different shape the previously selected one disappears. How do I make it so they don't disappear and stay on the screen until you exit?
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class ShapeStamper extends JFrame{
Random rand = new Random();
public int x;
public int y;
private JPanel panel1, panel2;
private JButton button1, button2, button3, button4;
private int option = 0;
public ShapeStamper(){
super("Shape Stamper!");
panel1 = new JPanel();
button1 = new JButton("Circle");
button2 = new JButton("Square");
button3 = new JButton("Rectangle");
button4 = new JButton("Oval");
button1.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
option = 1;
}
}
);
button2.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
option = 2;
}
}
);
button3.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
option = 3;
}
}
);
button4.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
option = 4;
}
}
);
panel2 = new JPanel();
panel2.setBackground(Color.WHITE);
MouseHandler mouse = new MouseHandler();
setVisible(true);
addMouseListener(mouse);
addMouseMotionListener(mouse);
add(panel2);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.add(button4);
add(panel1, BorderLayout.SOUTH);
setSize(500,500);
setVisible(true);
}
private class MouseHandler extends MouseAdapter implements MouseMotionListener{
#Override
public void mousePressed(MouseEvent e){
x = e.getX();
y = e.getY();
repaint();
}
}
public void paint(Graphics g){
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
if(option == 0){
g.setFont(new Font("Serif", Font.BOLD, 32));
g.drawString("Shape Stamper!", 150, 220);
g.setFont(new Font("Serif", Font.ITALIC, 16));
g.drawString("Programmed by: Chris", 150, 230);
}
if(option == 1){
Color randColor1 = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
g2d.setPaint(randColor1);
g2d.drawOval(50, 50, 100, 100);
}
if(option == 2){
Color randColor2 = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
g2d.setPaint(randColor2);
g2d.drawRect(50, 50, 100, 100);
}
if(option == 3){
Color randColor3 = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
g2d.setPaint(randColor3);
g2d.draw(new Rectangle2D.Double(75,50,150,100));
}
if(option == 4){
Color randColor4 = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
g2d.setPaint(randColor4);
g2d.draw(new Ellipse2D.Double(50, 25, 100, 50));
}
}
public static void main(String[] args) {
ShapeStamper application = new ShapeStamper();
application.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
You should not be overriding paint of a top level container and then trying to painting over the top of the components you have already added.
The basic problem you will encounter is, the paint system is clever enough that it may not ever call paint of the frame, but simply update the child components directly instead.
Instead, create yourself a custom component, extending from something like JPanel and override it's paintComponent method and perform your custom painting there. Then add this component to your frame.
You will also find the the paint updates are cleaner and won't flicker when updated.
You should also make sure you are calling repaint on this custom component when ever you change one it's options to ensure that changes are painted back to the component
Take a look at Performing Custom Painting for more details.
Also, just to be clear, you should not be calling super.paintComponents from paint (or in fact anywhere except for when you override paintComponents...which there really should be a need to do...)
Hi hope someone can tell me what I am doing wrong with my Key Event.
I am using a Card Layout to navigate through two of my JPanels atm. To do so I use Action Events as well as Key Events. The action events will toggle between JPanels when a button is pressed while the key events will hide away the buttons when a key is pressed. All good with the key events, it does what I want (call a method on one of the panels to set the bounds of the buttons placed inside it eq: button.setBounds(-1, -1, 150, 40); but when I press any of the buttons the key event wont respond despite not having any event on the buttons that I press. Below is my code, for simplicity I removed the non relevant parts of the panels like what they are meant to do.
Thanks in advance and please let me know if I need to provide more clues or to edit the code more, I will try my best to make the code clearer.
public class PanelContainer extends JPanel implements ActionListener, KeyListener{
GamePanel game = new GamePanel();
MainMenuPanel mainMenu = new MainMenuPanel();
CardLayout cards = new CardLayout();
public PanelContainer(){
setLayout(cards);
this.setFocusable(true);
this.addKeyListener(this);
mainMenu.newGameButton.addActionListener(this);
add(mainMenu, "Card1");
add(game, "Card2");
}
#Override
public void actionPerformed(ActionEvent aevt){
cards.show(this, "Card2");
game.action();
}
#Override
public void keyTyped(KeyEvent kevt){
}
#Override
public void keyPressed(KeyEvent kevt){
}
#Override
public void keyReleased(KeyEvent kevt){
if(kevt.getKeyCode() == KeyEvent.VK_ESCAPE || kevt.getKeyChar() == 'O' || kevt.getKeyChar() == 'o'){
game.shw(); //shw() is a method inside GamePanel that sets the bounds of the buttons
}
else if (kevt.getKeyChar() == 'h' || kevt.getKeyChar() == 'H'){game.hid();}
}
}
public class MainMenuPanel extends JPanel
{
private URL workingDir = this.getClass().getResource("imgresources/brick_wall.png") ;
private ImageIcon icon = new ImageIcon(workingDir) ;
private Image img = icon.getImage();
//create and initiate buttons;
JButton newGameButton = new JButton("New Game");
JButton highScoreButton = new JButton("High Scores");
JButton controlsButton = new JButton("Controls");
Point[] points = new Point[1000];
public MainMenuPanel(){
add(newGameButton);
add(highScoreButton);
add(controlsButton);
setPoints();
}
public void setButtonsBounds(){
newGameButton.setBounds(450, 200, 200, 40);
highScoreButton.setBounds(450, 250, 200, 40);
controlsButton.setBounds(450, 300, 200, 40);
}
#Override
public void paintComponent(Graphics g){
try{
super.paintComponent(g);
Graphics2D d2 = (Graphics2D) g;
d2.setColor(new Color(0, 0, 0));
d2.fillRect(0, 0, this.getWidth(), this.getHeight());
setButtonsBounds();
for(int i=0; i<275; i++){
d2.drawImage(img, points[i].x +200, points[i].y, this);
}
}catch(Exception e){}
}
}
public class GamePanel extends JPanel implements Runnable{
JButton button = new JButton("Main Menu");
JButton button2 = new JButton("Exit Game");
void shw(){
add(button);
add(button2);
button.setBounds(400, 200, 150, 20);
button2.setBounds(400, 240, 150, 20);
}
void hid(){
button.setBounds(1, 1, 150, 20);
button2.setBounds(1, 40, 150, 20);
}
}
It's a focus issue. Use Key Bindings instead of a KeyListener so you don't have to worry about this issue (and for other benefits as well -- check the Key Bindings tutorial for details).
Here's my SSCCE that demonstrates what I'm talking about. Note that both KeyListener and key bindings work until you press a button, and then only bindings work:
import java.awt.event.*;
import javax.swing.*;
public class KeyBindingsEg {
private static void createAndShowGui() {
PanelContainer mainPanel = new PanelContainer();
JFrame frame = new JFrame("KeyBindingsEg");
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();
}
});
}
}
#SuppressWarnings("serial")
class PanelContainer extends JPanel {
public PanelContainer() {
this.setFocusable(true);
this.addKeyListener(new MyKeyListener());
JButton newGameButton = new JButton("New Game");
newGameButton.addActionListener(new MyActionListener());
add(newGameButton);
setKeyBindings();
}
private void setKeyBindings() {
Action hideAction = new BindingAction(BindingAction.HIDE);
Action showAction = new BindingAction(BindingAction.SHOW);
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = getInputMap(condition);
ActionMap actionMap = getActionMap();
actionMap.put(BindingAction.HIDE, hideAction);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_H, 0), BindingAction.HIDE);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.SHIFT_DOWN_MASK),
BindingAction.HIDE);
int[] showKeys = { KeyEvent.VK_O, KeyEvent.VK_ESCAPE };
actionMap.put(BindingAction.SHOW, showAction);
for (int key : showKeys) {
inputMap.put(KeyStroke.getKeyStroke(key, 0), BindingAction.SHOW);
inputMap.put(KeyStroke.getKeyStroke(key, KeyEvent.SHIFT_DOWN_MASK),
BindingAction.SHOW);
}
}
private class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent aevt) {
System.out.println("button pressed");
}
}
private class MyKeyListener extends KeyAdapter {
public void keyReleased(KeyEvent kevt) {
if (kevt.getKeyCode() == KeyEvent.VK_ESCAPE
|| kevt.getKeyChar() == 'O' || kevt.getKeyChar() == 'o') {
System.out.println("KeyListener: show");
} else if (kevt.getKeyChar() == 'h' || kevt.getKeyChar() == 'H') {
System.out.println("KeyListener: hide");
}
}
}
private class BindingAction extends AbstractAction {
public static final String HIDE = "Hide";
public static final String SHOW = "Show";
public BindingAction(String text) {
super(text);
putValue(ACTION_COMMAND_KEY, text);
}
#Override
public void actionPerformed(ActionEvent evt) {
String actionCommand = evt.getActionCommand();
if (actionCommand.equals(HIDE)) {
System.out.println("key bindings: hide");
} else if (actionCommand.equals(SHOW)) {
System.out.println("key bindings: show");
}
}
}
}