Only single item is visible in the JFrame Window - java

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

Related

Most efficient way of using an action listener in Java?

I was tasked with creating a program that displays a numeric keypad (like one on a phone) and has a screen that displays the numbers that are picked. Also included is a clear button that clears the screen.
In creating my program, I created three classes. The Phone class simply creates a JFrame that adds a PhonePanel to the screen. The PhonePanel class adds a JLabel which acts as a screen, a JButton which acts as a clear button, and a KeypadPanel which is a GridLayout of JButtons which acts as the numeric keys.
The clear button and numeric buttons both use separate action listeners. Is this the most efficient way of going about this? Is there a way I can use one action listener instead of two?
// ******************************************************************************************
// Phone.java
// David Read
// This class creates a JFrame that contains a PhonePanel. The PhonePanel provides a
// user interface that allows one to input numeric symbols on a screen and allows clearing
// of the screen.
// ******************************************************************************************
package lab5;
import javax.swing.JFrame;
public class Phone {
public static void main(String[] args)
{
// Create a JFrame object.
JFrame frame = new JFrame ("Phone");
// Set the default close operation for the JFrame.
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// Add a Phone panel to the screen.
frame.getContentPane().add(new PhonePanel());
frame.pack();
frame.setVisible(true);
}
}
// ******************************************************************************************
// PhonePanel.java
// David Read
// This class creates a JPanel that includes an output label which displays inputed numeric
// symbols, a clear button that clears what is displayed on the output label, and a KeypadPanel
// which displays a GridLayout of buttons that when pressed, display their corresponding symbols
// on the output label.
// ******************************************************************************************
package lab5;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PhonePanel extends JPanel
{
private static JLabel labelOutput;
private JButton buttonClear;
//-----------------------------------------------------------------------
// Creates a JPanel that arranges three objects in a Border layout. The
// north component contains a JLabel, the east component contains a JButton
// and the center component contains a KeypadPanel.
//-----------------------------------------------------------------------
public PhonePanel()
{
// Set the layout manager, size and background color of the Phone Panel.
setLayout(new BorderLayout());
setPreferredSize (new Dimension(400, 200));
setBackground (Color.yellow);
// Output label created.
labelOutput = new JLabel(" ");
// Clear button created, assigned a button title and assigned an action listener.
buttonClear = new JButton();
buttonClear.setText("Clear");
buttonClear.addActionListener(new ClearButtonListener());
// Add the JLabel, JButton and KeypadPanel to the PhonePanel.
add(labelOutput, BorderLayout.NORTH);
add(buttonClear, BorderLayout.EAST);
add(new KeypadPanel(), BorderLayout.CENTER);
}
//-----------------------------------------------------------------------
// Adds the specified symbol to the output label.
//-----------------------------------------------------------------------
public static void addToOutputLabel(String input)
{
// Create a String object to hold the current value of the output label.
String label = labelOutput.getText();
// Append the inputed String onto the String.
label += input;
// Update the output label with the appended String.
labelOutput.setText(label);
}
//-----------------------------------------------------------------------
// Listens for the clear button to be pressed. When pressed, the output
// label is reassigned as blank.
//-----------------------------------------------------------------------
private class ClearButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
labelOutput.setText(" ");
}
}
}
// ******************************************************************************************
// KeypadPanel.java
// David Read
// This class creates a JPanel that contains several buttons which when pressed, adds their
// corresponding numeric symbol to the output label in the PhonePanel.
// ******************************************************************************************
package lab5;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class KeypadPanel extends JPanel
{
private JButton button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonStar, button0, buttonNumber;
//-----------------------------------------------------------------------
// Creates a JPanel that arranges several JButtons in a GridLayout. Each
// of the buttons are assigned button titles, action listeners and
// action commands.
//-----------------------------------------------------------------------
public KeypadPanel()
{
// Set layout to a GridLayout with 4 rows and 3 columns.
setLayout(new GridLayout(4,3));
// Create new JButtons.
button1 = new JButton();
button2 = new JButton();
button3 = new JButton();
button4 = new JButton();
button5 = new JButton();
button6 = new JButton();
button7 = new JButton();
button8 = new JButton();
button9 = new JButton();
buttonStar = new JButton();
button0 = new JButton();
buttonNumber = new JButton();
// Assign button titles to the JButtons.
button1.setText("1");
button2.setText("2");
button3.setText("3");
button4.setText("4");
button5.setText("5");
button6.setText("6");
button7.setText("7");
button8.setText("8");
button9.setText("9");
buttonStar.setText("*");
button0.setText("0");
buttonNumber.setText("#");
// Create a new KeypadButtonListener.
KeypadButtonListener listener = new KeypadButtonListener();
// Assign the listener as an action listener for all of the JButton objects.
button1.addActionListener(listener);
button2.addActionListener(listener);
button3.addActionListener(listener);
button4.addActionListener(listener);
button5.addActionListener(listener);
button6.addActionListener(listener);
button7.addActionListener(listener);
button8.addActionListener(listener);
button9.addActionListener(listener);
buttonStar.addActionListener(listener);
button0.addActionListener(listener);
buttonNumber.addActionListener(listener);
// Set the action commands for all of the JButtons.
button1.setActionCommand("1");
button2.setActionCommand("2");
button3.setActionCommand("3");
button4.setActionCommand("4");
button5.setActionCommand("5");
button6.setActionCommand("6");
button7.setActionCommand("7");
button8.setActionCommand("8");
button9.setActionCommand("9");
buttonStar.setActionCommand("*");
button0.setActionCommand("0");
buttonNumber.setActionCommand("#");
// Add the JButtons to the KeypadPanel.
add(button1);
add(button2);
add(button3);
add(button4);
add(button5);
add(button6);
add(button7);
add(button8);
add(button9);
add(buttonStar);
add(button0);
add(buttonNumber);
}
//-----------------------------------------------------------------------
// Listens for all of the buttons to be pressed. When a particular button
// is pressed, the addToOutputLabel method of the PhonePanel is called
// with the input being the action command of the button pressed.
//-----------------------------------------------------------------------
private class KeypadButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Add the action command string to the output label.
PhonePanel.addToOutputLabel(e.getActionCommand());
}
}
}
In this case it is better to use two separate action listeners as functionality for clear button and for number buttons is different.
It is considered as best practice to use single responsibility principle (https://en.wikipedia.org/wiki/Single_responsibility_principle) when developing your classes. This will make your code more maintainable and easier to read and modify.
It is better to use multiple ActionListeners here, however, if you still desire to use one ActionListener instead you may make a separate class to handle all actions similar to this.
public class KeyListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//Get the name of the ActionEvent
String cmd = e.getActionCommand();
//Here the Actionevent is only checked to see if it is a "Clear" or not
//If you need to impliment more then a switch statment may be appropriate
if(cmd.equals("Clear")) {
//Clear Label with additional setter method
PhonePanel.clearLabel();
}
else {
PhonePanel.addToOutputLabel(e.getActionCommand());
}
}

