SwingConstants has same int value for Bottom and East? - java

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?

Related

Correct usage of Recursion

I am just wondering if my usage of recursion is correct. The code works for the intended purpose; however, I am not sure if it is actually doing recursion. I have tried tracing through my program, but I don't understand why my output is correct. Basically, the program takes in a data file of spaces and blobs of '*' and my program is supposed to recursively calculate the number of blobs given a certain row and column in the array of spaces and blobs. The problem is that I am not sure why exactly when I used variables like north, south, east, west, it would be able to successfully return the values to me, as it seems that during recursion, each variable just exists within that call. Also, I am not sure why exactly north = count(row,col+1) would give a value for north, since everytime I iterate through the recursion of count, it doesn't seem to stop at a definite value for north, as in like it doesn't seem to stop and say to return 1 as north.
public static int count(int row, int col) {
int north = 0, south = 0, east = 0, west = 0;
if (map[row][col] == BLOB) {
map[row][col] = MARKED;
if (map[row][col+1] == BLOB) {
north = count(row,col+1);
}
//Go South
if (map[row][col-1] == BLOB) {
south = count(row, col-1);
}
//Go East
if (map[row+1][col] == BLOB) {
east = count(row+1, col);
}
//Go West
if (map[row-1][col] == BLOB) {
west = count(row-1, col);
}
return (1 + north + south + east + west);
}
return 0;
Recursion is just having a method call its self. Therefore, this is recursion.
You are correct in that each variable only exists in the scope of each call. However, they are being defined based off of the other recursive calls.
It seems that this code is trying to fill in an array (and the end case is when the part of the array is filled in). This would be why it seems like it doesn't stop calling its self (as it would take many recursive calls before end cases are met).

JComboBox DropDown list is not displayed

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

Method that maps colors to integers in Java

I am working on my code for my Java class and I can't figure out how to create a method that accepts an int parameter and changes the color based on that int.
The question specifically asks us to:
In your code, map each color to an integer (e.g. in my code 3 means green.) If the number passed to the method is not valid, change the color to red.The valid colors are "red", "yellow", "green", "blue", "magenta" and "black".
In other words, I am trying to select a string color using an integer. How would I go about doing this?
I have tried:
public void changeColor(int newColor)
{
switch(color) {
case 1:
// color1
case 2:
// color2
case 3:
// color3
default:
//defaultcolor
}
draw();
}
And I receive a compiler error saying;
incompatible types: int cannot be converted to java.lang.String
I apologize if I'm not inputting the code correctly. I am very new to programming.
You can use switch on color:
void selectColor(int color) {
switch(color) {
case 1:
// color1
break;
case 2:
// color2
break;
case 3:
// color3
break;
default:
//defaultcolor
}
}
However it would be better to define enum and pass it to this function instead int value.
Few things:
Shouldn't you be using newColor on your switch? (just basing it on your snippet. not too sure if you have another code in between.
Also, Put a break on your cases. Otherwise it will go through every case when applicable
public void changeColor(int newColor) {
switch(newColor) {
case 1:
// color1
break;
case 2:
// color2
break;
case 3:
// color3
break;
default:
//defaultcolor
}
draw();
}
Lastly, Based on your exception (int cannot be converted to java.lang.String), it looks like you are trying to convert an int to a String somewhere on your code. Try to use an Integer rather than the primitive int.
Integer number;
String numberInWords = Integer.toString(number);
instead of
int number;
Hope it helps.

Error loading a new image into a jlabel while I move

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.

Java: GridLayout cells appear to merge

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

Categories

Resources