Replace items in JComboBox with array - java

I was wondering if there was an easy way to do this. I'm trying to remove the items from the weapons combobox (with success), and then add the array into the combo box like how it was when it was first instantiated. I don't want to just create and copy a new one, because there are body constraints already set to the liking. Here is the code...
import org.apache.commons.lang3.ArrayUtils;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
public class TestGui extends JFrame {
private final String[] guiCharSelDefault = {"--- Select Character ---"};
private final String[] characters = {"charOne", "charTwo", "charThree", "charFour"};
private final String[] GuiCharSel = (String[]) ArrayUtils.addAll(guiCharSelDefault, characters);
private final String[] weapon = {"Weapon"};
private final String[][] allWeapons = {
{
"weakWeaponOne", "strongWeaponOne", "shortWeaponOne", "longWeaponOne"
},
{
"weakWeaponTwo", "strongWeaponTwo", "shortWeaponTwo", "longWeaponTwo"
},
{
"weakWeaponThree", "strongWeaponThree", "shortWeaponThree", "longWeaponThree"
},
{
"weakWeaponFour", "strongWeaponFour", "shortWeaponFour", "longWeaponFour"
}
};
private JComboBox charCombo = new JComboBox(GuiCharSel);
private JComboBox weaponsCombo = new JComboBox(weapon);
private JPanel centerFrame = createCenterFrame();
//**************************************************************************************
private GridBagConstraints setGbc(int gridx, int gridy, int ipadx, int ipady, String anchorLocation, double weightx, double weighty, Insets insets){
GridBagConstraints gbc = new GridBagConstraints();
if (anchorLocation.toUpperCase().equals("NORTHWEST")){
gbc.anchor = GridBagConstraints.NORTHWEST;
} else if (anchorLocation.toUpperCase().equals("NORTH")){
gbc.anchor = GridBagConstraints.NORTH;
} else if (anchorLocation.toUpperCase().equals("NORTHEAST")){
gbc.anchor = GridBagConstraints.NORTHEAST;
} else if (anchorLocation.toUpperCase().equals("WEST")){
gbc.anchor = GridBagConstraints.WEST;
} else if (anchorLocation.toUpperCase().equals("EAST")){
gbc.anchor = GridBagConstraints.EAST;
} else if (anchorLocation.toUpperCase().equals("SOUTHWEST")){
gbc.anchor = GridBagConstraints.SOUTHWEST;
} else if (anchorLocation.toUpperCase().equals("SOUTH")){
gbc.anchor = GridBagConstraints.SOUTH;
} else if (anchorLocation.toUpperCase().equals("SOUTHEAST")){
gbc.anchor = GridBagConstraints.SOUTHEAST;
} else {
gbc.anchor = GridBagConstraints.CENTER;
}
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.ipadx = ipadx;
gbc.ipady = ipady;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.insets = insets;
return gbc;
}
private Insets setInsets(int top, int left, int bottom, int right){
Insets insets = new Insets(top,left,bottom,right);
return insets;
}
//**************************************************************************************
private JPanel createCenterFrame(){
JPanel pnl = new JPanel();
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compound = BorderFactory.createCompoundBorder(raisedBevel, loweredBevel);
pnl.setBorder(compound);
charCombo.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String charName = ((JComboBox)(e.getSource())).getSelectedItem().toString();
if (charName.equals("charOne")){
weaponsCombo.removeAllItems();
weaponsCombo.addItem(allWeapons[1]); // <---- Help Please!!!
}
}
}
);
pnl.add(charCombo, setGbc(0,0, 0, 0, "NORTHWEST", 0, 0, setInsets(0, 10, 0, 0)));
pnl.add(weaponsCombo, setGbc(0,0, 0, 0, "NORTHWEST", 0, 0, setInsets(0, 10, 0, 0)));
return pnl;
}
TestGui(){
add(centerFrame, BorderLayout.CENTER);
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//**************************************************************************************
public static void main(String[] args) {
new TestGui();
}
}
Line 95 (// <---- Help Please!!!) is where I'm wondering if there is an easy way to do this. The problem is when you select "charOne" in the character combobox on the gui, you see a weird language string instead of a list of the 4 weapons in the weapon combobox.

The simple solution is simply to replace the ComboBoxModel...
if (charName.equals("charOne")) {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(allWeapons[1]);
weaponsCombo.setModel(model);
}
See How to Use Combo Boxes for more details

Related

GridBagConstraints ipad lock size

I'm new to Java Swing and am working on a project to help me become more familiar with it. I've noticed while changing the label text, the cell in the GridBagLayout increases/decreases (you can tell by the borderline resizing). I was wondering if there was a way to lock the ipad size, so it doesn't change (after it is set). Is there a way to lock the ipad size?
Below are images so you can see what I'm talking about.
Before:
After:
Notice how the label shrinks when a single digit is put in. And if a double digit is put in, the label expands (larger than the "- -" label)
Here is the code:
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StartGuiTest extends JFrame implements ActionListener {
private static final int unselectedDefaultElement = 0;
private static final String unselectedLvl = "- -";
private static final int maxLvl = 99;
private static final String[] GuiCharSel = {"--- Select Character ---", "Cloud", "Barret", "Tifa", "Aeris", "Red XIII", "Yuffie", "Cait Sith", "Vincent", "Cid"};
private String[] lvlRange = createArrRange(unselectedLvl, 1, maxLvl);
/*
* Interactive GUI Objects
*/
JLabel charPic;
JComboBox charSelCombo = new JComboBox(GuiCharSel);
JComboBox pickLvlAns = new JComboBox(lvlRange);
JLabel nextLvlAns = new JLabel(unselectedLvl);
public StartGuiTest() {
JPanel topFrame = new JPanel();
JPanel bottomFrame = new JPanel();
JPanel selPane = new JPanel();
JLabel pickLvl = new JLabel("Pick Current Level:");
JLabel nextLvl = new JLabel("Next Level:");
TitledBorder topFrameTitle;
Border blackLine = BorderFactory.createLineBorder(Color.black);
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compound = BorderFactory.createCompoundBorder(raisedBevel, loweredBevel);
topFrameTitle = BorderFactory.createTitledBorder(compound, "Character");
topFrameTitle.setTitleJustification(TitledBorder.CENTER);
topFrame.setBorder(topFrameTitle);
topFrame.setLayout(new BoxLayout(topFrame, BoxLayout.X_AXIS));
/*
* Adds Character Picture
*/
charPic = new JLabel("", null, JLabel.CENTER);
charPic.setPreferredSize(new Dimension(100,100));
topFrame.add(charPic);
//*******************************************************************************
/*
* Selection Pane Settings
*/
selPane.setLayout(new GridBagLayout());
/*
* Adds Character Selection ComboBox
*/
charSelCombo.setPrototypeDisplayValue(charSelCombo.getItemAt(unselectedDefaultElement));
selPane.add(charSelCombo, setGbc(0,0, 0, 0, "WEST", 0, 1, setInsets(0, 10, 0, 0)));
charSelCombo.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
charSelCombo.removeItem(GuiCharSel[unselectedDefaultElement]);
pickLvlAns.removeItem(lvlRange[unselectedDefaultElement]);
}
}
);
/*
* Adds "Pick Current Level:" Label
*/
selPane.add(pickLvl, setGbc(0,1, 0, 0, "EAST", 0, 1, setInsets(0, 0, 0, 0)));
/*
* Adds Character Current Level ComboBox
*/
pickLvlAns.setPrototypeDisplayValue(pickLvlAns.getItemAt(lvlRange.length - 1));
selPane.add(pickLvlAns, setGbc(1,1, 0, 0, "WEST", 1, 1, setInsets(0, 10, 0, 0)));
pickLvlAns.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String currLvl = ((JComboBox)(e.getSource())).getSelectedItem().toString();
if(isInteger(currLvl)){
if (Integer.parseInt(currLvl) == maxLvl){
nextLvlAns.setText(unselectedLvl);
} else {
nextLvlAns.setText(Integer.toString(Integer.parseInt(currLvl) + 1));
}
} else {
nextLvlAns.setText(unselectedLvl);
}
}
}
);
/*
* Adds "Next Level:" Label
*/
selPane.add(nextLvl, setGbc(0,2, 0, 0, "EAST", 0, 1, setInsets(0, 0, 0, 0)));
/*
* Adds Character Next Level Label
*/
nextLvlAns.setBorder(blackLine);
nextLvlAns.setHorizontalAlignment(JLabel.CENTER);
selPane.add(nextLvlAns, setGbc(1,2, 28, 5, "WEST", 1, 1, setInsets(0, 10, 0, 0)));
//*******************************************************************************
topFrame.add(selPane);
//*******************************************************************************
/*
* BOTTOM PANE
*/
TitledBorder bottomFrameTitle;
bottomFrameTitle = BorderFactory.createTitledBorder(compound, "Stats");
bottomFrameTitle.setTitleJustification(TitledBorder.CENTER);
bottomFrame.setBorder(bottomFrameTitle);
//*******************************************************************************
/*
* Display everything in GUI to user
*/
add(topFrame, BorderLayout.NORTH);
add(bottomFrame,BorderLayout.CENTER);
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent arg0) {
}
private GridBagConstraints setGbc(int gridx, int gridy, int ipadx, int ipady, String anchorLocation, double weightx, double weighty, Insets insets){
GridBagConstraints gbc = new GridBagConstraints();
if (anchorLocation.toUpperCase().equals("NORTHWEST")){
gbc.anchor = GridBagConstraints.NORTHWEST;
} else if (anchorLocation.toUpperCase().equals("NORTH")){
gbc.anchor = GridBagConstraints.NORTH;
} else if (anchorLocation.toUpperCase().equals("NORTHEAST")){
gbc.anchor = GridBagConstraints.NORTHEAST;
} else if (anchorLocation.toUpperCase().equals("WEST")){
gbc.anchor = GridBagConstraints.WEST;
} else if (anchorLocation.toUpperCase().equals("EAST")){
gbc.anchor = GridBagConstraints.EAST;
} else if (anchorLocation.toUpperCase().equals("SOUTHWEST")){
gbc.anchor = GridBagConstraints.SOUTHWEST;
} else if (anchorLocation.toUpperCase().equals("SOUTH")){
gbc.anchor = GridBagConstraints.SOUTH;
} else if (anchorLocation.toUpperCase().equals("SOUTHEAST")){
gbc.anchor = GridBagConstraints.SOUTHEAST;
} else {
gbc.anchor = GridBagConstraints.CENTER;
}
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.ipadx = ipadx;
gbc.ipady = ipady;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.insets = insets;
return gbc;
}
private Insets setInsets(int top, int left, int bottom, int right){
Insets insets = new Insets(top,left,bottom,right);
return insets;
}
protected static String[] createArrRange(String firstElement, int startNum, int endNum) {
String[] strArr = new String[endNum+1];
strArr[0] = firstElement;
for (int num = startNum, element = 1; num <= endNum; num++, element++){
strArr[element] = Integer.toString(num);
}
return strArr;
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
public static void main(String[] args) {
new StartGuiTest();
}
}
I've tried using label.setPrototypeDisplayValue(), but I guess this only works for the combo boxes in locking them so they don't change the size. I can't seem to find anything in the libraries or google that shows how to do this.
Welcome to the wonderful world of variable width fonts.
I would summiuse that the issue isn't with the nextLvlAns, but with the pickLvlAns
The problem seems to be -- is a different size then 2, which is changing the size of the combo box.
You started in the right direction with the using setPrototypeDisplayValue, but I'd suggest using something long pickLvlAns.setPrototypeDisplayValue("00"); for example or even maybe pickLvlAns.setPrototypeDisplayValue("----");, so that it covers a larger possible range.
Remember, when using variable width fonts, 0 is likely to be larger the -
Another trick might be to use a non editable JTextField instead of a JLabel, this because, JLabel keeps wanting to accommodate itself to the text content
JTextField nextLvlAns = new JTextField(unselectedLvl, 3);
//...
nextLvlAns.setEditable(false);

