Why is my text field not appearing? - java

I have to create a text field, a text area, and two buttons, but I am stuck on the text field because I cant get it to appear when I run my program. My JFrame keeps appearing empty.
public class SentanceBuilder extends JFrame {
private JTextField textField = new JTextField(50);
private JTextArea textArea = new JTextArea(200,200);
private JButton Submit = new JButton();
private JButton Cancel = new JButton();
public SentanceBuilder(){
textField.setVisible(true);
textField.setLocation(50, 50);
this.textField();
this.setSize(400, 300);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public void textField(){
String textContent = textField.getText();
}
}

You never add the textField variable to a container such as a JPanel that is held by the top-level window, such as a JFrame. In fact, in your code, you add nothing to your JFrame!
If this were my GUI, I'd
Create my JTextField
Create a main JPanel to hold my components.
Add it and other components to the main JPanel via the JPanel's add(...) method.
Add the main JPanel to the JFrame's contentPane via the JFrame's add(...) method.
Call pack() and then setVisible(true) on the JFrame, but only after adding all components to it, not before.
Read the Swing tutorials since this beats guessing every time. You can get links to the tutorials at the Swing Tag Info link.
e.g.,
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MyFoo extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textField = new JTextField(10);
private JButton button = new JButton("Foo Button");
public MyFoo() {
super("My JFrame");
// so Java will end when GUI is closed
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// code to be called when button is pushed
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO code that runs when button is pushed.
}
});
// panel to hold everything
JPanel mainPanel = new JPanel();
// add all to the panel
mainPanel.add(new JLabel("Text Field:"));
mainPanel.add(textField);
mainPanel.add(button);
// add the panel to the main GUI
add(mainPanel);
}
// start up code
private static void createAndShowGui() {
JFrame mainFrame = new MyFoo();
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
// call start up code in a Swing thread-safe way
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Related

Java Swing- Panel not appearing in frame

I am new to swing and am wondering why my login panel isn't appearing in the frame. I believe it should show on the left side of the frame, is this correct? What needs to be changed to make the panel appear. Thanks.
Here is the GUIFrame code
public class GUIFrame extends JFrame {
private static final long serialVersionUID = 1L;
public GUIFrame(){
Container container = getContentPane();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenDimension = toolkit.getScreenSize();
setSize(screenDimension.width/2, screenDimension.height/2);
setLocation(screenDimension.width/4,screenDimension.height/4);
setLayout(new GridLayout(1,2));
add(new Login(this));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
Here is the panels code:
public class Login extends JPanel {
private JPanel panel = new JPanel();
private JButton cancel = new JButton("Cancel");
private JButton submit = new JButton("Submit");
private JLabel username_label = new JLabel("Username :");
private JLabel password_label = new JLabel("Password :");
private JTextField username_text = new JTextField();
private JPasswordField password_text = new JPasswordField();
private GUIFrame frame;
public Login(GUIFrame frame){
this.frame = frame;
setLayout(new GridLayout(3,2,20,40));
addComponents();
}
public void addComponents(){
panel.add(username_label);
panel.add(username_text);
panel.add(password_label);
panel.add(password_text);
panel.add(cancel);
panel.add(submit);
}
}
Here is the main method which displays the frame:
public class Project {
public static void main(String[] args){
Project project = new Project();
}
public Project() {
//Login login = new Login();
GUIFrame frame = new GUIFrame();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});
}
}
panel.add(username_label);
panel.add(username_text);
panel.add(password_label);
panel.add(password_text);
panel.add(cancel);
panel.add(submit);
You create a separate JPanel and add the component to this panel, but you never add the panel to your Login panel.
Your Login panel already is a JPanel, so there is no need to create another JPanel.
The code should just be:
add(username_label);
add(username_text);
add(password_label);
add(password_text);
add(cancel);
add(submit);
There is also no reason to pass the JFrame as a parameter to your Login class.
Also, you are using the invokeLater() incorrectly. All Swing components should be created on the Event Dispatch Thread (EDT). So you should also include the new GuiFrame() inside the invokeLater().
Generally there is no need to have a separate JFrame class. The logic in your Project class should simply create an instance of the frame and add the Login panel to the frame. In other words don't extend JFrame.

textField.getText() not working when textField is in a different panel (compare to the button.addActionListener)

I'm new to Java Swing and encountered an issue when using JTextField.getText(). Basically .getText() is not picking up whatever string I put into the text field and returns an empty string.
I think the reason I got an empty string is that the JTextField is in a different panel than the button, but don't know how to get it working... Any help will be highly appreciated!
Here is my logic
(1) Create a JFrame, call it frame
(2) Create several JPanels and frame.add(JPanel)
(3) Fill in the panels with JButton and JTextField. Note that the text field is in a different panel than the button.
(4) Call button.addActionListener(...) and use JTextField.getText()
Here is my code:
package GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class aaaaa {
// Class attributes
// Overall class attributes
private JFrame frame = new JFrame("Simulation App");
// Class attributes for method setTextFieldPar
private JPanel panelThetaCh = new JPanel();
private JPanel panelSetButton = new JPanel();
private JTextField textFieldThetaCh = new JTextField();
private String StringThetaCh;
// Class attributes for method setButton
private JButton buttonSetPar;
// ========================================================================================================================
// Class methods
// Text field of all simulation parameters
public void setTextFieldPar(JPanel panel, JTextField textField, String latexString){
// Panel layout - FlowLayout
panel.setLayout(new FlowLayout());
panel.setMinimumSize(new Dimension(300, 100));
frame.add(panel);
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel labelText = new JLabel("text");
panel.add(labelText);
// Create text field
textField = new JTextField(13);
panel.add(textField);
}
// Button "Set Parameters"
public void setButton (JPanel panel){
panel.setLayout(new GridLayout(4, 0));
panel.setMaximumSize(new Dimension(200, 100));
frame.add(panel);
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonSetPar = new JButton("Set Parameters");
panel.add(buttonSetPar);
}
// Monitor input in text field
public void monitorTextField() {
buttonSetPar.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
// Extract numbers entered in text field for the parameters
StringThetaCh = textFieldThetaCh.getText();
if (StringThetaCh.equals("")) {
JFrame errorWindow = new JFrame("Error");
errorWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
errorWindow.setLocationRelativeTo(null);
JOptionPane.showMessageDialog(errorWindow, "At least one text field is empty, please enter numerical values");
}
}
});
}
// Constructor
public aaaaa(){
frame.setSize(350, 800);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
// Text field for parameters
setTextFieldPar(panelThetaCh, textFieldThetaCh, "\\theta_{CH}");
// Button for set parameter
setButton(panelSetButton);
// Monitoring input in text field
monitorTextField();
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
aaaaa window2 = new aaaaa();
window2.frame.setVisible(true);
}
});
}
}
You are already creating the text field in the class declaration:
private JTextField textFieldThetaCh = new JTextField();
then you pass it to the method setTextFieldPar and in there you are creating another text field that is added to the panel:
textField = new JTextField(13);
panel.add(textField);
So, the class variable textFieldThetaCh is not the one added to the panel and therefore is inaccessible to the user.
Simply remove the creation of the new text field in setTextFieldPar and it will work.
Here is a visual representation of what is happening:
in the class declaration:
inside the setTextFieldPar method (remember that the parameters are passed by value, so a copy of the object reference is made):
after textField = new JTextField(13);, the copy of the reference now points to a new object:
after panel.add(textField);, the new object is added to the panel, which is not what textFieldThetaCh is pointing to:
i just use textFieldThetaCh directly without send it as pram
you was taking the text from textFieldThetaCh when you are typing the text on textField
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class aaaaa {
// Class attributes
// Overall class attributes
private JFrame frame = new JFrame("Simulation App");
// Class attributes for method setTextFieldPar
private JPanel panelThetaCh = new JPanel();
private JPanel panelSetButton = new JPanel();
private JTextField textFieldThetaCh = new JTextField(13);
private String StringThetaCh;
// Class attributes for method setButton
private JButton buttonSetPar;
// Text field of all simulation parameters
public void setTextFieldPar(JPanel panel, JTextField textField, String
latexString){
// Panel layout - FlowLayout
panel.setLayout(new FlowLayout());
panel.setMinimumSize(new Dimension(300, 100));
frame.add(panel);
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel labelText = new JLabel("text");
panel.add(labelText);
// Create text field
// textField = new JTextField(13);
panel.add(textFieldThetaCh);
}
// Button "Set Parameters"
public void setButton (JPanel panel){
panel.setLayout(new GridLayout(4, 0));
panel.setMaximumSize(new Dimension(200, 100));
frame.add(panel);
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonSetPar = new JButton("Set Parameters");
panel.add(buttonSetPar);
}
// Monitor input in text field
public void monitorTextField() {
buttonSetPar.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
// Extract numbers entered in text field for the parameters
StringThetaCh = textFieldThetaCh.getText();
if (StringThetaCh.equals("")) {
JFrame errorWindow = new JFrame("Error");
errorWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
errorWindow.setLocationRelativeTo(null);
JOptionPane.showMessageDialog(errorWindow, "At least one text
field is empty, please enter numerical values");
}
else
JOptionPane.showMessageDialog(null,
StringThetaCh);
}
});
}
// Constructor
public aaaaa(){
frame.setSize(350, 800);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
// Text field for parameters
setTextFieldPar(panelThetaCh, textFieldThetaCh, "\\theta_{CH}");
// Button for set parameter
setButton(panelSetButton);
// Monitoring input in text field
monitorTextField();
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
aaaaa window2 = new aaaaa();
window2.frame.setVisible(true);
}
});
}
}
Your button actionPerformed is within monitorTextField() which is in the constructor. This gets fired up at the beginning but never called upon afterwards (referring to monitorTextField()).
Put the actionPerformed somewhere outside of a function so it can function anytime the button is pressed and it should work.

