Java: GridLayout cells appear to merge - java

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

Related

How do I make a selected Combobox value display different text?

I am new to Java and couldn't find any answers for my problem that I was able to understand.
I want to make a selected value in my ComboBox change what text is displayed in the textfield.
For example, if the user selects an artist in the combobox, then the artists' albums are displayed in the textfield.
Any help is appreciated. Thanks!
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
String a = (String)jComboBox1.getSelectedItem();
int artists = 0;
switch (artists){
case 0: jTextField1.setText("Take Care, Nothing Was The Same, Views, More Life, Scorpion");
break;
case 1: jTextField1.setText("Stoney, Beerbongs & Bentleys");
break;
case 2: jTextField1.setText("One Love, Listen, Nothing But the Beat");
break;
case 3: jTextField1.setText("Ready for the Weekend, 18 Months, Motion");
break;
case 4: jTextField1.setText("Cole World: The Sideline Story, 2014 Forest Hills Drive, 4 Your Eyez Only");
break;
case 5: jTextField1.setText("My Beautiful Dark Twisted Fantasy, Yeezus, The Life of Pablo, ye");
break;
case 6: jTextField1.setText("Parachutes, a Rush of Blood to the Head, X&Y, Viva La Vida, Mylo Xyloto");
}
}
Here is a full working example:
import java.awt.GridLayout;
import javax.swing.*;
public class ChangeTextViaCheckbox extends JFrame {
public ChangeTextViaCheckbox() {
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 1));
JCheckBox cb1 = new JCheckBox("Checkbox 1");
JCheckBox cb2 = new JCheckBox("Checkbox 2");
JTextField tf = new JTextField();
cb1.addActionListener(e -> tf.setText("CB 1 is active"));
cb2.addActionListener(e -> tf.setText("CB 2 is active"));
add(cb1);
add(cb2);
add(tf);
}
public static void main(String[] args) {
ChangeTextViaCheckbox frame = new ChangeTextViaCheckbox();
frame.pack();
}
}
The both ActionListener listen on a performed action. If thats the case, they set a new Text in the JTextField.
But it would be better, if you implement it via JRadioButton and a ButtonGroup. With this there can't be a multiple choice.
Your question is lacking details and examples, you should post the important parts of your code that you've already written, for example I have no idea now what [GUI] API are you using(for example swing or AWT), so I strongly advise you to edit your question and provide more details, but either way I'm going to give you a simple example.
I'm going to assume your using the swing api, but it shouldn't be that different if your using another GUI api (like AWT).
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingExample extends JFrame{
public SwingExample(){
String[] artists = {"artist1","artist2","artist3"};
Map<String,String> albumOfArtists = new HashMap<String,String>();
albumOfArtists.put("artist1","album1");
albumOfArtists.put("artist2","album2");
albumOfArtists.put("artist3","album3");
JComboBox combo1 = new JComboBox<String>(artists);
JTextField field1 = new JTextField();
//You implement an action listener to define what should be done when
//an user performs certain operation. An action event occurs,
//whenever an action is performed by the user. Examples: When the user
//clicks a button, chooses a menu item, presses Enter in a text field.
//add action listener to your combobox:
combo1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String selectedString=(String)combo1.getSelectedItem();
field1.setText(albumOfArtists.get(selectedString));
//for example if you select artist1 then the text displayed in the text field is: album1
}
}
add(combo1);
add(field1);
}
private static void createAndShowGUI() {
JFrame frame = new CreateNewJTextField();
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
You can use switch() for your combobox. I've written a code which has the name defined to combobox as cb1. The getSelectedItem() method is used for cb1. You can define the corresponding command for each case (starting from index 0).
String a = (String)cb1.getSelectedItem();
int i = 0;
switch (i){
case 0:
break;
}
Make sure to end each case with break; or your code will execute repeatedly.
Now if the textfield you're using is t1 then the following code is generalised,
switch (i) {
case 0: t1.setText(<whatever you want to display>);
break;
}
Hope this helps.
Here's the revisited code:
String a = (String)cb1.getSelectedItem();
int i = 0;
switch(i){
case 0: t1.setText("Take Care, Nothing Was The Same, Views, More Life, Scorpion");
// for combobox option Drake index = 0
break;
case 1: t1.setText("Stoney, Beerbongs & Bentleys");
// for combobox option post_malone index = 1
break;
case 2: t1.setText("One Love, Listen, Nothing But the Beat");
// for combobox option david_guetta
break;
}
switch is a selection statement that successively tests the value of an expression against alist of integers or characters constants. When a match is found, the statements associated with that constant are executed. Here, the variable i is the expression(the option you choose from combobox) which is evaluated.
Hope this helps again!

SwingConstants has same int value for Bottom and East?

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?

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

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.

Type of an ArrayList for Combobox and TextFields

I have an ArrayList<JTextField> that has N positions. However, I have to make a change, I need to add a JComboBox to that array so my question is:
What type of data do I need to declare on my ArrayList?
I've tryed with an ArrayList<Object> and ArrayList<JComponent> but it doesn't work because the lines, where I set the horizontal alignment report errors.
private ArrayList<JTextField> jTextFieldAL;
for (int i = 0; i < size; i++) {
jLabelAL.add(new JLabel("" + tagNamesAL.get(i)));
if (tagNamesAL.get(i).equals("AGENT_NAME")) {
jTextFieldAL.add(new tools.AgentNameTextField());
jTextFieldAL.get(i).setHorizontalAlignment(SwingConstants.RIGHT);
} else {
switch (tagContentAL.get(i).toString().toLowerCase()) {
case "int":
jTextFieldAL.add(new tools.IntegerTextField(this.simul));
jTextFieldAL.get(i).setHorizontalAlignment(SwingConstants.RIGHT);
break;
case "double":
case "float":
jTextFieldAL.add(new tools.DoubleTextField(this.simul));
jTextFieldAL.get(i).setHorizontalAlignment(SwingConstants.RIGHT);
break;
default:
jTextFieldAL.add(new JTextField());
jTextFieldAL.get(i).setHorizontalAlignment(SwingConstants.RIGHT);
break;
}
}
jTextFieldAL.get(i).addKeyListener(keyEvent);
p1.add(jLabelAL.get(i));
p1.add(jTextFieldAL.get(i));
}
I've tryed with an ArrayList and ArrayList but it doesn't work because the lines, where I set the horizontal alignment report errors : this is expected because Object/JComponent does not have setHorizontalAlignment method.
So you need to down caste it to JTextField and than call this API.
I am not sure if this is a good idea to use, as to down caste the object, you need to know at each index what type is the actual type of the object stored(JTextFild or JComboBox), otherwise you will land up with ClassCasteException.
I've found a solution to my problem. I don't need to add the ComboBox to the ArrayList. I just add the ComboBox directy to the panel.
Like this:
for (int i = 0; i < size; i++) {
jLabelAL.add(new JLabel("" + tagNamesAL.get(i)));
if (tagNamesAL.get(i).equals("BEHAVIOUR")){
addCSPComboBox(p1);
break;
}
And the addCSPComboBox method:
public void addCSPComboBox(JPanel p1){
CSPComboBox cspComboBox = new tools.CSPComboBox();
JLabel behaviour = new JLabel("BEHAVIOUR");
p1.add(behaviour);
p1.add(cspComboBox);
}
This works just fine for my problem. I hope I can help anyone with the same problem ;)

Categories

Resources