Multiple JTextFields in a JOptionPane.ShowInputDialog?

I'm wanting to put several JTextFields into a JOptionPane so that I can validate the information put within them. I know that showInputDialog() will produce one Input, but how would I go about implementing 3/4
EDIT: (At run-time it just shows one input field)
//JDIALOG(FOR END PAYMENT)
dialogPanel = new JPanel();
creditCardNoInput = new JTextField();
sortCodeInput = new JTextField();
secNoInput = new JTextField();
cardHolderName = new JTextField();
dialogPanel.add(creditCardNoInput);
dialogPanel.add(sortCodeInput);
dialogPanel.add(secNoInput);
dialogPanel.add(cardHolderName);
int result = JOptionPane.showConfirmDialog(null, dialogPanel,
"Please Enter your card details", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
//Execute desired code
Use a JPanel.
Put your JTextFields, along with your JLabels (since you'll likely need these as well), into a JPanel or JPanels, and put the main JPanel into the JOptionPane. You can put a complete complex GUI into JPanels and display this in a JOptionPane if desired.
For example:
import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class ComplexOptionPane extends JPanel {
private PlayerEditorPanel playerEditorPanel = new PlayerEditorPanel();
private JTextArea textArea = new JTextArea(12, 30);
public ComplexOptionPane() {
textArea.setEditable(false);
textArea.setFocusable(false);
textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new AbstractAction("Get Player Information") {
#Override
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.showConfirmDialog(null, playerEditorPanel,
"Edit Player JOptionPane", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
for (PlayerEditorPanel.FieldTitle fieldTitle : PlayerEditorPanel.FieldTitle
.values()) {
textArea.append(String.format("%10s: %s%n",
fieldTitle.getTitle(),
playerEditorPanel.getFieldText(fieldTitle)));
}
}
}
}));
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(new JScrollPane(textArea), BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
ComplexOptionPane mainPanel = new ComplexOptionPane();
JFrame frame = new JFrame("ComplexOptionPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class PlayerEditorPanel extends JPanel {
enum FieldTitle {
NAME("Name"), SPEED("Speed"), STRENGTH("Strength"), HEALTH("Health");
private String title;
private FieldTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
};
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];
gbc = createGbc(0, i);
add(new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT), gbc);
gbc = createGbc(1, i);
JTextField textField = new JTextField(10);
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();
}
}
Also -- this answer
An MCVE using your code example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
import javax.swing.border.Border;
public class Foo1 {
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 JPanel dialogPanel;
private JTextField creditCardNoInput;
private JTextField sortCodeInput;
private JTextField secNoInput;
private JTextField cardHolderName;
public Foo1() {
dialogPanel = new JPanel(new GridBagLayout());
Border titleBorder = BorderFactory.createTitledBorder("Credit Card Information");
Border emptyBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10);
Border combinedBorder = BorderFactory.createCompoundBorder(titleBorder, emptyBorder);
dialogPanel.setBorder(combinedBorder);
creditCardNoInput = new JTextField(5);
sortCodeInput = new JTextField(5);
secNoInput = new JTextField(5);
cardHolderName = new JTextField(5);
dialogPanel.add(new JLabel("Credit Card Number:"), createGbc(0, 0));
dialogPanel.add(creditCardNoInput, createGbc(1, 0));
dialogPanel.add(new JLabel("Sort Code:"), createGbc(0, 1));
dialogPanel.add(sortCodeInput, createGbc(1, 1));
dialogPanel.add(new JLabel("Second Number:"), createGbc(0, 2));
dialogPanel.add(secNoInput, createGbc(1, 2));
dialogPanel.add(new JLabel("Cardholder Name:"), createGbc(0, 3));
dialogPanel.add(cardHolderName, createGbc(1, 3));
int result = JOptionPane.showConfirmDialog(null, dialogPanel,
"Please Enter your card details", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
// Execute desired code
}
}
private static 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;
}
private static void createAndShowGui() {
new Foo1();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Solution:
When I was running my code, for some reason it was preferring my other GUI to start up. I only found this out when I commented out the code and the JOptionPane was still executing, so I manually selected my GUI, ran it, and the 4 boxed appeared.
P.S Please vote this answer so that I can get a badge. Thanks! :)

