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.
Related
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;
}
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?
While trying to get the horizontal alignment of a given JLabel, i noticed that SwingConstants.TOP has the same numeric int value as SwingConstants.NORTH (both are 1), but SwingConstants.BOTTOM has the same int value SwingConstants.EAST (both 3) instead of SwingConstants.SOUTH (5) !
if (c instanceof JLabel) {
JLabel tempLabel = (JLabel) c;
//for meaning of values see javax.swing.SwingConstants.
switch (tempLabel.getVerticalAlignment()) {
case 0:
output = VERTICAL_ALIGNMENT.CENTER;
break;
case 1:
output = VERTICAL_ALIGNMENT.TOP;
break;
case 3: //Bottom but also east instead of south!
output = VERTICAL_ALIGNMENT.BOTTOM;
break;
default:
//use default value setting
}
}
I wanted to make cases for all lower vertical alignments to (be it BOTTOM, SOUTH, SOUTH_EAST, SOUTH_WEST) to return VERTICAL_ALIGNMENT.BOTTOM - but the int values of those constants do not have the expected consistency. How can i solve this best, and maybe also why are they defined in this strange way?
this might be a duplicate of JComboBox popup menu not appearing , but as it is a rather old question and not been active for quite some time, plus all the answers were not solutions, that helped with my problem. Thus I decided to create a new question.
The Problem is as follows:
I got an application of a prior colleque, that does not work at my company anymore. Now I tried adding a JComboBox to a JPanel. The JCombobox is displayed as expected, but it behaves in the same way as described by Seth in his question:
1) The first click on the expand button does nothing. The second click highlights the contents of the box, but the popup still doesn't appear.
2) Once I've clicked the button and given it focus, up/down keystrokes cycle through the entries correctly.
I have broken down the code to what I think is the minimum of needed programming, to have the problem occur. (As one comment in the mentioned question mentioned to provide SSCCE, which never happened).
Now here is the code I can provide:
public static class CreateProjectDialog extends JFrame {
private Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
public CreateProjectDialog() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
int SZ_INCR = 1;
// Passe Fontgröße an Resolution an:
if (size.width > 1920) {
SZ_INCR = 2;
}
// Initialize Glass Layer
final JPanel panelGlass = (JPanel) getGlassPane();
panelGlass.setLayout(null);
panelGlass.setVisible(true);
private static JPanel licBorrowPanel = null;
licBorrowPanel = new JPanel();
licBorrowPanel.setBounds(0, 20, 1000, 500);
licBorrowPanel.setVisible(false);
licBorrowPanel.setBackground(Color.WHITE);
panelGlass.add(licBorrowPanel);
}
public static void main(String[] args) {
hauptFrame = new CreateProjectDialog();
}
public static void licenceBorrowDialog() {
int mainWidth = hauptFrame.getSize().width;
int mainHeight = hauptFrame.getSize().height;
// pick a Date
JComboBox dayList = new JComboBox();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar calToday = Calendar.getInstance();
Date dayToday = calToday.getTime();
int weekDay = calToday.get(Calendar.DAY_OF_WEEK);
String weekDayName = "";
for (int i = 1; i <= 22; i++){
dayToday.setDate(dayToday.getDate()+1);
weekDay = dayToday.getDay();
weekDayName = translateWeekDay(weekDay);
dayList.addItem(i + " day(s) until " + weekDayName + " " + df.format(dayToday));
}
dayList.setOpaque(true);
dayList.setSelectedIndex(2);
dayList.setBounds(mainWidth / 2 - (125*SZ_INCR), (165*SZ_INCR), (250*SZ_INCR), (100*SZ_INCR));
licBorrowPanel.add(dayList);
dayList.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int numberOfDays;
JComboBox dl = (JComboBox)e.getSource();
numberOfDays = dl.getSelectedIndex()+1;
labelSelectedDate.setText("<HTML><BODY><b>Count of days: </b>" + numberOfDays + "</HTML></BODY>");
}
});
}
//Translate weekday int to name
public static String translateWeekDay(int day){
String retDay;
switch (day) {
case 0: retDay = "Monday";
break;
case 1: retDay = "Truesday";
break;
case 2: retDay = "Wednesday";
break;
case 3: retDay = "Thursday";
break;
case 4: retDay = "Friday";
break;
case 5: retDay = "Saturday";
break;
case 6: retDay = "Sunday";
break;
default: retDay = "Invalid day";
break;
}
return retDay;
}
}
I tried popoulating with more items (as proposed by jluzwick) to see, if the DropDown is simply hidden behind anything, but no.
I definitely have never used getRootPane() instead of getContentPane(), as suspected by Sehtim.
There is also JCombobox is not displayed , where the accepted answer is to set the setVisible(true) to the end of the constructor. I tried that and it did not change any behaviour in my case.
The question I need an answer to, is: How do I make the DropDown list visible, to enable the user to easily choose an entry?
Thanks MadProgrammer for the hint regarding the code not compiling - I found a solution and will provide it here for anyone having a similar issue.
The problem was a result of mixing heavy weight and light weight components (awt / swing).
This resulted in the light weight popup being used, which was then probably occluded by other components and thus not visible.
The solution ( if the mix of both heavy and light weight has to stay ) is to disable the light weight popup forcing the application to use a backup popup. This is done by replaceing the following line:
dayList.setSelectedIndex(2);
With this line:
dayList.setLightWeightPopupEnabled (false);
I found the solution here:
http://de.comp.lang.java.narkive.com/t2GPS9vy/jcombobox-poppt-nicht-auf
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