GridBagConstraints ipad lock size - java

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

Related

Can't compare button icon to another icon

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?).

How to locate JTextField under other JTextField?

I am making authentication GUI which should contain 2 text fields, username JTextField and password JPasswordField. I want to make the password field be below the username field. my current code is as follows:
public class GuiAuthentication extends JFrame {
private static final int WIDTH = 1000;
private static final int HEIGHT = 650;
private JTextField tfUsername;
private JPasswordField tfPassword;
public GuiAuthentication() {
try {
setTitle("Metaspace Launcher");
getContentPane().setLayout(new FlowLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
tfUsername = new JTextField("Username");
tfPassword = new JPasswordField("********");
tfUsername.setBounds(10, 10, 50, 20);
tfPassword.setBounds(10, 50, 50, 20);
getContentPane().add(tfUsername);
getContentPane().add(tfPassword);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setMinimumSize (new Dimension(WIDTH, HEIGHT));
setMaximumSize (new Dimension(WIDTH, HEIGHT));
setResizable(false);
requestFocus();
setLocationRelativeTo(null);
setVisible(true);
} catch (final Exception ex) {
ex.printStackTrace();
System.exit(ex.toString().hashCode());
}
}
#Override
public void paint(final Graphics g) {
super.paint(g);
Gui.drawBackground(this, g, WIDTH, HEIGHT);
Gui.drawRect(g, WIDTH/3, HEIGHT/3 + 20, 325, 200, 0xAA000000);
}
However, this results in the password field being located against the username field, and both of them are centered, and not located at X position 10 which I specify:
--> Screenshot (click)
Is the problem in the layout I currently use (FlowLayout)? If so, which one should I use then? If not, what else might be wrong?
Tried using GridBagLayout as well. It results in this (fields side by side, centered):
Your GridBagLayout attempt images suggest that either you're not using GridBagConstraints when adding components or that you're using the incorrectly.
If you want to center your text components in the GUI, one over the other, and say put them in their own box, then use a GridBagLayout for the container that holds them, and also pass in appropriate GridBagConstraints that will work well with your desire. This will mean giving the constraints an appropriate gridx and gridy value to match where in the grid you wish to place the component. Also you will want to anchor the component correctly, and you will usually want to set the constraints insets to give an empty space buffer around your components so that they don't crowd each other. Myself, when I do something like this, I often use a 4 x 4 grid with two rows and two columns including a column of JLabels on the left so the user knows what each text component in the right column represents. I often use a helper method to help create my constraints, something like this:
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.fill = GridBagConstraints.HORIZONTAL; // stretch components horizontally
gbc.weightx = 1.0;
gbc.weighty = 0.0; // increase if you want component location to stretch vert.
// I_GAP is a constant and is the size of the gap around
// each component
gbc.insets = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
// if the x value is odd, anchor to the left, otherwise if even to the right
gbc.anchor = x % 2 == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
return gbc;
}
And then I'd use it like this:
JPanel innerPanel = new JPanel(new GridBagLayout());
JLabel userNameLabel = new JLabel("User Name:");
userNameLabel.setForeground(Color.LIGHT_GRAY);
innerPanel.add(userNameLabel, createGbc(0, 0)); // add w/ GBC
innerPanel.add(tfUsername, createGbc(1, 0)); // etc...
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setForeground(Color.LIGHT_GRAY);
innerPanel.add(passwordLabel, createGbc(0, 1));
innerPanel.add(tfPassword, createGbc(1, 1));
A working example could look like so:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class MetaSpaceLauncherPanel extends JPanel {
// path to a public starry image
public static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/b/be/Milky_Way_at_Concordia_Camp%2C_Karakoram_Range%2"
+ "C_Pakistan.jpg/1280px-Milky_Way_at_Concordia_Camp%2C_Karakoram_Range"
+ "%2C_Pakistan.jpg";
private static final int I_GAP = 10;
private static final int COLS = 15;
private JTextField tfUsername = new JTextField(COLS);
private JPasswordField tfPassword = new JPasswordField(COLS);
private BufferedImage background = null;
public MetaSpaceLauncherPanel(BufferedImage background) {
this.background = background;
// close window if enter pressed and data within fields
ActionListener listener = e -> {
String userName = tfUsername.getText().trim();
char[] password = tfPassword.getPassword();
Window window = SwingUtilities.getWindowAncestor(MetaSpaceLauncherPanel.this);
if (userName.isEmpty() || password.length == 0) {
// both fields need to be filled!
String message = "Both user name and password fields must contain data";
String title = "Invalid Data Entry";
JOptionPane.showMessageDialog(window, message, title, JOptionPane.ERROR_MESSAGE);
} else {
// simply close the dialog
window.dispose();
}
};
tfUsername.addActionListener(listener);
tfPassword.addActionListener(listener);
JPanel innerPanel = new JPanel(new GridBagLayout());
innerPanel.setOpaque(false);
Border outerBorder = BorderFactory.createEtchedBorder();
Border innerBorder = BorderFactory.createEmptyBorder(I_GAP, I_GAP, I_GAP, I_GAP);
Border border = BorderFactory.createCompoundBorder(outerBorder, innerBorder);
innerPanel.setBorder(border);
JLabel userNameLabel = new JLabel("User Name:");
userNameLabel.setForeground(Color.LIGHT_GRAY);
innerPanel.add(userNameLabel, createGbc(0, 0));
innerPanel.add(tfUsername, createGbc(1, 0));
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setForeground(Color.LIGHT_GRAY);
innerPanel.add(passwordLabel, createGbc(0, 1));
innerPanel.add(tfPassword, createGbc(1, 1));
setLayout(new GridBagLayout());
add(innerPanel); // add without constraints to center it
}
public String getUserName() {
return tfUsername.getText();
}
public char[] getPassword() {
return tfPassword.getPassword();
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.fill = GridBagConstraints.HORIZONTAL; // stretch components horizontally
gbc.weightx = 1.0;
gbc.weighty = 0.0; // increase if you want component location to stretch vert.
// I_GAP is a constant and is the size of the gap around
// each component
gbc.insets = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
// if the x value is odd, anchor to the left, otherwise if even to the right
gbc.anchor = x % 2 == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
return gbc;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
g.drawImage(background, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || background == null) {
return super.getPreferredSize();
}
int w = background.getWidth();
int h = background.getHeight();
return new Dimension(w, h);
}
private static void createAndShowGui() {
BufferedImage img = null;
try {
// just using this as an example image, one available to all
// you would probably use your own image
URL imgUrl = new URL(IMG_PATH); // online path to starry image
img = ImageIO.read(imgUrl);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1); // no image available -- exit!
}
MetaSpaceLauncherPanel launcherPanel = new MetaSpaceLauncherPanel(img);
JDialog dialog = new JDialog(null, "MetaSpace Launcher", ModalityType.APPLICATION_MODAL);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.getContentPane().add(launcherPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
// test to see if we can get the data
String userName = launcherPanel.getUserName();
char[] password = launcherPanel.getPassword();
// don't convert password into String as I'm doing below as it is now
// not secure
String message = String.format("<html>User Name: %s<br/>Password: %s</html>", userName,
new String(password));
JOptionPane.showMessageDialog(null, message);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Replace items in JComboBox with array

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

how can I use JTextField and JLabel together?

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

Small GUI issue I cannot fix. JTextFields

Small error I can't manage to do. So right now my program GUI looks like this:
Now there is a TextField under the 'Mark' column were the user can input their data. I also want the same for the weight section were I want to insert a TextField right under 'Weight' column.
However when I try and put in a TextField, both the the Textfields turn like this when the window is small:
and this when the window is enlarged:
How can I make it so that there is a textfield under Mark AND Weight?
Code:
public class Gradeanalysis implements ActionListener {
public void actionPerformed (ActionEvent e){
GridBagConstraints gbc = new GridBagConstraints();
//Adding the JPanels. Panel for instructions
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
//JLabel for the Instructions.
JLabel label = new JLabel("<html> Instructions: Type in the grades you’ve received, along with the weights they’ll have in the determination of your overall average. <br> After you press ‘Calculate’, the results will show your average so far. <br> Every grade you enter must be a non-negative number, and every percentage/weight you enter must be a positive number :)</html>");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
gbc.gridy = 0;
panel.add(label, gbc);
//JLabel1 for Assingment/Grade/Weight(Percent)
JLabel label1 = new JLabel("<html><pre>Assingment\t\t\t\t\t Mark\t\t\t\t\tWeight</pre></html>");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.NORTH;
panel.add(label1, gbc);
//JLabel Numbers for the number list of assingments at the side.
JLabel numbers = new JLabel("1");
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.NORTH;
gbc.weighty = 1;
panel.add(numbers, gbc);
//JTextfield for Mark
JTextField mark = new JTextField(2);
gbc.fill = GridBagConstraints.NONE;
gbc.gridy = 2;
panel.add(mark, gbc);
//JTextfield for Weight
JTextField weight = new JTextField(2);
gbc.gridx = 2;
panel.add(weight, gbc);
//New frame set
JFrame frame = new JFrame("Grade Calculator-- ");
frame.setVisible(true);
frame.setSize(750,700);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(panel);
}
}
Thanks for reading.
Here's the GUI I created.
I don't know where your main method is, but you must always start a Swing application with a call to the SwingUtilities invokeLater method. The invokeLater method puts the creation and execution of the Swing components on the Event Dispatch thread (EDT).
When I use the GridBagLayout, I use the addComponent method I created to create a unique GridBagConstraints for each Swing component. I don't like to remember defaults.
The order of the JFrame methods is extremely important. Memorize the order of the JFrame methods in this example.
I put the instructions in a JTextArea. This way, the instruction text splits based on the size of the JTextArea. There's no need to hard code the line breaks with HTML.
Here's the code.
package com.ggl.testing;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class GradeAnalysis implements Runnable {
private static final Insets normalInsets = new Insets(10, 10, 0, 10);
private static final Insets finalInsets = new Insets(10, 10, 10, 10);
public static void main(String[] args) {
SwingUtilities.invokeLater(new GradeAnalysis());
}
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setVisible(true);
}
private JPanel createMainPanel() {
GridBagConstraints gbc = new GridBagConstraints();
// Adding the JPanels. Panel for instructions
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
int gridy = 0;
// JLabel for the Instructions.
JTextArea instructionTextArea = new JTextArea(5, 30);
instructionTextArea.setEditable(false);
instructionTextArea.setLineWrap(true);
instructionTextArea.setWrapStyleWord(true);
instructionTextArea.setText(getInstructions());
JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1,
finalInsets, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL);
// JLabels for Assignment/Grade/Weight(Percent)
JLabel label1 = new JLabel("Assignment");
label1.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
JLabel label2 = new JLabel("Mark");
label2.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, label2, 1, gridy, 1, 1, finalInsets,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
JLabel label3 = new JLabel("Weight");
label3.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
// JLabel Numbers for the number list of assignments at the side.
JLabel number = new JLabel("1");
number.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, number, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
// JTextfield for Mark
JTextField mark = new JTextField(20);
mark.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, mark, 1, gridy, 1, 1, normalInsets,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
// JTextfield for Weight
JTextField weight = new JTextField(20);
weight.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, weight, 2, gridy++, 1, 1, normalInsets,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
return panel;
}
private String getInstructions() {
return "Instructions: Type in the grades you’ve received, along with the weights "
+ "they’ll have in the determination of your overall average. After you "
+ "press ‘Calculate’, the results will show your average so far. Every "
+ "grade you enter must be a non-negative number, and every "
+ "percentage/weight you enter must be a positive number :)";
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
}
I suggest that you
Don't use setBounds(...) on any component or GUI
Same for setSize(...)
Instead nest JPanels each using its own layouts to achieve a pleasing and easy to manage layout and GUI.
Consider putting your intro text into a JTextArea. If you want it to look like a JLabel, you can take out the background color and borders.
Best of all would be to display the tabular data in a JTable, and for that you'd want to create your own table model, one based on the AbstractTableModel and that uses an Assignment object for each row.
An example without the JTable:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class GradeAnalysis2 extends JPanel {
private static final int PREF_H = 400;
private static final String DISPLAY_TEXT = "Instructions: "
+ "Type in the grades you’ve received, along with the "
+ "weights they’ll have in the determination of your "
+ "overall average.\n"
+ "After you press ‘Calculate’, the results will show "
+ "your average so far.\n"
+ "Every grade you enter must be a non-negative number, "
+ "and every percentage/weight you enter must be a "
+ "positive number :)";
private JTextArea displayArea = new JTextArea(5, 50);
private GradeTablePanel gradeTablePanel = new GradeTablePanel();
public GradeAnalysis2() {
displayArea.setText(DISPLAY_TEXT);
displayArea.setWrapStyleWord(true);
displayArea.setLineWrap(true);
displayArea.setEditable(false);
displayArea.setFocusable(false);
displayArea.setBorder(null);
displayArea.setBackground(null);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(gradeTablePanel, BorderLayout.PAGE_START);
centerPanel.add(Box.createGlue(), BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane(centerPanel);
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(new AddAssignmentAction("Add")));
setLayout(new BorderLayout());
add(displayArea, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
Dimension sz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return sz;
}
int height = Math.max(sz.height, PREF_H);
return new Dimension(sz.width, height);
}
private class AddAssignmentAction extends AbstractAction {
public AddAssignmentAction(String name) {
super(name);
int mnenomic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnenomic);
}
public void actionPerformed(ActionEvent e) {
gradeTablePanel.addAssignment();
gradeTablePanel.revalidate();
gradeTablePanel.repaint();
};
}
private class GradeTablePanel extends JPanel {
private int count = 0;
// parallel collections -- a bad kludge.
// a table model would make this much cleaner
private List<JTextField> marks;
private List<JTextField> weights;
public GradeTablePanel() {
setLayout(new GridBagLayout());
JLabel assgmntLbl = new JLabel(Assignment.ASSIGNMENT, SwingConstants.CENTER);
assgmntLbl.setFont(assgmntLbl.getFont().deriveFont(Font.BOLD));
JLabel markLbl = new JLabel(Assignment.MARK, SwingConstants.CENTER);
markLbl.setFont(markLbl.getFont().deriveFont(Font.BOLD));
JLabel weightLbl = new JLabel(Assignment.WEIGHT, SwingConstants.CENTER);
weightLbl.setFont(weightLbl.getFont().deriveFont(Font.BOLD));
add(assgmntLbl, createGbc(0, 0));
add(markLbl, createGbc(1, 0));
add(weightLbl, createGbc(2, 0));
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.CENTER;
return gbc;
}
public void addAssignment() {
count++;
JLabel countLabel = new JLabel(String.valueOf(count));
JTextField markField = new JTextField(2);
JTextField weightField = new JTextField(2);
add(countLabel, createGbc(0, count));
add(markField, createGbc(1, count));
add(weightField, createGbc(2, count));
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("GradeAnalysis2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GradeAnalysis2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Assignment {
public static final String ASSIGNMENT = "Assignment";
public static final String MARK = "Mark";
public static final String WEIGHT = "Weight";
private String assignment;
private int mark;
private double weight;
public Assignment(String assignment, int mark, double weight) {
this.assignment = assignment;
this.mark = mark;
this.weight = weight;
}
public String getAssignment() {
return assignment;
}
public void setAssignment(String assignment) {
this.assignment = assignment;
}
public int getMark() {
return mark;
}
public void setMark(int mark) {
this.mark = mark;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
You can set the minimum, expected and maximum sizes for each JTextField like so:
JTextField t = new JTextField();
t.setMaximumSize(MAX);
t.setMinimumSize(MIN);
t.setBounds(x, y, width, height);
Where MIN and MAX are a Dimension Object, and the inputs to set bounds are int

Categories

Resources