switch(arg0.getKeyCode()) {
//if keycode is 'd' key
case 68:
break;
case 65:
System.out.println("stuff for left key using a");
break;
case 87:
shark.MoveUp();
break;
case 38:
shark.MoveUp();
break;
case 82:
new Game();
break;
}
So Game is the name of the class. This is not the JFrame. When I try calling the jframe, it does not recognize it. When I press "R", it creates a new game but it does not get rid of the old game. When the old game runs in the background, the new game becomes unplayable due to lag. How do I delete the old Game that is running and just run the new one I started in case 82?
i'd highly recommend on using JFrame.dispose() ONthe old Game as long as it expanding JFrame. If not you can add a method to the Game class that will dispose the JFrame it contains. A method as such will look like that:
JFrame frame = new JFrame("game");//Lets assume thats your frame in Game
//that should be your method inside of Game class:
public void gameDispose(){
if(frame != null)
frame.dispose();
}
Now the only problem you may be in is not being able to call this dispose method since your Game is not inside of a variable. Therefore when Game is created it should happen inside of a variable as follow:
Game g = new Game();//Just for understaning of g variable.
Later when needed call your method.
Therefor your code should look like this:
Game g = new Game();
switch(arg0.getKeyCode()) {
//if keycode is 'd' key
case 68:
break;
case 65:
System.out.println("stuff for left key using a");
break;
case 87:
shark.MoveUp();
break;
case 38:
shark.MoveUp();
break;
case 82:
g.dispose().
g = new Game()
break;
}
Related
I know it is said in the document that JFrame.setDefaultCloseOperation(int) is HIDE_ON_CLOSE. But when I press the X on current frame window, not only does it hide the current frame but also terminate the running program. Can anyone explain?
Edit: The closing frame is not the last frame left.
Is it true that JFrame.setDefaultCloseOperation() default value is HIDE_ON_CLOSE?
Run this method on the frame.
public static void showDefaultCloseOperation(JFrame frame) {
final int closeOp = frame.getDefaultCloseOperation();
switch (closeOp) {
case JFrame.DO_NOTHING_ON_CLOSE:
System.out.println("DO_NOTHING_ON_CLOSE");
break;
case JFrame.HIDE_ON_CLOSE:
System.out.println("HIDE_ON_CLOSE");
break;
case JFrame.EXIT_ON_CLOSE:
System.out.println("EXIT_ON_CLOSE");
break;
case JFrame.DISPOSE_ON_CLOSE:
System.out.println("DISPOSE_ON_CLOSE");
break;
default:
System.err.println("Not found: " + closeOp);
}
}
Here it prints:
HIDE_ON_CLOSE
So the answer to that is: yes, it is true.
Here at least. What result do you get on the local machine / environment?
What I want is that press the " A", " S ", "D " and " W " the character move in their respective directions keys.
The problem is that every time I change direction , I change the image of JLabel ( it is an arrow ) .
It really works well but every time the image is changed, the JLabel back for a second to its default position . Then the JLabel continues from where it was.
Here is the code.
private int pX;
private int pY;
public MovePj() {
initComponents();
pX=labelPj.getX();
pY=labelPj.getY(); }
private void formKeyPressed(KeyEvent evt) {
switch(evt.getKeyCode()){
case 87: //Norte
pY=pY-movimiento;
labelPersonaje.setIcon(new ImageIcon(rutaBase+"Imagenes\\movement\\07-north.png"));
break;
case 83: //Sur
pY=pY+movimiento;
labelPersonaje.setIcon(new ImageIcon(rutaBase+"Imagenes\\movement\\03-sur.png"));
break;
case 68: //Este
pX=pX+movimiento;
labelPersonaje.setIcon(new ImageIcon(rutaBase+"Imagenes\\movement\\01-east.png"));
break;
case 65: //Oeste
pX=pX-movimiento;
labelPersonaje.setIcon(new ImageIcon(rutaBase+"Imagenes\\movement\\05-west.png"));
break;
default:
break;
}
labelPersonaje.setLocation(pX, pY);
//labelPj.setBounds(pX, pY, labelPj.getWidth(), labelPj.getHeight());
}
The character moves correctly, but to change the image of JLabel , this returns to the preset point.
Thanks.
The setIcon(...) method will invoke:
revalidate();
repant();
on the label which causes the layout manager to be invoked. So I would guess you need to use:
panel.setLayout( null );
to prevent the size/location of the label from being recalculated. You would do this when you create the panel.
Also, it is not a good idea to read the images in response to the KeyEvent. You should read the images when the class is loaded for better performance.
I am a student of very basic Java. We did an assignment to make the background color change according to the radio button selected using several if statements. That worked fine. I decided to change the selection process to a combobox and use a switch case. It seems to me the process is failing the if statement in the switch case method. I'm trying to get a better understanding of how things work. The code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Lab17_4combo extends JFrame implements ActionListener
{
Container container;
JComboBox colors;
public Lab17_4combo()
{
super("ComboBox ");
container = this.getContentPane();
container.setLayout(new FlowLayout());
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] selectColor = {"Red", "Yellow", "Blue", "Green", "Magenta"};
JComboBox colors = new JComboBox(selectColor);
colors.setSelectedIndex(-1);
colors.addActionListener(this);
container.add(colors);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
int chgColor;
if(e.getSource() == colors)
{
chgColor = colors.getSelectedIndex();
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
case 1:
container.setBackground(Color.yellow);
case 2:
container.setBackground(Color.blue);
case 3:
container.setBackground(Color.green);
case 4:
container.setBackground(Color.magenta);
}
}else
{
container.setBackground(Color.magenta);
}
}
public static void main(String[] args)
{
Lab17_4combo s = new Lab17_4combo();
}
}
I put in the else to check if it was failing the if. I'm assuming that is where the problem is, but I don't know how to fix it. Any help would be greatly appreciated. The original assignment has been completed, this is my own experimentation. I'm not asking for anyone to do my homework for me. Cheers
EDIT--
I have made the suggested changes to the code (Thanks to all for the suggestions). The background color of the container still does not change regardless of the selection I make from the combobox. I'm assuming there are mistakes elsewhere in the code, but I'm at a loss to find them. My expectation is that the background color of the container will change according to the selection I make from the combobox. This is not happening.
The revised code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Lab17_4combo extends JFrame implements ActionListener
{
Container container;
JComboBox colors;
public Lab17_4combo()
{
super("ComboBox ");
container = this.getContentPane();
container.setLayout(new FlowLayout());
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] selectColor = {"Red", "Yellow", "Blue", "Green", "Magenta"};
JComboBox colors = new JComboBox(selectColor);
colors.setSelectedIndex(-1);
colors.addActionListener(this);
container.add(colors);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
int chgColor;
if(e.getSource() == colors)
{
chgColor = colors.getSelectedIndex();
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
case 2:
container.setBackground(Color.blue);
break;
case 3:
container.setBackground(Color.green);
break;
case 4:
container.setBackground(Color.magenta);
break;
}
}
}
public static void main(String[] args)
{
Lab17_4combo s = new Lab17_4combo();
}
}
With my limited knowledge of Java I'm not able to see where the mistake(s) may be. Any help would be appreciated.Cheers
You forgot the break statement after each case
Try this:
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
case 2:
container.setBackground(Color.blue);
break;
case 3:
container.setBackground(Color.green);
break;
case 4:
container.setBackground(Color.magenta);
break;
default:
//You may add a default case here.
}
EDIT:-
I think your condition
if(e.getSource() == colors)
is never true thats why you are getting this problem. You may try to compare like this:
if(e.getSource().equals(colors))
Always use .equals method when you are comparing objects.
As mentioned in my comment you forgot to add break in each of your case.
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
case 2:
container.setBackground(Color.blue);
break;
case 3:
container.setBackground(Color.green);
break;
case 4:
container.setBackground(Color.magenta);
break;
default:
//What if none of above condition is satisfied.
}
Edit: - Check the comments in the code
class Lab17_4combo extends JFrame implements ActionListener
{
Container container;
JComboBox colors;// you declared colors.
public Lab17_4combo()
{
super("ComboBox ");
container = this.getContentPane();
container.setLayout(new FlowLayout());
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] selectColor = {"Red", "Yellow", "Blue", "Green", "Magenta"};
//JComboBox colors = new JComboBox(selectColor);// You declared colors again. Change this line to
colors = new JComboBox(selectColor);
colors.setSelectedIndex(-1);
colors.addActionListener(this);
container.add(colors);
setVisible(true);
}
You should use break after each case.
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
....
You need to make sure and add a break; after every line in the case, like this:
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
case 2:
container.setBackground(Color.blue);
break;
case 3:
container.setBackground(Color.green);
break;
case 4:
container.setBackground(Color.magenta);
break;
}
}else
{
container.setBackground(Color.magenta);
}
Looks like you always end up with magenta color given the if condition and the switch statement.
Use break for each case statement.
In the switch statement, for each case, you do not have a break;. So even if switch finds a valid matching case, it executes that case and, in your code (since you do not break the control to come out of that case), it eventually passes the control to the cases following the matching case and always ending up in the last case.
First, I am new to programming and this is my first major assignment in java and programming in general so if I am doing some incredibly stupid please tell me so I can correct the bad habit.
Anyway to the problem, I am currently trying to create a gridLayout that has a variable number of rows which will be filled with a label that has text that comes from a file. My problem is specifically on gridLayout were the labels that I do add and are constants seem to be disappearing into one giant cell. So far none of the reasearch I have done has lead to anything so I thought I may as well pose the question.
public void fillTimetablePane(JPanel pane){
int noOfRows = pref.getNoOFPeriods()+1;
pane.setLayout(new GridLayout(noOfRows,4));
pane.setBorder(BorderFactory.createLineBorder(Color.black));
JLabel label = new JLabel();
int i=0;
while (i<4){
switch (i) {
case 0: label.setText("Lesson");
break;
case 1: label.setText("Period");
break;
case 2: label.setText("Room");
break;
case 3: label.setText("Teacher");
break;
}
i++;
pane.add(label);
}
}
here is an image of what happens when I add run the following code:
http://www.freeimagehosting.net/1hqn2
public void fillTimetablePane(JPanel pane){
int noOfRows = pref.getNoOFPeriods()+1;
pane.setLayout(new GridLayout(noOfRows,4));
pane.setBorder(BorderFactory.createLineBorder(Color.black));
//JLabel label = new JLabel(); // from here
int i=0; // V
while (i<4){ // V
JLabel label = new JLabel(); // to here
switch (i) {
case 0: label.setText("Lesson");
break;
case 1: label.setText("Period");
break;
case 2: label.setText("Room");
break;
case 3: label.setText("Teacher");
break;
}
i++;
pane.add(label);
}
}
Ok, why is it not working in your case but works fine in my case? The problem is that you add your label 4 times and change the text inbetween. In a Layout, a single component can only be existing once. So what happens is that when you add your label a second/third/fourth time, its location in the grid will be updated and not added again.
In my case, I actually create a new JLabel in every iteration of the loop and therefore adding a different label to the JPanel.
Hope this is clear enough. Just ask if something is not clear.
You added the same label 4 times. Move the new JLabel inside your while loop
I am a self taught programmer, so I do not know the proper ways to do things. I have made simple games like asteroids and snake, but in those games, you can easily modify the variables within the keyevent functions. Here is how I did it in my simple Asteroids game:
/*
* key listener events
*/
public void keyReleased(KeyEvent k){
int keyCode = k.getKeyCode();
switch(keyCode){
case KeyEvent.VK_LEFT:
turnLeft = false;
break;
case KeyEvent.VK_RIGHT:
turnRight = false;
break;
case KeyEvent.VK_UP:
accel = false;
break;
case KeyEvent.VK_1:
cls = true;
break;
case KeyEvent.VK_ENTER:
break;
case KeyEvent.VK_SPACE:
fire = false;
}
}
public void keyTyped(KeyEvent K){}
public void keyPressed(KeyEvent k){
int keyCode = k.getKeyCode();
switch(keyCode){
case KeyEvent.VK_LEFT:
turnLeft = true;
break;
case KeyEvent.VK_RIGHT:
turnRight = true;
break;
case KeyEvent.VK_UP:
accel = true;
break;
case KeyEvent.VK_1:
cls = false;
break;
case KeyEvent.VK_ENTER:
clearAllBullets();
break;
case KeyEvent.VK_SPACE:
fire = true;
}
}
If I were to make a more advanced game (with a main menu, options, main game, etc.) How should I do the key/mouse input?
Also, if I were to go into the single-player, should I put all of the gameplay code into one class? Is there a way to put the single player code into a separate class and somehow have the key input still modify the variables and such?
Thank you for your time!
P.S. Any links or source is extremely appreciated. :D
"Is there a way to put the single player code into a separate class and somehow have the key input still modify the variables and such?"
Yes, there is way to encapsulate all event-based behaviours- http://en.wikipedia.org/wiki/Mediator_pattern but, it can make yor code very complicated, so firstly try to implement your game in more "normal" way.
Anyway - you will need other classes, to present domain model of your game (Player, Gameboard, UserInterfaces etc...)