So I want to replace an ImageIcon in a JLabel every time a button is pressed. I made it so the image, label, and GridBagConstraints are public. When I try to change it though nothing happens.
Am I going about this the wrong way or?
Thanks!
package hi.low;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class Card_panel extends JPanel implements ActionListener
{
private final int WIDTH = 400, HEIGHT = 200;
private static String[] imageList = {
"images/2h.png", "images/3h.png", "images/4h.png", "images/5h.png", "images/6h.png",
"images/7h.png", "images/8h.png", "images/9h.png", "images/th.png", "images/jh.png",
"images/qh.png", "images/kh.png", "images/ah.png", "images/2d.png", "images/3d.png",
"images/4d.png", "images/5d.png", "images/6d.png", "images/7d.png", "images/8d.png",
"images/9d.png", "images/td.png", "images/jd.png", "images/qd.png", "images/kd.png",
"images/ad.png", "images/2c.png", "images/3c.png", "images/4c.png", "images/5c.png",
"images/6c.png", "images/7c.png", "images/8c.png", "images/9c.png", "images/tc.png",
"images/jc.png", "images/qc.png", "images/kc.png", "images/ac.png", "images/2s.png",
"images/3s.png", "images/4s.png", "images/5s.png", "images/6s.png", "images/7s.png",
"images/8s.png", "images/9s.png", "images/ts.png", "images/js.png", "images/qs.png",
"images/ks.png", "images/as.png"
};
private static int imageNum = -1;
GridBagConstraints gbc = new GridBagConstraints();
GridBagConstraints c = new GridBagConstraints();
ImageIcon image;
JLabel label;
private static ArrayList<Card> deck;
private static Card tempCard, currentCard;
public Card_panel()
{
deck = new ArrayList();
char[] suits = {'h', 'd', 'c', 's'};
char[] values = {'2', '3', '4', '5', '6', '7', '8', '9', 't', 'j', 'q', 'k', 'a'};
for(int a = 0; a<suits.length; a++)
{
for(int b = 0; b<values.length; b++)
{
tempCard = new Card(suits[a],values[b]);
deck.add(tempCard);
}
}
int rand_num;
int cards_left = 52;
Random generator = new Random( System.currentTimeMillis() );
for(int a = 0; a<52; a++)
{
rand_num = generator.nextInt(cards_left);
currentCard = deck.get(rand_num);
deck.remove(rand_num);
cards_left -= 1;
}
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground (Color.green.darker().darker());
setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
image = new ImageIcon(imageList[0]);
label = new JLabel("", image, JLabel.CENTER);
add( label, gbc );
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 1;
JButton higher = new JButton("Higher");
higher.setActionCommand("higher");
higher.addActionListener (this);
add( higher, gbc );
gbc.gridx++;
JButton lower = new JButton("Lower");
lower.setActionCommand("lower");
lower.addActionListener (this);
add( lower, gbc );
}
#Override
public void actionPerformed(ActionEvent e)
{
String Action;
Action = e.getActionCommand ();
if (Action.equals ("higher"))
{
System.out.println("User chose higher!");
//function to check if it is right if right go to next card
image = new ImageIcon(imageList[1]);
label = new JLabel("", image, JLabel.CENTER);
add( label, gbc );
}
if (Action.equals ("lower"))
{
System.out.println("User chose lower!");
//function to check if it is right if right go to next card
}
}
}
Rather then trying to create and add a new label each time, simply call setIcon on the label itself
Something more like...
image = new ImageIcon(imageList[1]);
label.setIcon(image);
Check out How to use lables for more details.
I might also suggest that you load the images first, so you don't need to keep reloading them/creating new objects on each actionPerformed
I'd also recommend ImageIO over ImageIcon
Related
I am overriding the actionListener. All of the buttons besides "playbutton" have an image attached as an icon (button1, button2, button3). Every time a button is pressed, it should compare its icon to the prepared ImageIcon "livePicture" and if they are the same, it should go with the "Escaped()" method. Otherwise, the program will run the "Died()" method.
However, at least with the current code, it only uses "Died()". This, I guess, means that there is something wrong with the ifs that compare the images, but that is the only way of comparison I found on the internet.
Also, keep in mind that this is my first project, so it may seem a little cluttered.
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Vector;
public class Frame
{
private final int WIDTH = 1024;
private final int HEIGHT = 768;
private JFrame frame;
private JPanel panel;
private JLabel human;
private JTextArea text;
private JTextArea deathMessage;
private ImageIcon livePicture;
private JButton button1;
private JButton button2;
private JButton button3;
private GridBagConstraints gbc;
private ActionListener actionListener;
private JButton playButton;
private Border border = BorderFactory.createEmptyBorder();
private Font font = new Font(Font.MONOSPACED, Font.PLAIN, 20);
public Frame()
{
Quest survival = new Quest();
actionListener = e -> {
if (e.getSource() == playButton) //playbutton works fine
{
if (!survival.IsEmpty())
{
AppendQuest(survival.GetQuest());
survival.RemoveQuest();
}
else
{
Escaped();
}
}
else if (e.getSource() == button1) //button1 action
{
if (button1.getIcon().toString() != livePicture.toString())
{
Died();
}
else
{
if (!survival.IsEmpty())
{
AppendQuest(survival.GetQuest());
survival.RemoveQuest();
}
else
{
Escaped();
}
}
}
else if (e.getSource() == button2) //button2 action
{
if (button2.getIcon().toString() != livePicture.toString())
{
Died();
}
else
{
if (!survival.IsEmpty())
{
AppendQuest(survival.GetQuest());
survival.RemoveQuest();
}
else
{
Escaped();
}
}
}
else if (e.getSource() == button3) //button3 action
{
if (button3.getIcon().toString() != livePicture.toString())
{
Died();
}
else
{
if (!survival.IsEmpty())
{
AppendQuest(survival.GetQuest());
survival.RemoveQuest();
}
else
{
Escaped();
}
}
}
};
//I left the rest of the constructor for bonus info
frame = new JFrame();
panel = new JPanel();
gbc = new GridBagConstraints();
human = new JLabel(ImageSize(200, 200, "res/human.png"));
text = new JTextArea("You have lost in the forest. Now you have to find " +
"your way back.");
FormatText(text);
deathMessage = new JTextArea();
frame.setTitle("Shady Path");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.getContentPane().setBackground(Color.BLACK);
frame.setResizable(false);
playButton = new JButton();
playButton.addActionListener(actionListener);
playButton.setFont(font);
playButton.setText("Play");
playButton.setForeground(Color.WHITE);
playButton.setBackground(Color.BLACK);
playButton.setBorder(border);
panel.setLayout(new GridBagLayout());
panel.setOpaque(false);
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(human, gbc);
gbc.insets = new Insets(30, 0, 0, 0);
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(text, gbc);
gbc.fill = GridBagConstraints.VERTICAL;
gbc.insets = new Insets(50, 0, 68, 0);
panel.add(playButton, gbc);
frame.add(panel);
frame.setVisible(true);
}
public void AppendQuest(Vector<String> event)
{
panel.removeAll();
panel.add(human, gbc);
gbc.insets = new Insets(0, 0, 30, 0);
text.setText(event.remove(0));
FormatText(text);
panel.add(text, gbc);
deathMessage.setText(event.remove(0));
FormatText(deathMessage);
livePicture = ImageSize(50, 50, event.remove(0));
Collections.shuffle(event);
ImageIcon picture1 = ImageSize(50, 50, event.get(0)); //setting button1
button1 = new JButton();
button1.addActionListener(actionListener);
button1.setIcon(picture1);
button1.setBorder(border);
ImageIcon picture2 = ImageSize(50, 50, event.get(1)); //setting button2
button2 = new JButton();
button2.addActionListener(actionListener);
button2.setIcon(picture2);
button2.setBorder(border);
ImageIcon picture3 = ImageSize(50, 50, event.get(2)); //setting button3
button3 = new JButton();
button3.addActionListener(actionListener);
button3.setIcon(picture3);
button3.setBorder(border);
gbc.gridwidth = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(50, 360, 100, 0);
panel.add(button1, gbc);
gbc.insets = new Insets(50, 77, 100, 77);
panel.add(button2, gbc);
gbc.insets = new Insets(50, 0, 100, 360);
panel.add(button3, gbc);
panel.revalidate();
panel.repaint();
}
private void Escaped()
{
//Unnecessary info
}
private void Died()
{
//Unnecessary info
}
//This just resizes the images
private ImageIcon ImageSize(int x, int y, String fileName)
{
BufferedImage baseImg = null;
try {
baseImg = ImageIO.read(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
Image resizedImg = baseImg.getScaledInstance(x, y, Image.SCALE_SMOOTH);
ImageIcon IconImg = new ImageIcon(resizedImg);
return IconImg;
}
private void FormatText(JTextArea baseText)
{
//Unnecessary info
}
}
EDIT:
Here is also an example of what vector could go as an "event" in "AppendQuest"
Vector<String> items2 = new Vector<>();
items2.add("You are kind of disoriented. What will you use to find the right way?" +
" moss, sun or tree barks");
items2.add("Unfortunately you didn't orient yourself well enough. Now, you " +
"will roam through the forest forever.");
items2.add("res/orientation_sun.png");
items2.add("res/orientation_moss.png");
items2.add("res/orientation_sun.png");
items2.add("res/orientation_tree_bark.png");
You can compare Objects with the .equals(Object) function:
if(!button.getIcon().equals(livePicture))
{
Died();
}
else
{...}
The == operator checks the identity of objects or the value of native types (e.g. int).
That means:
int nr1 = 1;
int nr2 = 1;
if(nr1 == nr2) {...} //true -> int is a native type
String str1 = "test";
String str2 = "test";
if(str1 == str2) {...} //false -> Same content but not same objects
if(str1.equals(str2)) {...} //true -> Same content, different objects
//Edit:
Another problem might be that you remove the image-url from your vector while creating the livePicture:
livePicture = ImageSize(50, 50, event.remove(0));
The url is not in the list anymore when you create your buttons. The result is that the buttons will never have the same image as your livePicture has, unless you're changing it (do you?).
I need a text field on a label but when i run this code there is no text field on the screen. How can i fix it.
JFrame jf = new JFrame() ;
JPanel panel = new JPanel() ;
JLabel label = new JLabel() ;
JTextField tField = new JTextField("asd" , 10) ;
label.add( tField ) ;
panel.add( label ) ;
jf.setSize( 500,400 ) ;
jf.add( panel ) ;
jf.setVisible(true) ;
JLabel's have no default layout manager, and so while your JTextField is being added tot he JLabel, it's not showing because the label has no idea how to show it.
There can be several ways to solve this depending on what you're trying to achieve:
Give the JLabel a layout manager, and then add the JTextField to it: but then the JTextField covers the JLabel, its text (if it has any) and its icon (if it has one), not good.
Create a JPanel to hold both, and give it an appropriate layout manager: probably a good bet.
Add them both to the same JPanel, using a layout manager that can easily place them in association: another good bet. GridBagLayout works well for this.
Don't forget to also call the JLabel's setLabelFor(...) method to associate it tightly with the JTextField, as per the JLabel Tutorial
For example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class GridBagEg {
private static void createAndShowGui() {
PlayerEditorPanel playerEditorPane = new PlayerEditorPanel();
int result = JOptionPane.showConfirmDialog(null, playerEditorPane, "Edit Player",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
// TODO: do something with info
for (PlayerEditorPanel.FieldTitle fieldTitle : PlayerEditorPanel.FieldTitle.values()) {
System.out.printf("%10s: %s%n", fieldTitle.getTitle(),
playerEditorPane.getFieldText(fieldTitle));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class PlayerEditorPanel extends JPanel {
enum FieldTitle {
NAME("Name", KeyEvent.VK_N), SPEED("Speed", KeyEvent.VK_P), STRENGTH("Strength", KeyEvent.VK_T);
private String title;
private int mnemonic;
private FieldTitle(String title, int mnemonic) {
this.title = title;
this.mnemonic = mnemonic;
}
public String getTitle() {
return title;
}
public int getMnemonic() {
return mnemonic;
}
};
private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();
public PlayerEditorPanel() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Player Editor"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
GridBagConstraints gbc;
for (int i = 0; i < FieldTitle.values().length; i++) {
FieldTitle fieldTitle = FieldTitle.values()[i];
JLabel label = new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT);
JTextField textField = new JTextField(10);
label.setDisplayedMnemonic(fieldTitle.getMnemonic());
label.setLabelFor(textField);
gbc = createGbc(0, i);
add(label, gbc);
gbc = createGbc(1, i);
add(textField, gbc);
fieldMap.put(fieldTitle, textField);
}
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH : GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
public String getFieldText(FieldTitle fieldTitle) {
return fieldMap.get(fieldTitle).getText();
}
}
Which displays as
Note that the JLabels have underlines on mnemonic chars, chars that when pressed in alt-key combination will bring the focus to the JTextField that the JLabel was linked to via, setLabelFor(...), and is caused by this code:
FieldTitle fieldTitle = FieldTitle.values()[i]; // an enum that holds label texts
JLabel label = new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT); // create JLabel
JTextField textField = new JTextField(10); // create JTextField
// set the label's mnemonic -- brings focus to the linked text field
label.setDisplayedMnemonic(fieldTitle.getMnemonic());
// *** here we *link* the JLabel with the JTextField
label.setLabelFor(textField);
Here is how I created the labels and JTextFields:
JPanel panel3 = new JPanel(new SpringLayout());
String[] labels = {"Non-animated image name:","Left animation image name:","Top animation image name:",
"Right animation image name:","Bottom animation image name:"};
for(int i=0; i<labels.length; i++){
JLabel l = new JLabel(labels[i],JLabel.TRAILING);
JTextField n = new JTextField(10);
panel3.add(l);
l.setLabelFor(n);
panel3.add(n);
}
SpringUtilities.makeCompactGrid(panel3,
5, 2,
6, 6,
6, 6);
Say for example, how would I access/get the value of the text in the JTextField with the label, "Top animation image name:"?
I know that usually, one can perform JTextField.getText(), but to me it looks like that wouldn't work here.
Thanks in advance!
This is just a specific example of the question:
how can I access an object created in a loop.
The answer is the same: put them in a collection or array. Note that the collection option has greater flexibility. For instance if you create a bunch of JLabel/JTextField associations, you could use a HashMap<String, JTextField> to associate the JTextField with a String.
For example:
Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
String[] labels = {"Non-animated image name:","Left animation image name:","Top animation image name:",
"Right animation image name:","Bottom animation image name:"};
for(int i=0; i<labels.length; i++){
JLabel l = new JLabel(labels[i],JLabel.TRAILING);
JTextField n = new JTextField(10);
panel3.add(l);
l.setLabelFor(n);
panel3.add(n);
fieldMap.put(labels[i], n);
}
// and then later you can get the text field associated with the String:
String text = fieldMap.get(labels[2]).getText();
Or for a full example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputForm extends JPanel {
private static final int COLUMNS = 10;
private static final int GAP = 3;
private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
private String[] labelTexts;
private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
public InputForm(String[] labelTexts) {
this.labelTexts = labelTexts;
setLayout(new GridBagLayout());
for (int i = 0; i < labelTexts.length; i++) {
String text = labelTexts[i];
JTextField field = new JTextField(COLUMNS);
fieldMap.put(text, field);
addLabel(text, i);
addTextField(field, i);
}
}
public String[] getLabelTexts() {
return labelTexts;
}
private void addTextField(JTextField field, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = TEXTFIELD_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(field, gbc);
}
private void addLabel(String text, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = LABEL_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(new JLabel(text), gbc);
}
public String getFieldText(String key) {
String text = "";
JTextField field = fieldMap.get(key);
if (field != null) {
text = field.getText();
}
return text;
}
private static void createAndShowGui() {
String[] labelTexts = new String[] { "One", "Two",
"Three", "Four" };
InputForm inputForm = new InputForm(labelTexts);
int result = JOptionPane.showConfirmDialog(null, inputForm, "Enter Stuff Here",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
for (String text : labelTexts) {
System.out.printf("%20s %s%n", text, inputForm.getFieldText(text));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Each time you create a JLabel and a JTextField, store references to each of them inside a new instance of a container class.
For example:
private class LabelTextFieldContainer {
JLabel label;
JTextField textField;
//Constructor goes here...
}
for(int i=0; i<labels.length; i++){
JLabel l = new JLabel(labels[i],JLabel.TRAILING);
JTextField n = new JTextField(10);
panel3.add(l);
l.setLabelFor(n);
panel3.add(n);
containerList.add( new Container(l, n) ); //Instantiate List<LabelTextFieldContainer> containerList somewhere else
}
I have a problem while refreshing the content pane of my GUI. I can create a listener that is executed, but I can't manage to access the content pane to update it. Here is my code so far:
Egutegia() and Hasiera() and constructors for JPanels with different data. They load correctly when set to variable centralData from the beggining. My goal is to change between one another when clicking the buttons with their name. So far I only tried to implement one.
The action listener is written in the later part. It prints "reaches here" correctly. However, I dont know how to acces the content pane (content) from there and redraw the corresponding JPanel.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MyApp{
private static String message1 = "message1";
private static String message2 = "message2";
private static BotMessage botMessage;
private static TopButtons topButtons;
private static JButton[] buttons;
private static JButton b1,b2,b3,b4;
public static JPanel centralData = new Hasiera();
private static class BotMessage extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
double h = getHeight();
double w = getWidth();
Font font = new Font("default", Font.BOLD, (int)(h/2));
g.setFont(font);
int stw = g.getFontMetrics().stringWidth(message2);
g.drawString(message1, (int)(w*0.02), (int)(3*h/4));
g.drawString(message2,(int) (w*0.98 - stw),(int)(3*h/4));
setBackground(Color.ORANGE);
}
public static class TopButtons extends JPanel{
public TopButtons(JButton buttons[]){
setLayout(new GridLayout(1,1));
setBackground(Color.ORANGE);
for (int i=0;i < buttons.length;i++){
add(buttons[i]);
}
}
}
/*
* LOADING EVERYTHING INTO A WINDOW
*/
public static void main(String[] args) {
botMessage = new BotMessage();
b1 = new JButton("Hasiera");
ActionListener ref = new ActionListener(){
public void actionPerformed(ActionEvent e){
centralData = new Egutegia();
System.out.println("reaches here");
}
};
b1.addActionListener(ref);
b2 = new JButton("Egutegia");
b3 = new JButton("Foroa");
b4 = new JButton("Txata");
buttons = new JButton[]{b1,b2,b3,b4};
topButtons = new TopButtons(buttons);
JPanel content = new JPanel();
content.setLayout(new GridBagLayout());
GridBagConstraints c1 = new GridBagConstraints();
c1.fill = GridBagConstraints.BOTH;
c1.weighty = 0.02;
c1.gridx = 0;
c1.gridy = 0;
c1.gridwidth = 2;
content.add(topButtons, c1);
GridBagConstraints c2 = new GridBagConstraints();
c2.weightx = 1;
c2.weighty = 1;
c2.fill = GridBagConstraints.BOTH;
c2.gridx = 0;
c2.gridy = 1;
content.add(centralData, c2);
GridBagConstraints c3 = new GridBagConstraints();
c3.fill = GridBagConstraints.BOTH;
c3.weighty = 0.04;
c3.gridx = 0;
c3.gridy = 2;
content.add(botMessage, c3);
JFrame window = new JFrame("MY APP");
window.setContentPane(content);
window.setSize(400,600);
window.setLocation(100,100);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I have all of the labels working correctly but the userLabel[3] is not positioning properly
No matter what I do, the label "Color:" always shows up on the frame with a x-coordinate of 0 and a y-coordinate that is half way down the frame.
JLabel[] userLabel = new JLabel[4];
for(int p = 0; p < userLabel.length; p++){
userLabel[p] = new JLabel();
userLabel[p].setSize(100,50);
frameSetUp.add(userLabel[p]);
}
userLabel[0].setText("Width of Frame:");
userLabel[1].setText("Height of Frame:");
userLabel[2].setText("# OF Balls:");
userLabel[3].setText("Color:");
userLabel[0].setLocation(10,35);
userLabel[1].setLocation(10,85);
userLabel[2].setLocation(10,135);
userLabel[3].setLocation(0,0); //no matter what coordinates I change this too, it wont reposition
Image:
[IMG]http://i41.tinypic.com/23jfo9l.png[/IMG]
http://i41.tinypic.com/23jfo9l.png
Don't use setLocation, setBounds, null layouts or absolute positioning.
Instead use the layout managers including perhaps nested JPanels, each using its own layout manager to achieve pleasing easy to maintain GUI's.
For more help, show a picture of what you're trying to achieve, what you actually are achieving, and post a minimal working example, code that is small, that compiles and runs, and shows us your problem.
e.g.,
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputForm extends JPanel {
private static final int COLUMNS = 10;
private static final int GAP = 3;
private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
private String[] labelTexts;
private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
public InputForm(String[] labelTexts) {
this.labelTexts = labelTexts;
setLayout(new GridBagLayout());
for (int i = 0; i < labelTexts.length; i++) {
String text = labelTexts[i];
JTextField field = new JTextField(COLUMNS);
fieldMap.put(text, field);
addLabel(text, i);
addTextField(field, i);
}
}
public String[] getLabelTexts() {
return labelTexts;
}
private void addTextField(JTextField field, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = TEXTFIELD_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(field, gbc);
}
private void addLabel(String text, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = LABEL_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(new JLabel(text), gbc);
}
public String getFieldText(String key) {
String text = "";
JTextField field = fieldMap.get(key);
if (field != null) {
text = field.getText();
}
return text;
}
private static void createAndShowGui() {
String[] labelTexts = new String[] { "Width of Frame:",
"Height of Frame:", "# OF Balls:", "Color:" };
InputForm inputForm = new InputForm(labelTexts);
int result = JOptionPane.showConfirmDialog(null, inputForm, "Input Form",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
for (String text : labelTexts) {
System.out.printf("%20s %s%n", text, inputForm.getFieldText(text));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which will display like so:
The beauty of this code, is if you wish to add another field, say a line thickness field, and want to add it so that it is second to last, then the only change needed to the code would be to change this:
String[] labelTexts = new String[] { "Width of Frame:",
"Height of Frame:", "# OF Balls:", "Color:" };
to this:
String[] labelTexts = new String[] { "Width of Frame:",
"Height of Frame:", "# OF Balls:", "Line Thickness:", "Color:" };
Which results in:
No need to have to calculate how to change the Color label or JTextField's locations as the layout manager does all the hard work for you.
Finally got the answer try increasing the size of the JLabel array by 1 and run it will work fine
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Labelss{
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(50, 50, 700, 550);
JLabel[] userLabel = new JLabel[6];
for(int p = 0; p < userLabel.length; p++){
userLabel[p] = new JLabel();
}
userLabel[0].setBounds(10,35,100,50);
userLabel[1].setBounds(10,85,100,50);
userLabel[2].setBounds(10,135,100,50);
userLabel[3].setBounds(10,185,100,50);
userLabel[4].setBounds(10,235,100,50);
userLabel[0].setText("Width of Frame:");
userLabel[1].setText("Height of Frame:");
userLabel[2].setText("# OF Balls:");
userLabel[3].setText("Color:");
userLabel[4].setText("Stack overflow:");
for(int p = 0; p < userLabel.length; p++){
frame.add(userLabel[p]);
}
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}