Java - Jframe not displaying Buttons Labels or textfields - java

im new to java but when I try to create a new frame all I get is a new window open with a white background on and none of the buttons or text boxes or labels get added. I don't know what im doing wrong?
private static void MainGui(){
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle(name+ "'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
MainInterfaces Class
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}

Your code doesn't compile because you have a lot of errors (you have no main method, private static void MainGui(){ makes no sense etc.). Try this code instead which compiles and opens the GUI fine for me, showing everything as you want to (the buttons, the labels, etc.):
1) Class MainGui.java
class MainGui{
public static void main(String[] args) {
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle("'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(MainGui.EXIT_ON_CLOSE);
}
}
2) Class MainInterfaces.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}

I fixed it with one line of code. Just switch the "setVisible(true)" method to being inside the MainInterface class. However, make sure you put it as the last line of code inside the constructor, or it won't work. Basically, what was happening is that while the frame itself was being set to be true, the components were being added afterwards and were consequently not being shown. Putting "setVisible(true)" last makes sure all the components are added when you display the frame.
As a side note, you can add all methods you typed in the MainGUI class inside of MainInterface.
Here's MainGUI:
public class MainGUI
{
public static void main(String[] args)
{
new MainInterfaces();
}
}
Here's what MainInterfaces looks likes:
public class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces()
{
setTitle("(Name)'s Inbox");
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl); add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
}

Related

When using JPanels in java how can you display user input data in one class to another

I've been having some difficulty with this. Basically I want a user to enter a name in one Java class and have that data displayed in another. I try using gets but I keep getting 'null'. Also how would you do this if I wanted to get an int from my class (exampl) to display in my second class. Would it basically be the same?
Here's an example to show what I mean
1st class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exampl extends JFrame implements ActionListener {
JLabel intro = new JLabel("Welcome What is your name?");
JTextField answer = new JTextField(10);
JButton button = new JButton("Enter");
final int WIDTH = 330;
final int HEIGHT = 330;
JLabel greeting = new JLabel("");
JButton next =new JButton("Next");
String name = answer.getText();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Exampl() {
super("Welcome");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
add(intro);
add(answer);
add(button);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == button) {
String greet = "Hello there" + name;
greeting.setText(greet);
add(next);
next.addActionListener(this);
if(source==next)
dispose();
new Hello();
}
}
public static void main(String[] args) {
Exampl frame= new Exampl();
frame.setVisible(true);
}
}
2nd class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Hello extends JFrame implements ActionListener {
String name;
JLabel hi = new JLabel("Nice to see you "+name);
JButton button = new JButton("Enter");
final int WIDTH = 330;
final int HEIGHT = 330;
JLabel greeting = new JLabel("");
JButton next =new JButton("Next");
public Hello() {
super("Welcome");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
add(hi);
add(button);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == button) {
String greet = "example " + name;
greeting.setText(greet);
add(next);
}
}
public static void main(String[] args) {
Exampl frame= new Exampl();
frame.setVisible(true);
}
}
My recommendations for you:
Don't extend JFrame, instead extend JPanel. See: Extends Frame vs creating it inside the program and Why shouldn't you extend JFrame and other components
Don't use multiple JFrames. See The use of multiple JFrames, good / bad practice? (BAD) instead you might want to try using Card Layout or JDialogs
What do you mean by extend? do you mean "public class Hello extends Exampl"? I'm new to java so I don't know much.
From that comment on another answer, you might want to learn the basics first in console applications before going into a GUI application which adds more complexity to your programs and thus your learning.
I'm planning on doing a project where I add the inputted name and a random int into a file so I can store it. Or would it make more sense to add that code into the same class?
From that comment, you can create a public method which returns the value in a JTextField in the format you need, then call that method from the other class, for example:
public String getUserName() {
return userNameField.getText();
}
public int getDigit() {
try {
return Integer.parseInt(digitField.getText());
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
return -1; //In case it's not a number, or return 0, or whatever you need
}
//------In another class------//
int digit = object1.getDigit(); //Where object1 is an instance of the other class where those methods are defined
Make a getter in first class and extends second one class then use super.getter();

How to set the size of the JTextArea and JTextField to my liking in the following code?

Ignore the functionality. I am only interested about the GUI.
I have used a JPanel component called mainPanel and added a JTextArea called receivingWindow and a JTextField called sendWindow to it.
The receiveWindow and sendWindow take up the entire frame space despite me specifying their sizes in the following lines:
receivingWindow = new JTextArea(50,50);
sendWindow = new JTextField(30);
How do I set their size to my liking?
Here is the full code:
package hf;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ChatClient
{
private JFrame frame;
private JTextArea receivingWindow;
private JTextField sendWindow;
private JButton sendButton;
private JPanel mainPanel;
private Socket connectionSocket;
private final static int serverPortNumber = 5000;
private PrintWriter printWriter;
private BufferedReader incomingReader;
private InputStreamReader incomingInputStreamReader;
private JScrollPane scrollPane;
public static void main(String[] args)
{
ChatClient chatClient = new ChatClient();
chatClient.startUp();
}
public void startUp()
{
setUpGui();
setUpNetworking();
handleEvents();
setUpListenerThread();
displayFrame();
}
private void setUpGui()
{
frame = new JFrame("Chat Client");
receivingWindow = new JTextArea(50,50);
sendWindow = new JTextField(30);
sendButton = new JButton("Send");
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.PAGE_AXIS));
scrollPane = new JScrollPane(receivingWindow);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
mainPanel.add(scrollPane);
mainPanel.add(sendWindow);
mainPanel.add(sendButton);
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
}
private void handleEvents()
{
sendButton.addActionListener(new MySendButtonListener());
}
private void setUpNetworking()
{
try
{
connectionSocket = new Socket("127.0.0.1",serverPortNumber);
printWriter = new PrintWriter(connectionSocket.getOutputStream());
incomingInputStreamReader = new InputStreamReader(connectionSocket.getInputStream());
incomingReader = new BufferedReader(incomingInputStreamReader);
}
catch(Exception ex)
{
System.out.println("Error in connecting to the server.");
}
}
private class MySendButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String message = sendWindow.getText();
printWriter.println(message);
printWriter.flush();
sendWindow.setText("");
sendWindow.requestFocus();
}
}
private void setUpListenerThread()
{
try
{
Runnable incomingThread = new IncomingMessageRunnable();
Thread thread = new Thread(incomingThread);
thread.start();
}
catch(Exception ex)
{
System.out.println("Error in setting up thread for listening to incoming menssages.");
}
}
private class IncomingMessageRunnable implements Runnable
{
public void run()
{
String incomingMessage = null;
try
{
while((incomingMessage = incomingReader.readLine())!=null)
{
receivingWindow.append(incomingMessage+"\n");
}
}
catch(Exception e)
{
System.out.println("Error in receiving incoming messages");
}
}
}
private void displayFrame()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
What you specified in your code aren't really the sizes on the panel but rather how many columns and rows or columns your JTextField and your JTextArea have respectively. From the Oracle Docs:
JTextArea(int rows, int columns)
Constructs a new empty TextArea with the specified number of rows and columns.
JTextField(int columns)
Constructs a new empty TextField with the specified number of columns.
Your components are taking up the whole screen space because your BoxLayout fits every component added to the panel into the panel and aligns them vertically while respecting their maximum sizes and since you haven't set any they appear to be filling up the whole space.
I would refrain from trying to archive pixel-perfect GUI anyways and rather find a better LayoutManager to archive what you have in mind. I would suggest you look at A Visual Guide to Layout Managers and see which layout best suits your needs.

