How to do this?
I want to do this how can I do
public void mousePressed(MouseEvent e){
switch(e.getActionCommand){
case button1: System.out.println("button1 pressed");
break;
case button2: System.out.println("button2 pressed");
break;
case button3: System.out.println("button3 pressed");
break;
case button4: System.out.println("button4 pressed");
break;
case button5: System.out.println("button5 pressed");
break;
}
}
to answer your question let's start by switch/case statement, it can be used with numbers and String in Java. So you need to deal with String when capturing the user interaction in your listener, the solution is: you need to use the method setName(...) on your Swing components and capture that name which is a String in your listener. Look at this example:
public void mousePressed(MouseEvent e){
Component c = (Component) e.getSource();
switch(c.getName()){
case "button1": System.out.println("button1 pressed");
break;
case "button2": System.out.println("button2 pressed");
break;
case "button3": System.out.println("button3 pressed");
break;
case "button4": System.out.println("button4 pressed");
break;
case "button5": System.out.println("button5 pressed");
break;
}
}
But don't forget to use the method setName("buttonX") for each button when you create,because that name you passed in the method must match to one of the names in your switch/case statement.
Related
Could you help me with this little problem?
I'm trying to make a menu system which shows the options in a JEditorPane, it's something like this:
Welcome
Select an option.
1.) New register.
2.) New input.
3.) Exit.
the options are chosen by the user through a JTextField, when "1" is entered it shows another menu:
New register
1.) Option X.
2.) Option Y.
3.) Back.
and so on, the problem is that I don't know how I can capture the user's input, advance to the next menu, and re-capture the user's input all in a JTextField.
textField.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
String cap = "";
cap = textField.getText();
switch(cap) {
case "1":
paintEditorPane("Welcome");
// here is my problem, I don't know how to re-capture JTextField input
switch(cap){
case "1":
paintEditorPane("NewRegister");
break;
}
break;
}
}
});
Here's Basic. Now you have to make many cases to judge states.
public static class MainPanel extends JPanel{
private JTextArea textArea;
public MainPanel() {
this.setLayout(new BorderLayout());
this.textArea = new JTextArea();// you can use constructor to set Text but I like use method "setText".
this.textArea.addKeyListener(new keyHandler());
this.textArea.setText("Welcome\r\nSelect an option. 1.) New register. 2.) New input. 3.) Exit.\r\n");
this.textArea.setCaretPosition(this.textArea.getText().length());// move caret to last
this.add(this.textArea, BorderLayout.CENTER);
}
public void addText(String text) {textArea.setText(textArea.getText() + "\r\n" + text +"\r\n");}
public class keyHandler extends KeyAdapter{
#Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_1 : addText("New register"); break;
case KeyEvent.VK_2 : addText("New input"); break;
case KeyEvent.VK_3 : addText("Exit"); break;
}
}
}
}
I've written a simple KeyListener to recognize Arrow_Left/Right Events.
For some reason my Left-Key is firering 1 VK_LEFT pressed AND 1 VK_RIGHT Event (the Right-Arrow is working normaly)
Does this have to be a Hardware / KeyBoard problem (the arrow keys are working fine) or does one know how to fix this?
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT: {
//left
System.out.println("leftPressed");
keyLeftPressed = true;
}
case KeyEvent.VK_RIGHT: {
//right
System.out.println("rightPressed");
keyRightPressed = true;
}
}
}
The console output on a leftClick is:
leftPressed
rightPressed
On a RightClick:
rightPressed
You forgot break statement on the case statement. If you did not break, the next case will be executed.
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT: {
//left
System.out.println("leftPressed");
keyLeftPressed = true;
break;
}
case KeyEvent.VK_RIGHT: {
//right
System.out.println("rightPressed");
keyRightPressed = true;
break;
}
}
}
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
//left
System.out.println("leftPressed");
keyLeftPressed = true;
break;
case KeyEvent.VK_RIGHT:
//right
System.out.println("rightPressed");
keyRightPressed = true;
break;
}
}
You use switch-case in the wrong way. The parenthesis aren't necessary, but you must add the break-statements.
I have one problem. First - I HAVE AND I WILL HAVE JUST ONE BUTTON.
My problem is: How it can be for each button click different effect-animation.
So, when I first time click on button image goes down, then I second time click image goes from left to right, then I third time click image gone and then it repeat for fourth click image goes down(I can make animation left to right, animation down and then image gone.So I know how to do animation (effects), but I just do not know how to create for every click different effect on image)...
first read about ActioListeners
then simply create a listener that uses a counter!
Each time you click the button the listener increases that counter. And you use different animations based on the current value of the counter. When the "last" animation took place - simply reset the counter to start from scratch.
Here you go
public class ButtonCycle extends JPanel {
private int counter = 0;
public ButtonCycle() {
JButton btn = new JButton("Next");
btn.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseClicked(MouseEvent e) {
switch(counter) {
case 0:
// "Go down"-animation code here
System.out.println("Go down");
counter++;
break;
case 1:
// "Left->right"-animation code here
System.out.println("Left->right");
counter++;
break;
case 2:
// "Disappearing"-animation code here
System.out.println("*poof*, now I'm gone");
counter = 0;
break;
}
}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
});
add(btn);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Button cycling through animations");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(250,250));
f.setContentPane(new ButtonCycle());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
You could utilize the java.util.Random class along with the Random.nextInt() method against values from 1 to 4 within the ActionPerformed event of your Button. Then, depending upon which value is randomly produced run a specific animation method, perhaps through a switch/case or if statements...whatever. Here is an example:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Random rnd = new Random();
int value = (rnd.nextInt(4) + 1);
switch (value) {
case 1:
imageDown();
break;
case 2:
imageLeftRight();
break;
case 3:
imageGone();
break;
case 4:
imageUp();
break;
}
}
Or if you prefer, you could use the Math.random() method., for example:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int value = 4 + (int)(Math.random() * (((1 - 2) - 4) + 1));
switch (value) {
case 1:
imageDown();
break;
case 2:
imageLeftRight();
break;
case 3:
imageGone();
break;
case 4:
imageUp();
break;
}
}
Of course there will be times when the random number generated will be the very much the same as the number generated previously but then again you could use a class field to hold the previous random value and if the currently generated value is the same as the previously generated value then you can generate another within perhaps a do/while loop, for example:
private int previousValue = 0;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int value = 0;
Random rnd = new Random();
do {
value = (rnd.nextInt(4) + 1);
} while (previousValue == value);
previousValue = value;
switch (value) {
case 1:
imageDown();
break;
case 2:
imageLeftRight();
break;
case 3:
imageGone();
break;
case 4:
imageUp();
break;
}
}
I've made a game that is controlled by the arrow keys. Therefore I have a KeyListener listening for the arrow keys:
public void keyReleased(KeyEvent event)
{
switch(event.getExtendedKeyCode())
{
case KeyEvent.VK_UP:
gameManager.up();
break;
case KeyEvent.VK_DOWN:
gameManager.down();
break;
case KeyEvent.VK_RIGHT:
gameManager.right();
break;
case KeyEvent.VK_LEFT:
gameManager.left();
break;
}
}
Now here is my problem:
When I maximize the window using the keyboard by pressing Windows key + Up arrow, these events still get fired. How can I detect that the Windows key has been pressed, while one of the arrow keys got pressed?
Set an flag in your KeyListener, e.g.
boolean windowsPressed;
public void keyPressed(KeyEvent e) {
if(event.getExtendedKeyCode() == VK.WINDOWS) windowsPressed = true;
}
public void keyReleased(KeyEvent event)
{
switch(event.getExtendedKeyCode())
{
case KeyEvent.VK_UP:
if(!windowsPressed) gameManager.up();
break;
case KeyEvent.VK_DOWN:
gameManager.down();
break;
case KeyEvent.VK_RIGHT:
gameManager.right();
break;
case KeyEvent.VK_LEFT:
gameManager.left();
break;
case KeyEvent.VK_WINDOWS:
windowsPressed = false;
break;
}
}
You can catch the window key in your keyreleased
case: KeyEvent.VK_WINDOWS:
//do nothing
so it wont register the up button when you pressed the window + up
Is it a keyboard limitation problem?
I'm having an issue with some code I'm just playing around with. Imagine a top down space shooter. The issue I'm having is that, on my computer, when I press and hold the up and left arrows, I cannot shoot (Spacebar). Any other direction (up, down, left, right, up + right, right + down, left + down) works. I had a friend run the code on his computer and he found that all directions worked except up + right and right + down, but up + left worked fine for him. We both looked at the code and can't figure it out. Could this be a hardware issue?
Basically, this is what I'm doing:
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame
{
boolean up, down, left, right, fire;
// Main constructor
public Test()
{
// listeners for user input
this.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
{
up = true;
break;
}
case KeyEvent.VK_LEFT:
{
left = true;
break;
}
case KeyEvent.VK_RIGHT:
{
right = true;
break;
}
case KeyEvent.VK_DOWN:
{
down = true;
break;
}
case KeyEvent.VK_SPACE:
{
fire = true;
break;
}
case KeyEvent.VK_ESCAPE:
{
// Exit
System.exit(0);
}
}
}
public void keyReleased(KeyEvent e)
{
// Upon releasing key, stop direction
switch(e.getKeyCode())
{
case KeyEvent.VK_UP:
{
up = false;
break;
}
case KeyEvent.VK_LEFT:
{
left = false;
break;
}
case KeyEvent.VK_RIGHT:
{
right = false;
break;
}
case KeyEvent.VK_DOWN:
{
down = false;
break;
}
}
}
});
}
public static void main(String[] args)
{
// create frame
Test test = new Test();
test.setLocationRelativeTo(null);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
test.loop();
}
public void loop()
{
Timer timer = new Timer(250, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (up)
System.out.println("Moving UP.");
if (left)
System.out.println("Moving LEFT.");
if (right)
System.out.println("Moving RIGHT.");
if (down)
System.out.println("Moving DOWN.");
if (fire)
{
System.out.println("FIRING.");
fire = false;
}
}
});
timer.start();
}
}
This question was originally asked here.
Yes, it looks like a hardware limitation. You can try to check whether it behaves the same way in other programs, if yes, it's definitely a hardware issue.
Keyboards have these kinds of limitations, see Rollover (key).