JLabel not showing text in GUI - java

so my code ask the user for input. then converts the temp. should be simple but my code is not working. It does not output my lable 3 it just does nothing. that is the only problem i am having with my code, i just dont know how to fix it
import javax.swing.*;
public class FahrenheitPanel extends JPanel
{
private JLabel lable1;
private JLabel lable2;
private JLabel lable3;
private JTextField fahrenheit;
public FahrenheitPanel()
{
lable1 = new JLabel ("Enter Fahrenheit temperature:");
lable2 = new JLabel ("Temperature in Celsius: ");
fahrenheit = new JTextField (5);
fahrenheit.addActionListener (new TempListener());
add (lable1);
add (fahrenheit);
add (lable2);
setPreferredSize (new Dimension(300, 75));
}
private class TempListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
int fahrenheitTemp, celsiusTemp;
String text = fahrenheit.getText();
fahrenheitTemp = Integer.parseInt (text);
celsiusTemp = (fahrenheitTemp-32) * 5/9;
lable3.setText(Integer.toString (celsiusTemp));
add ( lable3 );
}
}
public static void main (String[] args)
{
JFrame frame = new JFrame ("Fahrenheit to Celsius Converter");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
FahrenheitPanel panel = new FahrenheitPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

Don't add the labl3 JLabel to your GUI in the actionPerformed(...) method as doing this means you will be trying to add the JLabel as many times as the listener method is called, and will need to call revalidate and repaint unnecessarily. Instead add this JLabel to your GUI from the very beginning in the class's constructor.

The third label should be added to the frame from the start, with some default text.
If you add the label dynamically, then the container must be validated (by calling validate() on the panel).
Also, you should not set the preferred size of a panel. The layout manager computes the preferred size based on the components it contains.

First of all, i converted the Integer value to Double becuase it may have double numbers,
Second your are not adding your label in your class, this is the problem... run your program, if there is any problem , feel free to ask me
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FahrenheitPanel extends JPanel
{
private JLabel lable1;
private JLabel lable2;
private JLabel lable3;
private JTextField fahrenheit;
public FahrenheitPanel()
{
lable1 = new JLabel ("Enter Fahrenheit temperature:");
lable2 = new JLabel ("Temperature in Celsius: ");
lable3 = new JLabel("");
fahrenheit = new JTextField (5);
fahrenheit.addActionListener ((ActionListener) new TempListener());
add (lable1);
add (fahrenheit);
add (lable2);
add(lable3);
setPreferredSize (new Dimension(250, 75));
}
private class TempListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
double fahrenheitTemp, celsiusTemp;
String text = fahrenheit.getText();
fahrenheitTemp = Double.parseDouble (text);
celsiusTemp = ((fahrenheitTemp-32) * 5/9);
lable3.setText(Double.toString (celsiusTemp));
}
}
public static void main (String[] args)
{
JFrame frame = new JFrame ("Fahrenheit to Celsius Converter");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
FahrenheitPanel panel = new FahrenheitPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

Related

GUI Programming - Customizing frame

I'm just starting to use GUI programming. I'm trying to customize the frame but nothing is appearing so far when I add it to gameView, like the buttons or cat gif, so all I get is the frame window after I run it. Here's my code so far:
package experiment10;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class mainFrame extends JFrame
{
public static int MAX = 500; // maximum number to guess
private JButton submitBtn; // Submit button
private JButton clearBtn; // Clear Input button
private JTextField inputNumber; //input guessed number
private int magicNumber; //randomly generated number
public static void main(String[] arg) {
//Show frame
JFrame frame = new JFrame();
frame.setVisible(true);
}
public mainFrame() {
setSize(400, 400);
setResizable (false);
setTitle("Let's Play Hi Lo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
magicNumber = (int)(Math.random()*MAX);
Container gameView = getContentPane();
gameView.setLayout(new FlowLayout());
//Customizations
submitBtn = new JButton("Submit"); //create submit button
clearBtn = new JButton("Clear"); //create clear button
gameView.add(submitBtn); //adds submit button
gameView.add(clearBtn); //adds clear button
JLabel imageLabel = new JLabel(new ImageIcon("cat.gif")); //creates image
gameView.add(imageLabel); //adds image
JLabel textLabel = new JLabel("Please enter your guess"); //creates JLabel
gameView.add(textLabel); //adds JLabel
JTextField input = new JTextField(); //creates JTextField
gameView.add(input); //adds JTextField
}
}
Any help/tips are very much appreciated. Thank you.
You will need to call your mainFrame() from your main method:
mainFrame frame = new mainFrame();
You can also remove the following code from the main:
JFrame frame = new JFrame();
frame.setVisible(true);
You will then need to add setVisible(true); to your mainFrame() constructor.

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.

How do I remove the empty space in a JFrame?

I'm relatively new to Java GUI programming, and although the concepts are coming along well in my head, there's this small issue I'm having with removing the empty space in a JFrame.
If you run the code I have below, you'll notice that there's a considerable gap between the JTextFields and the JButton. I'd like the remove this gap so that the button is touching the very bottom JTextField.
Also, another very minor question. How do I increase the height of the JTextFields so that they have three rows instead of just one?
Anyway here's the code.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class HW4GUI extends JFrame
{
private JButton jbtAction;
private JTextField jtfFName;
private JTextField jtfLName;
private JTextField jtfLibNo;
private static int nextLibNo;
private JPanel textPanel;
public HW4GUI()
{
super("HW4GUI");
makeFrame();
showFrame();
}
public void makeFrame()
{
setLayout(new BorderLayout());
setResizable(false);
textPanel = new JPanel();
textPanel.setLayout(new GridLayout(3,2));
jbtAction = new JButton("Add Borrower");
JLabel FirstNameLabel = new JLabel("FirstName:");
jtfFName = new JTextField(3);
JLabel LastNameLabel = new JLabel("LastName:");
jtfLName = new JTextField(3);
JLabel LibNoLabel = new JLabel("Library Number:");
jtfLibNo = new JTextField(3);
FirstNameLabel.setHorizontalAlignment(JTextField.RIGHT);
LastNameLabel.setHorizontalAlignment(JTextField.RIGHT);
LibNoLabel.setHorizontalAlignment(JTextField.RIGHT);
jtfLibNo.setEditable(false);
textPanel.add(FirstNameLabel);
textPanel.add(jtfFName);
textPanel.add(LastNameLabel);
textPanel.add(jtfLName);
textPanel.add(LibNoLabel);
textPanel.add(jtfLibNo);
add(textPanel, BorderLayout.NORTH);
add(jbtAction, BorderLayout.SOUTH);
}
public void showFrame()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
}
Both of these are very easy fixes. For the first question, just set the second to "CENTER" instead of "SOUTH", and for the second question you can make it a JTextarea, which is multiple lines, or a JScrollPane which can scroll so it has a very large size.
P.S. you should always include a main method to run from like this one below.
public static void main(String[] args){
new HW4GUI();
}

Resize JButton within mu Jframe to put it on the bottom of the page horizantally

I need to write a code that generates library number and resize the JButton to put it to the bottom of the frame.
I need to write a code that generates library number from 1001 and each subsequent number should be one greater. Once the library number has been generated and shown in the text field, the button text should change to ‘Confirm’.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class HW4GUI extends JFrame implements ActionListener
{
private JButton jbtAction;
private JTextField jtfFName;
private JTextField jtfLName;
private JTextField jtfLibNo;
private int nextLibNo;
private JPanel textPanel;
public HW4GUI()
{
setTitle("HW4 GUI");
makeFrame();
showFrame();
}
public void actionPerformed(ActionEvent e)
{
I need to write a code that generates library number from 1001 and each subsequent number should be one greater. Once the library number has been generated and shown in the text field, the button text should change to ‘Confirm’.
}
public void makeFrame() Make frame method
{
setLayout( new GridLayout(4,0) );
jtfFName = new JTextField( 15 ) ;
JLabel aLabel = new JLabel("First Name: ");
jtfFName.setActionCommand("First Name");
jtfFName.setHorizontalAlignment(aLabel.RIGHT);
jtfLName = new JTextField( 15 ) ;
JLabel aLabel1 = new JLabel("Last Name: ");
jtfLName.setActionCommand("Last Name");
jtfLName.setHorizontalAlignment(aLabel1.RIGHT);
jtfLibNo = new JTextField( 10 ) ;
JLabel aLabel2 = new JLabel("Library Number: ");
jtfLibNo.setActionCommand("Library Number");
jtfLibNo.setEditable(false);
jtfLibNo.setHorizontalAlignment(aLabel2.RIGHT);
add(aLabel);
add(jtfFName);
add(aLabel1);
add(jtfLName);
add(aLabel2);
add(jtfLibNo);
JPanel textPanel = new JPanel();
jbtAction = new JButton("Add Borrower");
jbtAction.setLayout(new BoxLayout(jbtAction, BoxLayout.PAGE_AXIS));
add(jbtAction); I need to resize this button
jtfFName.addActionListener( this );
jtfLName.addActionListener( this );
jtfLibNo.addActionListener( this );
jbtAction.addActionListener( this );
}
public void showFrame()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400,200);
setVisible(true);
}
}