how to open a second jframe from a current one?

my current program takes in text from some JTextFields and adds it to a file to keep track of medications. What i want to do, is add another button to the bottom of the program that will open a second jframe to display the medications that are already documented, but all attempts have been brutally unsuccessful. Below is the code that i am currently working with.
Much Thanks.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
#SuppressWarnings({ "serial" })
public class MedGUITest extends JFrame {
private JLabel medName;
private JLabel medTime;
private JLabel medDose;
private JLabel finished;
private JTextField textFieldMed;
private JTextField textFieldTime;
private JTextField textFieldDose;
private JButton submitButton;
private JButton meds;
public MedGUITest(){
setLayout(new FlowLayout());
medName = new JLabel("Type Medication Here:");
add(medName);
textFieldMed = new JTextField("",15);
add(textFieldMed);
medDose = new JLabel("Type Medication Dose:");
add(medDose);
textFieldDose = new JTextField("",15);
add(textFieldDose);
medTime = new JLabel("Type Medication Time:");
add(medTime);
textFieldTime = new JTextField("",15);
add(textFieldTime);
submitButton = new JButton("Click Here to Add");
event e = new event();
submitButton.addActionListener(e);
add(submitButton);
meds = new JButton("Click Here to see meds");
event2 r = new event2();
meds.addActionListener(r);
add(meds);
finished = new JLabel("");
add(finished);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e){
String medName = textFieldMed.getText();
String medDose = textFieldDose.getText();
String medTime = textFieldTime.getText();
File med = new File("med.txt");
try(PrintWriter out= new PrintWriter(new FileWriter(med,true))) {
out.println("Medication: " + medName + " " +"Dosage: "+ medDose + " Mg"+ " " +"Time of day: "+ medTime);
finished.setText("Your Med has been added");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class event2 implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
public static void main(String args[]) throws IOException{
int winWidth = 300;
int winLength = 300;
MedGUITest gui = new MedGUITest();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(winWidth, winLength);
gui.setVisible(true);
gui.setTitle("Standard GUI");
}
}
You would probably want to use a JDialog instead of another JFrame. You just set it up the same way you set up any other JFrame or JDialog. You create the frame/dialog, add components and then call pack() then setvisible(true). You just want to make sure that you don't set JFrame.setDefaultCloseOperation() to close when the close your second JFrame.
I find it easier to set up my classes to sub-class JPanel instead of JFrame so then it is easier to reuse it in other places.

Split String on JButton press

I am trying to make the input from a JTextField get split into an array of words when I press a button. When I press the button the program gives me a huge list of errors. The line of code that splits the sentence and where I call the class in the action listener is where eclipse says the error is coming from. I do not know why I am getting this error and I don't know how to fix. I have tried a lot of different things but they don't work. If you could explain why this isn't working or how to fix that would be great. Here is my code. Thank you for your help.
Main Class:
public class Control {
public static void main(String[] args) {
OpenWindow ow = new OpenWindow();
ow.window();
}
}
Second Class:
public class OpenWindow extends JFrame{
//Making variables
String input;
String firstWord2;
JButton jb = new JButton("Button");
JLabel jl = new JLabel();
JTextField jtf = new JTextField(40);
JPanel jp1 = new JPanel(new GridLayout(3,1));
SentenceSplitter ss = new SentenceSplitter();
public void window() {
//Make window pop up
setTitle("Project");
setSize(600, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Action Listener
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input = jtf.getText();
//Error from line below
ss.split();
firstWord2 = ss.getFirstWord();
jl.setText(firstWord2);
}
});
//Add JFrames
jp1.add(jtf);
jp1.add(jb);
jp1.add(jl);
add(jp1);
}
//Make input accesible from other classes
String getInput() {
return input;
}
}
Third Class:
public class SentenceSplitter {
String firstWord;
public void split() {
OpenWindow ow2 = new OpenWindow();
//Get input
String sentence = ow2.getInput();
//Error from line below
String[] splitSentence = sentence.split(" ");
firstWord = splitSentence[0];
}
String getFirstWord() {
return firstWord;
}
}
In your code you
creating OpenWindow
In The OpenWindow object you are creating a SentenceSplitter and listening for a click
On the click you are calling the split method on the previously created SentenceSplitter
In split you are creating a new OpenWindow
What you maybe should do is pass the String as an input parameter to the split method