JPanel doesnt show components after the second button click

I want to put a JTextPane component in a JPanel with a GridBagLayout when I click on button.
My code works fine for the first button click, But after, the next components are not displayed.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class RefreshPanel {
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private JTextPane [] textPane;// = new JTextPane[1];
private JScrollPane scrollbar;
private ArrayList arrayList = new ArrayList();
private JButton newItem = new JButton("new");
private int counter=0;
private GridBagLayout gbl = new GridBagLayout();
RefreshPanel() {
scrollbar = new JScrollPane(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(gbl);
addButtonListener();
createFrame();
} //constructor
public void addButtonListener() {
newItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
arrayList.add("data");
textPane = generateTextPane(arrayList.size(), arrayList);
System.out.println(textPane.length);
for(int i=0;i<textPane.length;i++) {
System.out.println(textPane[i].getText());
addComponent(panel, gbl, textPane[i], 0, counter, 1, 1,1,1);
panel.revalidate();
}
}
});
}
private JTextPane[] generateTextPane(int arraySize, ArrayList arrayList) {
JTextPane [] textPane = new JTextPane[arraySize];
for(int i=0;i<textPane.length;i++) {
textPane[i]=new JTextPane();
textPane[i].setText((String) arrayList.get(i));
}
return textPane;
}
public void addComponent(Container cont,
GridBagLayout gbl,
Component c,
int x, int y,
int width, int height,
double weightx, double weighty) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = width; gbc.gridheight = height;
gbc.weightx = weightx; gbc.weighty = weighty;
gbl.setConstraints( c, gbc );
cont.add( c );
}
public void createFrame() {
//frame.getContentPane().setLayout(new FlowLayout());
frame.add(scrollbar, BorderLayout.CENTER);
frame.add(newItem, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300,300));
frame.setVisible(true);
}
public static void main(String [] args) {
new RefreshPanel();
}
}
Patrick: you are right! I really forgot to change the gridbagconstraints
addComponent(panel, gbl, textPane[i], 0, i, 1, 1, 1, 1);
instead of
addComponent(panel, gbl, textPane[i], 0, counter, 1, 1, 1, 1);

Accessing values of individual JTextFields created in a loop

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
}

setLocation of Label

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);
}
}

Categories

Resources