Applet and Swing not showing components in eclipse

I've run the following code in eclipse as an application and it works perfectly, however when I try to run it as an applet I get the window that says "Button to text" but none of the buttons appear. Also, an empty "applet viewer" windows pops up. Here is the code.
/**This program completes the requirements described
* in Option 3 which is to create a frame that contains 3 buttons.
* These buttons then will update the text shown on the frame.
* The program uses AWT and Swing to accomplish this task.
* For more information on the particular methods of this program, look below.
* Press a button to change the text on the bottom to the text displayed on the button
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingOption3 extends Applet {
private JFrame mainFrame;
private JLabel header;
private JLabel status;
private JPanel control;
//initialize the variables by creating them
public SwingOption3(){
prepareGUI();
//this constructor runs the prepareGUI method
}
public static void main(String[] args){
SwingOption3 swingOption3 = new SwingOption3();
swingOption3.showEvent();
//creates an object from the main class and runs the showEvent method
}
/** The following method performs these actions
* 1. Adds a title to the frame ("Button to Text")
* 2. Sets the size to 400 by 400
* 3. Uses the GridLayout to proportion the frame
* 4. Initializes the header and status variables
* 5. Adds a listener to the main frame
* 6. Adds the header, status, and control to the main frame
* 7. Sets the main frame to visible
* 8. Sets the control layout to flow
*/
private void prepareGUI(){
mainFrame = new JFrame("Button to Text");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
header = new JLabel("",JLabel.CENTER );
status = new JLabel("", JLabel.CENTER);
status.setSize(350, 100);
mainFrame.addWindowListener(new WindowAdapter() {
//this method allows the program window to be closed
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
control = new JPanel();
control.setLayout(new FlowLayout());
mainFrame.add(header);
mainFrame.add(control);
mainFrame.add(status);
mainFrame.setVisible(true);
}
/**The following method completes these tasks:
* 1. Sets the text of the header to inform the user what they should do
* 2. Adds the buttons to the JPanel "control"
* 3. Creates the listener methods and describes the ActionEvent
* that will be sent for each button press
**/
private void showEvent(){
header.setText("Press a button to change the text at the bottom");
//informs the user to press a button in order to change the text
JButton appleButton = new JButton("Apple");
JButton pearButton = new JButton("Pear");
JButton bananaButton = new JButton("Banana");
//creates the buttons and titles them
appleButton.setActionCommand("Apple");
pearButton.setActionCommand("Pear");
bananaButton.setActionCommand("Banana");
//sets the command that will be received and interpreted by the program
appleButton.addActionListener(new ButtonClickListener());
pearButton.addActionListener(new ButtonClickListener());
bananaButton.addActionListener(new ButtonClickListener());
//creates listeners for the button clicks
control.add(appleButton);
control.add(pearButton);
control.add(bananaButton);
//adds the buttons to the JPanel "control"
mainFrame.setVisible(true);
//makes the frame visible
}
private class ButtonClickListener implements ActionListener {
/**
* This method performs the following actions
* 1.Receives the command/ActionEvent from the previous method
* 2. Displays the appropriate text based on the ActionEvent
*/
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Apple")) {
status.setText("Display: Apple");
} //sets the display to "Display: Apple"
else if( command.equals("Pear")) {
status.setText("Display: Pear");
} //sets the display to "Display: Pear"
else {
status.setText("Display: Banana");
} //sets the display to "Display: Banana"
}
}
}
`
I'm not quite sure where I'm going wrong so I posted the whole thing. I appreciate your help.
You don't create new JFrames in applets, you use the applet itself as the container for your controls. And your contructor doesn't call showEvent()--the other controls never got instantiated.

Java submit button action

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

JTextArea editable or not editable depending on how it's called

Total re-edit with compilable example that clarifies my issue.
Overall program: Class MainFrame displays a JTable with results from a SQL query. MainFrame also has JButtons for refreshing, adding, updating, and querying the table. Clicking the Update button makes visible a text area and submit button. Users can enter an id number into the text area. When they click submit a new frame, UpdateFrame, opens with all the data from the record the corresponds to the id number.
Stripped-down versions of MainFrame and UpdateFrame are below.
UpdateFrame2.java
package kft1task4;
import javax.swing.*;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.JScrollPane;
public class UpdateFrame2 extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JTextArea jta = new JTextArea("This is a text area");
UpdateFrame2() {
setVisible(true);
setBounds(1000,400,1000,500);
pane.setLayout(null);
add(pane);
jta.setBounds(110,100,100,15);
pane.add(jta);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
} //End actionListener
} //End class
Very simple. One frame with one panel with one JTextArea. The JTextArea should be editable; I should be able to type in it.
MainFrame2.java
package kft1task4;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.*;
public class MainFrame2 extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JButton closeButt = new JButton("Push me to close the program");
JButton updateButt = new JButton("Push me to update a record");
JButton submitUpdButt = new JButton("Submit");
JLabel updateLabel = new JLabel("Select student id to update");
JTextArea updateTA = new JTextArea();
MainFrame2(){
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(1000,200,1500,1000);
pane.setLayout(null);
add(pane);
updateButt.setBounds(620,550,200,100);
updateButt.addActionListener(this);
pane.add(updateButt);
closeButt.setBounds(1290,550,200,100);
closeButt.addActionListener(this);
pane.add(closeButt);
submitUpdButt.setBounds(820,735,200,25);
submitUpdButt.addActionListener(this);
submitUpdButt.setVisible(false);
pane.add(submitUpdButt);
updateLabel.setBounds(620,700,200,15);
updateLabel.setVisible(false);
pane.add(updateLabel);
updateTA.setBounds(820,700,200,15);
updateTA.setVisible(false);
pane.add(updateTA);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == closeButt){
System.exit(0);
}
if(source == updateButt){
updateLabel.setVisible(true);
updateTA.setVisible(true);
submitUpdButt.setVisible(true);
}
if(source == submitUpdButt){
//submitUpdButt.setVisible(false);
new UpdateFrame2();
updateTA.setText(null);
updateTA.setVisible(false);
updateLabel.setVisible(false);
submitUpdButt.setVisible(false);
}
}
}
Note the three fields: updateLabel, updateTA, and submitUpdButt (and please forgive the poor naming). When new MainFrame2() is first instantiated, those three fields are .setVisible(False). Clicking updateButt makes them visible.
Click submitUpdButt performs five actions: First, it instantiates a new UpdateFrame2(). Second, it clears the text from UpdateTA. Finally, it makes the three fields invisible. Those 5 actions complete with no problem.
Now here's the oddity: Notice that I've listed "submitUpdButt.setVisible(false)" twice. Once before "new UpdateFrame2()" and once after. I comment out one and leave other in place. If "submitUpdButt.setVisible(false)" appears before "new UpdateFrame2()," the UpdateFrame appears, and its text area is editable.
If "submitUpdButt.setVisible(false)" appears after "new UpdateFrame2()," as it's written above, the UpdateFrame appears. But its text area is not editable.
To clarify: Every other element of the program behaves exactly the same. The 3 fields appear and disappear as expected. The window open and close correctly. The text "This is a text area" appears where it should. No errors are produced. But the text area in UpdateFrame2 is editable or not based on where I put "submitUpdButt.setVisible(false)".
I hope this description is more clear than my last one.

About java GUI and clear JFrame to show new content?

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

Categories