Java gui Jbutton

I have a program but I can't combine the textfield and the button in the same frame like in top textfield and below that the button:
Here is my source code:
import java.awt.*;
import javax.swing.*;
public class FirstGui extends JFrame
{
JTextField texts;
JButton button;
public FirstGui()
{
texts = new JTextField(15);
add(texts);
button = new JButton("Ok");
add(button);
}
public static void main(String args [])
{
FirstGui gui = new FirstGui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(200,125);
gui.setVisible(true);
}
}
Add a layout like FlowLayout:
public FirstGui()
{
setLayout(new FlowLayout());
texts = new JTextField(15);
add(texts);
button = new JButton("Ok");
add(button);
}
at the very beginning of your constructor, before anything else.
The default layout is BorderLayout for JFrame. When you add components to a BorderLayout, if you don't specify their BorderLayout position, like BorderLayout.SOUTH, the component will automatically be add to BorderLayout.CENTER. Bthe thing is though, each position can only have one component. So when you add texts it gets added to the CENTER. Then when you add button, it gets added to the CENTER but texts gets kicked out. So to fix, you can do
add(texts, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
See Laying out Components Within a Container to learn more about layout managers.
UPDATE
import java.awt.*;
import javax.swing.*;
public class FirstGui extends JFrame {
JTextField texts;
JButton button;
public FirstGui() {
texts = new JTextField(15);
add(texts, BorderLayout.CENTER);
button = new JButton("Ok");
add(button, BorderLayout.SOUTH);
}
public static void main(String args[]) {
FirstGui gui = new FirstGui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setVisible(true);
}
}

Trying to use GUI, having trouble adding buttons and labels

The assignment is simple, all we need to do is have the code create a window with a red panel with a single button and label. Here is the code thus far as well as the tester class.
I got the label to display on the window, but its in a weird place. I cant get the button to display at all as well getting the background to display as red.
This is where I'm having trouble with the most:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyCustomFrame extends JFrame
{
public MyCustomFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createComponents()
{
JPanel panel=new createPanel();
button=new JButton("Push Me");
label=new JLabel("This is a label");
add(button);
add(label);
}
private JButton button;
private JLabel label;
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 800;
public void createPanel()
{
JPanel panel=new JPanel();
panel.setBackground(Color.RED);
//button=new JButton("Push Me");
//label=new JLabel("This is a label");
}
public void createFrame()
{
JFrame frame=new JFrame();
add(frame);
frame.setVisible(true);
}
}
And this is the tester class:
import javax.swing.JFrame;
public class MyCustomFrameViewer
{
public static void main(String[] args)
{
MyCustomFrame frame = new MyCustomFrame();
frame.setTitle("My first frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You create the JPanel, panel, but add nothing to it, and then never add the panel to your JFrame. You should add your components to the JPanel, panel, and then add the panel object to your JFrame.
Note that a JPanel uses FlowLayout by default, and so it will more easily accept multiple other components without special add methods. The JFrame's contentPane uses BorderLayout which is slightly more complicated to use.
Add the panel to the frame instead of the label and button, and add the label and button to the panel...
private void createComponents()
{
JPanel panel=new createPanel();
add(panel);
button=new JButton("Push Me");
label=new JLabel("This is a label");
panel.add(button);
panel.add(label);
}
You may also want to take a look at Initial Threads and make sure you are creating your UI from within the context of the Event Dispatching Thread
Some side notes...
This scares me...
public void createFrame()
{
JFrame frame=new JFrame();
add(frame);
frame.setVisible(true);
}
You're trying to add a frame to a frame, which is an illegal operation in Swing, but thankfully, you're not actually calling it from what I can see.
Instead of using setSize(FRAME_WIDTH, FRAME_HEIGHT);, you may wish to use pack instead.
See also the tips in comments in this example:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
// Don't extend frame, just use an instance
//public class MyCustomFrame extends JFrame {
public class MyCustomFrame {
private JFrame frame;
private JButton button;
private JLabel label;
private JPanel panel;
// better to override the preferred size of the component of interest
final int GAME_WIDTH = 300;
final int GAME_HEIGHT = 100;
public MyCustomFrame() {
createComponents();
// better to override the preferred size of the component of interest
//setSize(GAME_WIDTH, GAME_HEIGHT);
}
private void createComponents() {
// compilation error! createPanel() does not return anything..
//JPanel panel = new createPanel();
createPanel();
// create the frame!
createFrame();
}
private void createPanel() {
// creates a local instance
//JPanel panel = new JPanel();
panel = new JPanel() {
/* override the preferred size of the component of interest */
#Override
public Dimension getPreferredSize() {
return new Dimension(GAME_WIDTH, GAME_HEIGHT);
}
};
panel.setBackground(Color.RED);
button = new JButton("Push Me");
label = new JLabel("This is a label");
panel.add(button);
panel.add(label);
}
private void createFrame() {
// create a local instance of a JFrame that goes out of scope at end
// of method..
//JFrame frame = new JFrame();
frame = new JFrame("My first frame");
// add the panel to the frame!
frame.add(panel);
// better to use DISPOSE_ON_CLOSE
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// a good way to position a GUI
frame.setLocationByPlatform(true);
// this was trying to add a JFrame to another JFrame
//add(frame);
frame.pack();
}
public final JFrame getFrame() {
return frame;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
MyCustomFrame myFrame = new MyCustomFrame();
JFrame frame = myFrame.getFrame();
frame.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}

Execute a JFrame program

how to execute this program?
// Resolve class BorderLayout
import java.awt.*;
// Resolve class JFrame and JButton
import javax.swing.*;
// Definition of class FrameWithBorderLayout
public class FrameWithBorderLayout extends JFrame {// Attribute
private JButton buttonEast; // The east button
private JButton buttonSouth; // The south button
private JButton buttonWest; // The west button
private JButton buttonNorth; // The north button
private JButton buttonCenter; // The center button
// Constructor
public FrameWithBorderLayout() {
// Call super class constructor with a title
super("Frame With Multiple Buttons");
// Create JButton objects
buttonEast = new JButton("East");
buttonSouth = new JButton("South");
buttonWest = new JButton("West");
buttonNorth = new JButton("North");
buttonCenter = new JButton("Center");
// Add the JButton objects
add(buttonEast, BorderLayout.EAST);
add(buttonSouth, BorderLayout.SOUTH);
add(buttonWest, BorderLayout.WEST);
add(buttonNorth, BorderLayout.NORTH);
add(buttonCenter, BorderLayout.CENTER);
// Set when the close button is clicked, the application exits
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Reorganize the embedded components
pack();
}
}
---------------------------------current source-------------------------------------
// Resolve class BorderLayout
import java.awt.*;
// Resolve class JFrame and JButton
import javax.swing.*;
// Definition of class FrameWithBorderLayout
public class test extends JFrame {
// Attribute
private JButton buttonEast; // The east button
private JButton buttonSouth; // The south button
private JButton buttonWest; // The west button
private JButton buttonNorth; // The north button
private JButton buttonCenter; // The center button
// Constructor
public test() {
// Call super class constructor with a title
super("Frame With Multiple Buttons");
// Create JButton objects
buttonEast = new JButton("East");
buttonSouth = new JButton("South");
buttonWest = new JButton("West");
buttonNorth = new JButton("North");
buttonCenter = new JButton("Center");
// Add the JButton objects
add(buttonEast, BorderLayout.EAST);
add(buttonSouth, BorderLayout.SOUTH);
add(buttonWest, BorderLayout.WEST);
add(buttonNorth, BorderLayout.NORTH);
add(buttonCenter, BorderLayout.CENTER);
// Set when the close button is clicked, the application exits
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Reorganize the embedded components
pack();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FrameWithBorderLayout frame = new FrameWithBorderLayout();
frame.setVisible(true);
}
});
}
}
Every Java program starts from a main method:
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FrameWithBorderLayout frame = new FrameWithBorderLayout();
frame.setVisible(true);
}
});
}
Add this to your frame class.
FrameWithBorderLayout frameTest = new FrameWithBorderLayout();
frameTest.setVisible(true);

Categories