How do I transfer the data in my JTextField to a JLabel?

So we're supposed to be making a reservation screen for our Airline. After the user inputs his/her information and clicks on Reserve my code needs to show her the information back in on a separate frame. I have the frame set up, I just need to transfer the information IN the JTextField to the frame on JLabel. I heard I need to make it into a variable so I can use it in multiple places. I'm new to Java so please don't use words I might not be familiar with. Thank you and here is my code. I have 3 classes.
First Class:
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TicketMan {
public static void main(String[] args) {
JFrame frame = new JFrame ("Airport");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
TicketManBot panel = new TicketManBot();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true); } }
Second Class:(The class the fields are on.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class TicketManBot extends JPanel {
private JLabel name;
private JLabel dest;
private JLabel depc;
private JLabel dept;
private JLabel seat;
private JButton b;
Random rand = new Random();
private JTextField namef, destf, depcf, deptf;
public TicketManBot()
{
name = new JLabel ("Enter passenger's name:");
dest = new JLabel ("Destination: ");
depc = new JLabel ("Departure city: ");
dept = new JLabel ("Departure time: ");
seat = new JLabel ("Seat Number: " + rand.nextInt(100));
b = new JButton ("Make Reservation");
b.addActionListener (new results());
// the fields I need to move
namef = new JTextField (10);
destf = new JTextField (10);
depcf = new JTextField (10);
deptf = new JTextField (10);
add (name);
add (namef);
add (dest);
add (destf);
add (depc);
add (depcf);
add (dept);
add (deptf);
add (seat);
add (b);
setPreferredSize (new Dimension(200, 300));
setBackground (Color.gray);
}
private class results implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
int resultLabel;
String text = namef.getText();
JFrame results = new JFrame("Thank you for flying with JJ Air");
results.setVisible(true);
results.setSize (200, 300);
// I need to move the fields up there in front of these VVVVVV
JLabel nr = new JLabel ("Name of the passenger:");
JLabel dr = new JLabel ("Destination:");
JLabel depr = new JLabel ("Departure city:");
JLabel dpr = new JLabel ("Departure time:");
JLabel sr = new JLabel ("Seat number:");
JLabel t = new JLabel ("Thank you for flying with us");
JLabel label = new JLabel ("");
JPanel panel = new JPanel ();
results.add(panel);
panel.add (nr);
panel.add (dr);
panel.add (depr);
panel.add (dpr);
panel.add (sr);
panel.add (t);
}
}
}
Third Class:
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class results extends JPanel {
}
jLabel.setText(jTextField.getText());
Where jLabel is your label and jTextField your text field.
For example:
JLabel nr = new JLabel ("Name of the passenger:"+Namef.getText());
You should read up on the Java coding style guidelines by the way, it will help make your code more readable to others.
Jlabel is the label you want to set text to. jtextField is the tetxfield you want to get info from
jLabel.setText(jTextField.getText());
Also what you could do, is maybe gather all info from all textFields into Array and then use it to display whatever from array in desired jLabel. Or even better use Array to display data in nice looking Table :)

Categories