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?).
Related
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());
}
}
I was testing something with JPanel. When I added random text to the JTextArea inside it, it kept increasing the size of the JPanel until it reached the edge.
How do I keep the text inside the JPanel without stretching it?
public class Game
{
TitleScreenHandler tsHandler = new TitleScreenHandler();
ChoiceHandler choiceHandler = new ChoiceHandler();
ComponentHandler compHandler = new ComponentHandler();
GridBagConstraints gbc = new GridBagConstraints();
Border whiteline = BorderFactory.createLineBorder(Color.WHITE);
JFrame window;
Container con;
JPanel titlePanel , startPanel, mainTextPanel, choiceButtonPanel, playerPanel;
JLabel titleLabel, hpLabel, hpLabelNumber, weaponLabel, weaponLabelName;
public static JButton startButton, choice1,choice2,choice3,choice4,choice5,choice6,choice7,choice8;
public static JTextArea mainTextArea;
Font titleFont = new Font("Times New Roman", Font.PLAIN, 100);
Font normalFont = new Font("Times New Roman", Font.PLAIN, 30);
public static String playerName;
public static String weapon,position;
public static int playerHP;
public static int weaponDamage;
public static void main(String[] args)
{
new Game();
}
public Game()
{
window = new JFrame();
window.setSize(1440,900);
window.setTitle("W: " + window.getWidth() + " H: " + window.getHeight());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.black);
window.setLayout(new GridBagLayout());
con = window.getContentPane();
//Panels are used to make sections in the window (Background)
//Labels are used to write in the sections/panels (Foreground)
//Buttons can be pressed inside Panels
//To make a text you need to design a panel, design its size/color,
//Design its text the same way, then add it to the panel
titlePanel = new JPanel();
titlePanel.setBounds(100, 100, 1080 , 150);
titlePanel.setBackground(Color.black);
titleLabel = new JLabel("Adventure");
titleLabel.setForeground(Color.white);
titleLabel.setFont(titleFont);
startPanel = new JPanel();
startPanel.setBounds(540, 600, 200, 100);
startPanel.setBackground(Color.black);
startButton = new JButton("START");
startButton.setBackground(Color.black);
startButton.setForeground(Color.white);
startButton.setFont(normalFont);
startButton.addActionListener(tsHandler);
window.addComponentListener(compHandler);
titlePanel.add(titleLabel);
startPanel.add(startButton);
con.add(titlePanel, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
con.add(startPanel, gbc);
window.setVisible(true);
}
public void createGameScreen()
{
titlePanel.setVisible(false);
startButton.setVisible(false);
mainTextPanel = new JPanel();
//mainTextPanel.setBounds(100, 100, 1080, 250);
mainTextPanel.setBackground(Color.black);
mainTextPanel.setBorder(whiteline);
mainTextArea = new JTextArea("This is the main text area");
mainTextArea.setBounds(100,100,1080,250);
mainTextArea.setBackground(Color.black);
mainTextArea.setForeground(Color.white);
mainTextArea.setLayout(new GridLayout());
mainTextArea.setFont(normalFont);
mainTextArea.setLineWrap(true);
mainTextArea.setWrapStyleWord(true);
playerPanel = new JPanel();
playerPanel.setBounds(100, 100, 1080, 50);
playerPanel.setBackground(Color.blue);
playerPanel.setLayout(new GridLayout(1,4));
choiceButtonPanel = new JPanel();
choiceButtonPanel.setBounds(500, 350, 300, 250);
choiceButtonPanel.setLayout(new GridLayout(2,4, 50, 50));
choiceButtonPanel.setBackground(Color.red);
choice1 = new JButton("Choice 1");
choice1.setBackground(Color.black);
choice1.setForeground(Color.white);
choice1.setFont(normalFont);
choice1.setFocusPainted(false);
choice1.addActionListener(choiceHandler);
choice1.setActionCommand("c1");
choiceButtonPanel.add(choice1);
choice2 = new JButton("Choice 2");
choice2.setBackground(Color.black);
choice2.setForeground(Color.white);
choice2.setFont(normalFont);
choice2.setFocusPainted(false);
choice2.addActionListener(choiceHandler);
choice2.setActionCommand("c2");
choiceButtonPanel.add(choice2);
choice3 = new JButton("Choice 3");
choice3.setBackground(Color.black);
choice3.setForeground(Color.white);
choice3.setFont(normalFont);
choice3.setFocusPainted(false);
choice3.addActionListener(choiceHandler);
choice3.setActionCommand("c3");
choiceButtonPanel.add(choice3);
choice4 = new JButton("Choice 4");
choice4.setBackground(Color.black);
choice4.setForeground(Color.white);
choice4.setFont(normalFont);
choice4.setFocusPainted(false);
choice4.addActionListener(choiceHandler);
choice4.setActionCommand("c4");
choiceButtonPanel.add(choice4);
choice5 = new JButton("Choice 5");
choice5.setBackground(Color.black);
choice5.setForeground(Color.white);
choice5.setFont(normalFont);
choice5.setFocusPainted(false);
choice5.addActionListener(choiceHandler);
choice5.setActionCommand("c5");
choiceButtonPanel.add(choice5);
choice6 = new JButton("Choice 6");
choice6.setBackground(Color.black);
choice6.setForeground(Color.white);
choice6.setFont(normalFont);
choice6.setFocusPainted(false);
choice6.addActionListener(choiceHandler);
choice6.setActionCommand("c6");
choiceButtonPanel.add(choice6);
choice7 = new JButton("Choice 7");
choice7.setBackground(Color.black);
choice7.setForeground(Color.white);
choice7.setFont(normalFont);
choice7.setFocusPainted(false);
choice7.addActionListener(choiceHandler);
choice7.setActionCommand("c7");
choiceButtonPanel.add(choice7);
choice8 = new JButton("Choice 8");
choice8.setBackground(Color.black);
choice8.setForeground(Color.white);
choice8.setFont(normalFont);
choice8.setFocusPainted(false);
choice8.addActionListener(choiceHandler);
choice8.setActionCommand("c8");
choiceButtonPanel.add(choice8);
gbc.anchor = GridBagConstraints.PAGE_END;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
con.add(playerPanel,gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
//gbc.ipadx = 750;
gbc.ipady = 1000;
gbc.gridwidth = 2;
gbc.gridx = 1;
gbc.gridy = 0;
con.add(mainTextPanel,gbc);
gbc.fill = GridBagConstraints.NONE;
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.gridx = 1;
gbc.gridy = 5;
con.add(choiceButtonPanel,gbc);
hpLabel = new JLabel("HP: ");
hpLabel.setFont(normalFont);
hpLabel.setForeground(Color.white);
hpLabelNumber = new JLabel();
hpLabelNumber.setFont(normalFont);
hpLabelNumber.setForeground(Color.white);
weaponLabel = new JLabel("Weapon: ");
weaponLabel.setFont(normalFont);
weaponLabel.setForeground(Color.white);
weaponLabelName = new JLabel();
weaponLabelName.setFont(normalFont);
weaponLabelName.setForeground(Color.white);
playerPanel.add(hpLabel);
playerPanel.add(hpLabelNumber);
playerPanel.add(weaponLabel);
playerPanel.add(weaponLabelName);
mainTextPanel.add(mainTextArea, BorderLayout.PAGE_START);
playerSetup();
}
public void playerSetup()
{
playerHP = 15;
weapon = "Fists";
weaponLabelName.setText(weapon);
hpLabelNumber.setText("" + playerHP);
ForestEvents.townGate();
}
/*public void townGate()
{
position = "towngate";
mainTextArea.setText("You are at the gates of the town. A guard is standing in front of you. What do you do?");
choice1.setText("Talk to the Guard");
choice2.setText("Attack the Guard");
choice3.setText("Leave");
choice4.setText("");
}*/
public void talkGuard()
{
position = "talkguard";
mainTextArea.setText("Guard: Hello Stranger. I have never seen you before. I'm sorry but I cannot let you enter.");
choice1.setText("Go Back");
choice2.setText("");
choice3.setText("");
choice4.setText("");
}
public void attackGuard()
{
position = "attackguard";
mainTextArea.setText("Guard: HOW DARE YOU!\nThe guard fought back and hit you hard.\n(You received 3 damage)");
playerHP -= 3;
hpLabelNumber.setText("" + playerHP);
choice1.setText("Go Back");
choice2.setText("");
choice3.setText("");
choice4.setText("");
}
public void crossRoad()
{
position = "crossroads";
mainTextArea.setText("You are at the crossroad.\n Go south to go back to the town.");
choice1.setText("Go North");
choice2.setText("Go East");
choice3.setText("Go South");
choice4.setText("Go West");
}
public class ComponentHandler implements ComponentListener
{
public void componentResized(ComponentEvent e)
{
Component c = (Component)e.getSource();
window.setTitle("W: " + c.getWidth() + " H: " + c.getHeight());
}
#Override
public void componentHidden(ComponentEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void componentMoved(ComponentEvent e)
{
}
#Override
public void componentShown(ComponentEvent e)
{
}
}
public class TitleScreenHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
createGameScreen();
}
}
public class ChoiceHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String yourChoice = event.getActionCommand();
switch (position)
{
case "towngate":
switch(yourChoice)
{
case "c1":
talkGuard();
break;
case "c2":
attackGuard();
break;
case "c3":
crossRoad();
break;
case "c4":
break;
}
break;
case "talkguard":
switch(yourChoice)
{
case "c1":
ForestEvents.townGate();
break;
}
break;
case "attackguard":
switch(yourChoice)
{
case "c1":
ForestEvents.townGate();
break;
}
break;
case "crossroad":
switch(yourChoice)
{
case"c1":
break;
case"c2":
break;
case"c3":
ForestEvents.townGate();
break;
case"c4":
break;
}
break;
}
}
}
}
Edit: Added the rest of the code and added the textarea to the scrollpane and the scrollpane to the Jpanel now the text isnt showing up in the panel.
import javax.swing.JTextArea;
public class ForestEvents
{
String pos;
int hp;
public ForestEvents()
{
pos = Game.position;
hp = Game.playerHP;
}
public static void townGate()
{
Game.position = "towngate";
Game.mainTextArea.setText("You are at the gates of the town. A guard is standing in front of you. What do you do? \na\nas\n\n\n\n\\n"
+ "\n\n\n\1\n1\n\n\n\n\n\\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n1\n1\n2\n2\n3\n4\n6");
Game.choice1.setText("Talk to the Guard");
Game.choice2.setText("Attack the Guard");
Game.choice3.setText("Leave");
Game.choice4.setText("");
}
}
You will want to get your JTextArea into JScrollPane, as Adeel said in the comments (+1), then control it with GridBagLayout. No need to set component bounds, preferred size etc. If you want to use GridBagLayout, you have to learn how weights work with fill and anchor. In code below change gbc.fill HORIZONTAL to VERTICAL and swap weights I used for adding scroll to window (so it should be weightx=0,y=1), or change fill to BOTH and make both weights equal to 1 (in this case, you can comment out this empty JLabel I added at the end). Observe and learn.
In your code, you're not setting weights. So, as you may have guessed, everything has the same weight. mainTextArea is added while gbc.fill is HORIZONTAL, no weights and is not inside JScrollPane - that's why it stretches. And be careful with ipads.
SSCCE (comments in code)
public class DontStretchMyTextArea {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setSize(1440, 900);
window.setTitle("W: " + window.getWidth() + " H: " + window.getHeight());
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
window.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTH;
gbc.insets = new Insets(10, 10, 10, 10);
JTextArea mainTextArea = new JTextArea( "This is the main text area" , 10 , 30 ); //here you can set how many rows/columns you want,
//but anyway GridBagLayout will recalculate size of component
//based on gbc.fill, weights and surrounding components
//mainTextArea.setLayout(new GridLayout());
mainTextArea.setLineWrap(true);
mainTextArea.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(mainTextArea);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints panelGBC = new GridBagConstraints();
panelGBC.weightx = 1; //I want to fill whole panel with JTextArea
panelGBC.weighty = 1; //so both weights =1
panelGBC.fill = GridBagConstraints.BOTH; //and fill is set to BOTH
panel.add(scroll, panelGBC);
panel.setBackground(Color.gray);//this shouldn't be visible
gbc.weightx = 1;
gbc.weighty = 0;
window.add(panel, gbc);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx++;
window.add(new JLabel(), gbc); //GridBagLayout always needs component with both weights =1
SwingUtilities.invokeLater(() -> { //we get our frame on EDT
window.pack();
window.setVisible(true);
});
}
}
How to use GridBagLayout
You can also add scroll directly to window. panel was created just for illustration purposes.
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);
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! :)
My code has a JPanel that contains three collapsible JPanels. The outer JPanel uses the BoxLayout to stack the three JPanels vertically. However, when I collapse a JPanel, the top JPanel will always expands to fill the region (even if I setMaximumSize() or such), whereas I want the lower JPanels to expand upward. It is generally glitchy. I was looking at the GridBagLayout, would that be more suitable for this sort of endeavor?
Thanks.
This is a VB image of what I dream about in my wildest dreams (images with title "Vertical Panels"):
http://www.codeproject.com/KB/cpp/CollapsiblePanelVB.aspx
I don't know what a collapsable panel is. Does it collapse all the way to 0, or does is have a minimum height?
If you manage the maximum size to always equal the preferred size then you should be able to use a BoxLayout. Just make sure you also use:
panel.add( Box.createVerticalGlue() );
at the bottom of your panel to allow the extra space to be used by the glue.
It would take me forever to cut out a compilable snippet from the 500 lines of garbage sprawled out before me.
And that is the reason for creating a SSCCE and forgetting about your garbage code. All you need is a panel with 3 collapsable panels. Then you add a button to collapse the panel and see what happens. Its better to start with demo code then write 500 lines of code and find out it doesn't work.
I strongly suggest MigLayout. It's very powerful and very easy to use. It's also widely used.
or old classic based on GridBagLayout
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ExpansiblePanel {
public static void main(String[] args) {
CollapsablePanel cp = new CollapsablePanel("test", buildPanel());
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(cp));
f.setPreferredSize(new Dimension(360, 200));
f.setLocation(150, 150);
f.pack();
f.setVisible(true);
}
public static JPanel buildPanel() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 1, 2, 1);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
JPanel p1 = new JPanel(new GridBagLayout());
gbc.gridwidth = GridBagConstraints.RELATIVE;
p1.add(new JButton("button 1"), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
p1.add(new JButton("button 2"), gbc);
gbc.gridwidth = GridBagConstraints.RELATIVE;
p1.add(new JButton("button 3"), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
p1.add(new JButton("button 4"), gbc);
p1.setBackground(Color.blue);
return p1;
}
private ExpansiblePanel() {
}
}
class CollapsablePanel extends JPanel {
private static final long serialVersionUID = 1L;
private boolean selected;
private JPanel contentPanel_;
private HeaderPanel headerPanel_;
private class HeaderPanel extends JPanel implements MouseListener {
private static final long serialVersionUID = 1L;
private String text_;
private Font font;
private BufferedImage open, closed;
final int OFFSET = 30, PAD = 5;
HeaderPanel(String text) {
addMouseListener(this);
text_ = text;
font = new Font("sans-serif", Font.PLAIN + Font.BOLD, 12);
// setRequestFocusEnabled(true);
setPreferredSize(new Dimension(200, 25));
setBackground(Color.black);
setForeground(Color.red);
int w = getWidth();
int h = getHeight();
/*try {
open = ImageIO.read(new File("images/arrow_down_mini.png"));
closed = ImageIO.read(new File("images/arrow_right_mini.png"));
} catch (IOException e) {
e.printStackTrace();
}*/
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int h = getHeight();
/*if (selected)
g2.drawImage(open, PAD, 0, h, h, this);
else
g2.drawImage(closed, PAD, 0, h, h, this);
*/ // Uncomment once you have your own images
g2.setFont(font);
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = font.getLineMetrics(text_, frc);
float height = lm.getAscent() + lm.getDescent();
float x = OFFSET;
float y = (h + height) / 2 - lm.getDescent();
g2.drawString(text_, x, y);
}
#Override
public void mouseClicked(MouseEvent e) {
toggleSelection();
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
}
CollapsablePanel(String text, JPanel panel) {
super(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(1, 3, 0, 3);
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
selected = false;
headerPanel_ = new HeaderPanel(text);
setBackground(Color.orange);
contentPanel_ = panel;
add(headerPanel_, gbc);
add(contentPanel_, gbc);
contentPanel_.setVisible(false);
JLabel padding = new JLabel();
gbc.weighty = 1.0;
add(padding, gbc);
}
public void toggleSelection() {
selected = !selected;
if (contentPanel_.isShowing()) {
contentPanel_.setVisible(false);
} else {
contentPanel_.setVisible(true);
}
revalidate();
headerPanel_.repaint();
}
}