Java GUI Variables Problems

I seem to have set up something wrong in the action listener for the Create Button handler. When I tried to get the value of the text field nameTF I get a null pointer error. I tried to imitate your code for the calculator, and the Exit Button Handler works well. I know that pressing the Create button invokes the handler but the statement
inName = nameTF.getText();
gives the error message.
The complete text of the listener is
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
and the whole program is below. Any help/explanation/suggestion would be very welcome.
import javax.swing.*; // import statement for the GUI components
import java.awt.*; //import statement for container class
import java.awt.event.*;
public class DogGUI //creation of DogGUI clas
{
private JLabel nameL, typeL, ageL, outtputL;
private JTextField nameTF, typeTF, ageTF;
private JButton createB, exitB;
CreateButtonHandler cbHandler;
ExitButtonHandler ebHandler;
public void driver () //creates everything
{
//create the window
JFrame DogInfo = new JFrame ("Dog GUI");
DogInfo.setSize(400,300); //set the pixels for GUI
DogInfo.setVisible(true); // set visibility to true
DogInfo.setDefaultCloseOperation(DogInfo.EXIT_ON_CLOSE); // when closed JFrame will disappear
//layout
Container DogFields = DogInfo.getContentPane();
DogFields.setLayout(new GridLayout(5,2));
// setting labels for GUI
nameL = new JLabel ("Enter name of Dog: ",
SwingConstants.RIGHT);
typeL = new JLabel ("Enter the type of the Dog: ",
SwingConstants.RIGHT);
ageL = new JLabel ("Enter the age of the Dog: ",
SwingConstants.RIGHT);
outtputL = new JLabel ("Dog Information: ",
SwingConstants.RIGHT);
//Buttons
JButton createB, exitB; //creating button for creation of Dog and button to exit
createB = new JButton("Create Dog");
exitB = new JButton("Exit");
//text fields
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
typeTF = new JTextField(15);
ageTF = new JTextField(5);
outtputTF = new JTextField(25);
outtputTF.setEditable(false); //this TF is to display this output
//Lables and Textfields
DogInfo.add(nameL);
DogInfo.add(nameTF);
DogInfo.add(typeL);
DogInfo.add(typeTF);
DogInfo.add(ageL);
DogInfo.add(ageTF);
DogInfo.add(outtputL);
DogInfo.add(outtputTF);
//Buttons
DogInfo.add(createB);
DogInfo.add(exitB);
//Instantiate Listeners
cbHandler = new CreateButtonHandler();
ebHandler = new ExitButtonHandler();
//Register Listeners
createB.addActionListener(cbHandler);
exitB.addActionListener(ebHandler);
DogInfo.setVisible(true);
}
//run the program from main, instantiate class, invoke driver() method
public static void main(String[] args)
{
DogGUI d = new DogGUI();
d.driver();
}
// class to actually handle Dog creation
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
private class ExitButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("inside exit button");
System.exit(0);
} // end method actionPerformed
}
}
You have a local variable in the driver() method called nameTF that is hiding that field (same for some other variables).
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
Remove the declaration of those fields since they are already declared as instance fields.
private JTextField nameTF, typeTF, ageTF;
(probably not outtputTF, depending on what you want to do)

Categories

Resources