im training with GUI in Java. So I started creating pet game prototype or smth similar like game.
I have created menu to choose what to do, Register, Info, or Exit aplication.
Created fields and dorpdownBox to choose everything for register.
Also made sumbit button(its very start so i added just max characters validation on petName).
Now im stucked, i dont know how to take all information from dropdownBox and textbox that has been chosen and sent to other class Pet. I have googled but havent found anything that would be clear.
Maybe someone could give me some tips or write part for my code.
I want to take selected PetName , PetType, PetGender to other class pet.
P.s. i have copied many lines from google so I understand only 80-90% my code.
Main.java
import javax.swing.*;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener {
public static void main (String []args){
new Main("Meniu"); // Create title
}
// Main class constructor
public Main(String title) {
super(title);
setMenu(); //create menu
setSize(300, 400);// size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // close running program if window are closed
setLocationRelativeTo(null); // set window position at center
setResizable(false); //resizable or not
show();
}// Main class constructor
// menu choices
JMenuItem Registration, Apie, Exit;
// menu method for creation and style
private void setMenu() {
JMenuBar barObj = new JMenuBar(); // create menuBar obj
JMenu messagesObj = new JMenu("Meniu"); //create menu bar menu object
barObj.setBackground(Color.YELLOW); // set menu bar bg color
Registration = new JMenuItem("Registration");
Registration.setToolTipText("Push to register"); // write text when u hang mouse over
Registration.addActionListener(this);
Registration.setBackground(Color.WHITE); // set menu bar menu options bg color
messagesObj.add(Registration); // add Registration into messages
Apie = new JMenuItem("Apie");
Apie.setToolTipText("Push for information");
Apie.addActionListener(this);
Apie.setBackground(Color.WHITE);
messagesObj.add(Apie);
Exit = new JMenuItem("Exit");
Exit.setToolTipText("Here you will exit");
Exit.addActionListener(this);
Exit.setBackground(Color.WHITE);
messagesObj.add(Exit);
barObj.add(messagesObj);
setJMenuBar(barObj);
} //create menu end
// implemented method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Registration){
int registReply = JOptionPane.showConfirmDialog(this, "Norite registruotis?",
"Išeiti", JOptionPane.YES_NO_OPTION);
if(registReply == JOptionPane.YES_OPTION){ //registReply is what u have choosen
petRegistration ();
}
}else if (e.getSource() == Apie)
JOptionPane.showMessageDialog(this, "Jus esate informacijos lange.", "Apie", JOptionPane.PLAIN_MESSAGE);
else if (e.getSource() == Exit){
int exitReply = JOptionPane.showConfirmDialog(this, "Ar norite Exit?",
"Išeiti", JOptionPane.YES_NO_OPTION);// exitReply is what u have choosen
if(exitReply == JOptionPane.YES_OPTION){// if its has been chose/ program will shutdown
System.exit(0);
}
} // if end
}// actionPerformed
public void petRegistration(){
Container container = getContentPane();
// petName textbox and label
JTextField jtfRegLabel = new JTextField("***Registration***", 25);
jtfRegLabel.setHorizontalAlignment(JTextField.CENTER);
jtfRegLabel.setEditable(false);
JTextField jtfText1 = new JTextField(7);
JTextField jtfNameLabel = new JTextField("Pet Name (min 3, max 16 letters)", 17);
jtfNameLabel.setEditable(false);
jtfText1.setDocument(new JTextFieldLimit(16)); // add limit to text box
// pettype combobox and label
Frame frame = new Frame("Choice");
Label label = new Label("What is your Choice:");
Choice choice = new Choice();
frame.add(choice);
choice.add("Cat ");
choice.add("Dog ");
choice.add("Fish ");
choice.add("Mouse ");
choice.add("Bird ");
choice.add("Horse ");
JTextField jtfTypeLabel = new JTextField("Pet Type, Choose one ", 17);
jtfTypeLabel.setEditable(false);
// petGender combobox and label
Choice choice1 = new Choice();
frame.add(choice1);
choice1.add("Male ");
choice1.add("Female ");
JTextField jtfGenderLabel = new JTextField("Pet Gender, Choose one ", 17);
jtfGenderLabel.setEditable(false);
// submit registration
JButton submitRegObj = new JButton("Submit");
container.add(jtfRegLabel);
container.add(jtfText1);
container.add(jtfNameLabel);
container.add(choice);
container.add(jtfTypeLabel);
container.add(choice1);
container.add(jtfGenderLabel);
container.add(submitRegObj);
container.setLayout(new FlowLayout());
setSize(300, 400); // set size of window
setVisible(true);// set it visible
}
}// Main clases end
Pet.java
public class Pet {
private String petName;
private String petType;
private String petGender;
public Pet(String petName, String petType, String petGender) {
super();
this.petName = petName;
this.petType = petType;
this.petGender = petGender;
}
}
I think JTextFieldLimit class is necessary. Its just make max characters validation.
Thanks.
Firstly, you are mixing frameworks. Swing and AWT components don't play well together. I'd highly recommend against using AWT components and stick to the Swing framework.
Secondly, don't use JTextFields for labels, that's what JLabel is for
Start by taking the fields that are used for registriation and add them to their own JPanel as class instance fields...
public class RegistrationPanel extends JPanel {
JTextField jtfName;
JComboBox cbType;
JComboBox cbSex;
// Constructor and other code //
}
Then, in your RegistrationPanel, provide appropriate setters and getters...
public String getPetName() {
return jtfName.getText();
}
public void setPetName(String name) {
jtfName.setText(name);
}
// Other setters and getters //
This way, when you need it, you can retrieve the values from the panel.
When the user selects the registration menu, you would create a new instance of this panel and add it to your frame. You could even make use of a CardLayout to help switch between views
To make life easier, use enum types for restricted values like type and sex.
I highly recommend that you take the time to read through
Creating a GUI with Swing
Enum Types
Related
I wrote this after seeing videos of thenewboston and then, when I ran, only the last item added was visible and all other textFields [textField1, textField2 and textField3] are not visible. It worked perfectly in his videos but when I tried, only the passwordField was visible. I'm a beginner and I was unable to find what's the problem. Please help me out what is the problem and what should I do to mitigate this error. One small request, please explain a bit detail because I a newbie to Java and GUI.
package learningPackage;
import java.awt.FlowLayout;
//gives the layout
import java.awt.event.ActionListener;
//this makes the field wait for an event.
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JTextField;
//creates a field where we can type text.
import javax.swing.JPasswordField;
//creates a text field where the text typed is hidden with asterics.
class tuna extends JFrame
{
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JPasswordField passwordField;
public tuna()
{
super("Title Text");
textField1 = new JTextField(10);
//sets a the default value of 10.
add(textField1);
textField2 = new JTextField("Enter a Text");
//sets default text of "Enter a Text" without the quotes
add(textField2);
textField3 = new JTextField("Uneditable", 20);
//Displays Uneditable with a default value of 20.
//To make this Uneditable, you must do this...
textField3.setEditable(false);
//this makes the textField uneditable.
add(textField3);
passwordField = new JPasswordField("myPassword");
add(passwordField);
thehandler Handler = new thehandler();
textField1.addActionListener(Handler);
textField2.addActionListener(Handler);
textField3.addActionListener(Handler);
passwordField.addActionListener(Handler);
/*
* The addActionListener method takes an object of Event Handler class.
*
* Therefore, we must create an object of Event Handler Class.
*
*
* The addActionListener method takes an object because, sometimes, we might
* have different classes with different code to execute. So, we pass the object to
* identify which class code is to be executed.
*/
}
class thehandler implements ActionListener
{
/*
* In order to handle events in Java, you need Event handler Class.
* and, that Event Handler Class must implement ActionListener.
*
* What the ActionListener does is that
*
* It will wait for some Event to happen and after that particular event happens,
* it will implement some piece of code.
*/
public void actionPerformed(ActionEvent event)
{
String string = "";
if(event.getSource()==textField1)
string = String.format("Text Field 1 : %s", event.getActionCommand());
else if(event.getSource()==textField2)
string = String.format("Text Field 2 : %s", event.getActionCommand());
else if(event.getSource()==textField3)
string = String.format("Text Field 3 : %s", event.getActionCommand());
else if(event.getSource()==passwordField)
string = String.format("Password Field : %s", event.getActionCommand());
//when the user presses enter key after entering text, this actually stores the
//thing entered into the String.
JOptionPane.showConfirmDialog(null, string);
}
}
}
public class Apples {
public static void main(String[] args)
{
tuna Srivathsan = new tuna();
Srivathsan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this would close the window when X button is pressed.
Srivathsan.setSize(500, 500);
Srivathsan.setVisible(true);
Srivathsan.setLocationRelativeTo(null);
}
}
Here is the image of the window :
import java.awt.FlowLayout;
//gives the layout
That statement imports the layout & makes it available to the code, but does not set the layout on any container.
While a JPanel has a default layout of FlowLayout, the default layout of the (content pane of the) JFrame is BorderLayout. A BorderLayout accepts up to 5 components or containers (like JPanel) in each of 5 constraints. If no constraint is given, it defaults to the CENTER. If more than one component is added to the CENTER (or any other area of a BorderLayout), all but one of those components will fail to appear. I cannot recall if it is the first or last that appears, but it's a moot point, because the code should not do that.
My advice would be as follows:
Don't extend JFrame (or JPanel).
Add one JPanel to the JFrame.
Add the components (and/or containers) to that JPanel.
Here is an example implementing points 2 & 3. Point 1 is not implemented (batteries not included).
import javax.swing.*;
public class SingleComponentLayoutProblem extends JFrame {
private final JTextField textField1;
private final JTextField textField2;
private final JTextField textField3;
private final JPasswordField passwordField;
public SingleComponentLayoutProblem() {
super("Title Text");
JPanel panel = new JPanel(); // uses FlowLayout be DEFAULT
add(panel);
textField1 = new JTextField(10);
//sets a the default value of 10.
panel.add(textField1);
textField2 = new JTextField("Enter a Text");
//sets default text of "Enter a Text" without the quotes
panel.add(textField2);
textField3 = new JTextField("Uneditable", 20);
//Displays Uneditable with a default value of 20.
//To make this Uneditable, you must do this...
textField3.setEditable(false);
//this makes the textField uneditable.
panel.add(textField3);
passwordField = new JPasswordField("myPassword");
panel.add(passwordField);
}
public static void main(String[] args) {
Runnable r = () -> {
SingleComponentLayoutProblem sclp =
new SingleComponentLayoutProblem();
sclp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this would close the window when X button is pressed.
// don't guess sizes! ..
//sclp.setSize(500, 500);
// .. instead ..
sclp.pack();
sclp.setVisible(true);
sclp.setLocationRelativeTo(null);
};
SwingUtilities.invokeLater(r);
}
}
I have a school assignment where I have to create a java GUI and add pizzas to an array list. The array list is in a separate Order class. This is my first time using a GUI in Java so I'm still trying to figure things out.
The problem is, if I initialize the order class during the button click event, each time I press the 'add pizza to order' button, it recreates the order class and array list and starts over. If I initialize the order class outside of the button click event, it isn't recognized inside the click event method.
I also tried initializing the class in the main method with no luck. I will post the main method class below. Keep in mind there is also an Order class and a Pizza class.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Creating the FirstGUI class to hold the main method and GUI code
public class FirstGUI extends JFrame implements ActionListener {
// Labels to give directions to the customer
public JLabel labelSelectPizzaSize = new JLabel("Please Select a Size for Your Pizza: [S]mall, [M]edium, or [L]arge");
public JLabel labelSelectPizzaCrust = new JLabel("Please Select a Crust Type: [Thick] or [Thin]");
public JLabel labelHasPepperoni = new JLabel("Do You Want Pepperoni? [Y]es or [N]o");
public JLabel labelTotalBakeTime = new JLabel("Total Bake Time: ");
public JLabel labelOrderTotal = new JLabel("Order Total: ");
// Text boxes for customer input
public JTextField textEnterPizzaSize = new JTextField(5);
public JTextField textEnterPizzaCrust = new JTextField(5);
public JTextField textHasPepperoni = new JTextField(5);
// Button to add pizza to order
public JButton buttonAddPizzaToOrder = new JButton("Add Pizza to Order");
// Main method
public static void main(String[] args) {
// Creating a new class instance
new FirstGUI();
}
FirstGUI() {
// Setting visibility to true
this.setVisible(true);
// Setting the default close operation
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creating panels
JPanel panelMain = new JPanel();
JPanel panelPizzaSize = new JPanel();
JPanel panelPizzaCrust = new JPanel();
JPanel panelPizzaTopping = new JPanel();
JPanel panelButtons = new JPanel();
JPanel panelOrderInfo = new JPanel();
// Setting the layout for the ain panel
panelMain.setLayout(new BoxLayout(panelMain, BoxLayout.Y_AXIS));
// Adding ActionListner to the "Add Pizza To Order" button.
buttonAddPizzaToOrder.addActionListener(this);
// Adding labels, text fields, and buttons to the panels and then adding panels to the main panel.
panelPizzaSize.add(labelSelectPizzaSize);
panelPizzaSize.add(textEnterPizzaSize);
panelPizzaCrust.add(labelSelectPizzaCrust);
panelPizzaCrust.add(textEnterPizzaCrust);
panelPizzaTopping.add(labelHasPepperoni);
panelPizzaTopping.add(textHasPepperoni);
panelButtons.add(buttonAddPizzaToOrder);
panelMain.add(panelPizzaSize);
panelMain.add(panelPizzaCrust);
panelMain.add(panelPizzaTopping);
panelMain.add(panelButtons);
panelOrderInfo.add(labelTotalBakeTime);
panelOrderInfo.add(labelOrderTotal);
panelMain.add(panelOrderInfo);
// I'm not sure what this does.
this.getContentPane().add(panelMain);
// Setting size of the main panel.
this.setSize(475, 250);
}
// Method to create a pizza and add it to the array list when the "Add Pizza To Order" button is pressed.
public void actionPerformed(ActionEvent event1) {
try {
String a;
String b;
String c;
a = textEnterPizzaSize.getText().toUpperCase();
b = textEnterPizzaCrust.getText().toUpperCase();
c = textHasPepperoni.getText().toUpperCase();
Order O = new Order();
O.addPizza(new Pizza(a, b, c));
labelTotalBakeTime.setText("Total Bake Time: " + Double.toString(O.calculateBakeTime()));
labelOrderTotal.setText("- Order Total: " + Double.toString(O.calculateCost()));
// Conformation message when a pizza is added to the order.
JOptionPane.showMessageDialog(null, "Size: " + a + ", Crust: " + b + ", Pepperoni: " + c,
"Pizza Successfully Added To Order", JOptionPane.INFORMATION_MESSAGE);
}
// Exception and ERROR message handling
catch (MyException me) {
JOptionPane.showMessageDialog(null, me, "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
}
Try this approach,
Add a class variable to hold your order
private Order order;
Then,
public static void main( String[] args )
{
// Creating a new class instance
Order order = new Order(); // Create order here
new FirstGUI( order ); // Pass the order to the constructor
}
Initialize the order inside the constructor
FirstGUI( Order order )
{
this.order = order;
// other remaining code
}
In the actionPerformed method, add pizze to this order
order.addPizza( new Pizza( a, b, c ) );
I want to be able to pass user input from my GUI to one of my classes. However, the input is not passed over and immediately checks the if statement.
How do I get program to wait for the input and only checks after the button is clicked?
Main class
public class MainTest {
public static void main(String[] args) {
String weaponCategory;
//Create Java GUI
GUITest window = new GUITest();
if(window.getCategory() != "")
{
System.out.println("test");
}
}
}
GUITest class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITest implements ActionListener{
private JFrame frmInventorysystem;
private JPanel frameBottom;
private JComboBox equipList;
private String category = "";
private JButton confirmBtn, cancelBtn;
/**
* Create the application.
*/
public GUITest()
{
frmInventorysystem = new JFrame();
frmInventorysystem.setTitle("InventorySystem");
frmInventorysystem.setBounds(100, 100, 450, 300);
frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));
frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*JFrame inside another JFrame is not recommended. JPanels are used instead.
* Creating a flow layout for the bottom frame
*/
frameBottom = new JPanel();
frameBottom.setLayout(new FlowLayout());
//creates comboBox to find out which of the three items player is looking to insert
String[] weaponCategories = {"Weapon", "Armor", "Mod"};
equipList = new JComboBox(weaponCategories);
frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);
//Converting BorderLayout.south into a flow layout
frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);
confirmBtn = new JButton("Confirm");
confirmBtn.addActionListener(this);
frameBottom.add(confirmBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(this);
frameBottom.add(cancelBtn);
frmInventorysystem.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
//creates new windows to sort equipment when confirmBtn is clicked
if(e.getSource() == confirmBtn)
{
if(equipList.getSelectedItem().equals("Weapon"))
{
//GUIWeaponCategory weapon = new GUIWeaponCategory();
category = equipList.getSelectedItem().toString();
}
}
//Exits when cancelBtn is clicked
if(e.getSource() == cancelBtn)
{
System.exit(0);
}
}
public String getCategory()
{
return category;
}
public void setCategory(String a)
{
category = a;
}
}
GUITest launches as expected.
However, the first println is missing.
How would I go about doing this?
What concepts or pieces of code am I missing?
EDIT1: Added a couple more details to make the program reproducible and complete.
EDIT2: Making the code more readable for easy understanding.
There are some changes to make on your program
Remove extends JFrame as stated in my comments above, see Extends JFrame vs. creating it inside the program
Place your program on the EDT, see point #3 on this answer and the main method for an example on how to do that.
You're confused about how the ActionListeners work, they wait until you perform certain action in your program (i.e. you press Confirm button) and then do something. "Something" in your program means: Print the selected item and check if it's a weapon then, do something else.
So, in this case, you don't need to return back to main to continue with your program, main only serves to initialize your application and nothing else. You need to think in the events and not in a sequential way. That's the tricky and most important part.
You need to change your programming paradigm from console applications and do-while that everything happens in a sequential manner rather than events that are triggered when the user does something with your application.
For example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITest implements ActionListener {
private JFrame frmInventorysystem;
private JPanel frameBottom;
private JComboBox equipList;
private JButton confirmBtn, cancelBtn;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new GUITest()); //Java 8+ if using an earlier version check the point #2 in this answer and modify the code accordingly.
}
/**
* Create the application.
*/
public GUITest() {
frmInventorysystem = new JFrame();
frmInventorysystem.setTitle("InventorySystem");
frmInventorysystem.setBounds(100, 100, 450, 300);
frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));
/*
* JFrame inside another JFrame is not recommended. JPanels are used instead
* Creating a flow layout for the bottom frame
*/
frameBottom = new JPanel();
frameBottom.setLayout(new FlowLayout());
// creates comboBox to find out which of the three items player is looking to
// insert
String[] weaponCategories = { "Weapon", "Armor", "Mod" };
equipList = new JComboBox(weaponCategories);
frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);
// Converting BorderLayout.south into a flow layout
frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);
confirmBtn = new JButton("Confirm");
confirmBtn.addActionListener(this);
frameBottom.add(confirmBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(this);
frameBottom.add(cancelBtn);
frmInventorysystem.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// creates new windows to sort equipment when confirmBtn is clicked
if (e.getSource() == confirmBtn) {
String category = equipList.getSelectedItem().toString(); //Get the selected category
doSomething(category); //Pass it as a parameter
}
// Exits when cancelBtn is clicked
if (e.getSource() == cancelBtn) {
frmInventorysystem.dispose();
}
}
// Do something with the category
private void doSomething(String selectedEquipment) {
System.out.println(selectedEquipment);
if (selectedEquipment.equals("Weapon")) {
System.out.println("It's a weapon!"); //You can open dialogs or do whatever you need here, not necessarily a print.
} else {
System.out.println("Not a weapon");
}
}
}
Notice that I removed inheritance, I'm not returning back to main and still printing the selected item and checking if it's a weapon or not.
I also exit the application in a safer way.
This is a sample output:
Weapon
It's a weapon!
Armor
Not a weapon
Hello I have a problem with my comboBox. In app that im making my panel has a combo box with two choices and a button next to the combo box to proceed to the choice selected in the combo box but instead both if Statements run and no I have no idea why.
Combo box code is simple private JComboBox mainChoice = new JComboBox();
mainChoice.addItem("") etc...
class mainPanelGoButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String choice = (String)mainChoice.getSelectedItem();
System.out.printf(choice);
if(choice == "View Passenger Details");
{
JTextField first = new JTextField();
JTextField last = new JTextField();
Object[] message = {
"First Name:", first,
"Last Name:", last
};
int option = JOptionPane.showConfirmDialog(null, message, "Enter passenger name", JOptionPane.PLAIN_MESSAGE);
if (option == JOptionPane.OK_OPTION)
{
// Load passenger data
p = dataHandler.getPassengerData(first.getText(), last.getText());
if(p != null)
{
updateTextfields( p);
// Display passenger data
getContentPane().removeAll();
getContentPane().add(passengerDetailsPanel);
setSize(400,340);
setLocationRelativeTo(null);
validate();
repaint();
printAll(getGraphics());
}
}
}
if(choice == "Add New Passenger")
{
if(displayPassengerInputForm());
{
// Display passenger data
getContentPane().removeAll();
getContentPane().add(passengerDetailsPanel);
setSize(400,340);
setLocationRelativeTo(null);
validate();
repaint();
printAll(getGraphics());
}
}
}
}
// EXAMPLE OF MY PROGRAM THAT RETURNS BOTH WINDOW A and WINDOW B
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame extends JFrame
{
private JPanel mainPanel = new JPanel();
private JComboBox<String> mainChoice = new JComboBox<String>();
private JButton goButton = new JButton("GO");
public Frame()
{
createMainPanel();
this.add(mainPanel);
}
private void createMainPanel()
{
// Fill choice box
mainChoice.addItem("Find Passenger");
mainChoice.addItem("Add New Passenger");
// Set button
goButton.addActionListener(new mainPanelGoButtonListener());
goButton.setPreferredSize(new Dimension(5,5));
// Add to main panel
mainPanel.setLayout(new GridLayout(1,2,4,4));
mainPanel.add(mainChoice);
mainPanel.add(goButton);
}
class mainPanelGoButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(mainChoice.getSelectedItem().equals("Find Passenger"));
{
// DISPLAYS WINDOW FOR INPUT
System.out.printf(" WINDOW A ");
}
if(mainChoice.getSelectedItem().equals("Add New Passenger"));
{
// DISPLAYS WINDOW FOR INPUT
System.out.printf(" WINDOW B ");
}
}
}
public static void main(String args[])
{
Frame frame = new Frame();
frame.setTitle("SSD Project");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(400,50);
frame.setVisible(true);
}
}
Each time I press a button it prints out both Window A and Window B instead of one
One problem I see is that you use == to compare Strings.
Don't use == to compare Strings as this compares if two String objects are the same, something that you are not interested in testing. Use the equals(...) or equalsIgnoreCase(...) method which tests if two Strings contain the same characters, in the same order, with or without the same case respectively, and this is what you are really interested in.
Next: be sure you use if (something) { xxxx } else if (somethingElse) { xxxx } to be sure that only one if block gets performed.
Next: look up the CardLayout which will allow your GUI to change views much more cleanly.
Edit
You ask:
do you mean: mainChoice.getSelectedItem().equals("Add New Passenger") ?? cause im still getting the same result ;
Yes, exactly. But on further reflection, your code above cannot be causing both if blocks to fire as the String == can't be true for both test Strings. Something else is causing your problem.
could you give me some quick example?
Actually it would be better if you could create and post a minimal runnable program that reproduces your problem for us.
I'm learning Java and GUI. I have some questions, and the first is if there are any major difference between creating a subclass of JFrame and an instance of JFrame. It seems like like a subclass is more powerful? I also wonder if it's necessary to use this code when creating a GUI:
Container contentPane = getContentPane();
contentPane.setLayot(new Flowlayout());
I add my GUI class, it's a simple test so far, to a task that I have to hand in. When a user has entered some text in the textfield and press the button to continue to the next step, how do I do to clear the frame and show a new content or is there a special way to do this is in Java? I guess there must be better to use the same window instead of creating a new!? Help id preciated! Thanks
// Gui class
import java.awt.FlowLayout; // layout
import java.awt.event.ActionListener; // listener
import java.awt.event.ActionEvent; // event
import javax.swing.JFrame; // windows properties
import javax.swing.JLabel; // row of text
import javax.swing.JTextField; // enter text
import javax.swing.JOptionPane; // pop up dialog
import javax.swing.JButton; // buttons
// import.javax.swing.*;
public class Gui extends JFrame {
private JLabel text1;
private JTextField textInput1;
private JTextField textInput2;
private JButton nextButton;
// constructor creates the window and it's components
public Gui() {
super("Bank"); // title
setLayout(new FlowLayout()); // set default layout
text1 = new JLabel("New customer");
add(text1);
textInput1 = new JTextField(10);
add(textInput1);
nextButton = new JButton("Continue");
add(nextButton);
// create object to handle the components (action listener object)
frameHandler handler = new frameHandler();
textInput1.addActionListener(handler);
nextButton.addActionListener(handler);
}
// handle the events (class inside another class inherits contents from class outside)
private class frameHandler implements ActionListener {
public void actionPerformed(ActionEvent event){
String input1 = "";
// check if someone hits enter at first textfield
if(event.getSource() == textInput1){
input1 = String.format(event.getActionCommand());
JOptionPane.showMessageDialog(null, input1);
}
else if(event.getSource() == nextButton){
// ??
}
}
}
}
This small code might help you explain things :
import java.awt.event.*;
import javax.swing.*;
public class FrameDisplayTest implements ActionListener
{
/*
* Creating an object of JFrame instead of extending it
* has no side effects.
*/
private JFrame frame;
private JPanel panel, panel1;
private JTextField tfield;
private JButton nextButton, backButton;
public FrameDisplayTest()
{
frame = new JFrame("Frame Display Test");
// If you running your program from cmd, this line lets it comes
// out of cmd when you click the top-right RED Button.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel1 = new JPanel();
tfield = new JTextField(10);
nextButton = new JButton("NEXT");
backButton = new JButton("BACK");
nextButton.addActionListener(this);
backButton.addActionListener(this);
panel.add(tfield);
panel.add(nextButton);
panel1.add(backButton);
frame.setContentPane(panel);
frame.setSize(220, 220);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (tfield.getText().length() > 0)
{
if (button == nextButton)
{
/*
* this will remove the first panel
* and add the new panel to the frame.
*/
frame.remove(panel);
frame.setContentPane(panel1);
}
else if (button == backButton)
{
frame.remove(panel1);
frame.setContentPane(panel);
}
frame.validate();
frame.repaint(); // prefer to write this always.
}
}
public static void main(String[] args)
{
/*
* This is the most important part ofyour GUI app, never forget
* to schedule a job for your event dispatcher thread :
* by calling the function, method or constructor, responsible
* for creating and displaying your GUI.
*/
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new FrameDisplayTest();
}
});
}
}
if you want to switch (add then remove) JComponents, then you have to
1) add/remove JComponents and then call
revalidate();
repaint()// sometimes required
2) better and easiest choice would be implements CardLayout
If your requirement is to make a wizard, a panel with next and prev buttons, and on clicking next/prev button showing some component. You could try using CardLayout.
The CardLayout manages two or more components (usually JPanel instances) that share the same display space. CardLayout let the user choose between the components.
How to Use CardLayout
If your class extends JFrame, you can do:
getContentPane().removeAll();