JFrame will not display panel/buttons (Separate Classes) - java - java

So I need to used two classes for my GUI, one class is called "UI" and has a main method and the other is UIControls which will contain all the JPanels/Buttons and eventually the GridLayout. The only issue is my JFrame will not show any buttons or JPanels but before I made a seperate class for them everything worked fine.
Anyway thanks in advance =]
Regards -SKENG-
//EDIT: I already had "application.add(MP);" in the code I removed it before I posted it on this site. Cant remeber why I was just trying some things I've re-added it again now and It still doesnt work. Also the gridlayout was just a experiment I'm creating a different panel for that later ;)
UI - Main
import java.awt.*;
import javax.swing.*;
public class UI {
public static JFrame application;
public static void main(String []args) {
//=================FRAME SETTINGS=================
application = new JFrame("Despatch Depot Simulator");
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setLocation(500,200);
application.setSize(640,480);
application.setLayout(null);
application.setBackground(Color.WHITE);
application.setVisible(true);
application.setResizable(false);
}
}
UIControls
import java.awt.*;
import javax.swing.*;
public class UIControls extends UI {
public UIControls() {
//=================PANEL LAYOUT=================
JPanel MP = new JPanel(); //Main UI's Panel (MP = MainPanel)
MP.setBounds(1,1,640,480);
MP.setBackground(Color.WHITE);
MP.setLayout(null);
application.add(MP);
//=================JBUTTONS=================
JButton AddBox = new JButton("Add Box"); {MP.add(AddBox);}
AddBox.setBounds(505,2,125,30);
JButton AddTube = new JButton("Add Tube"); {MP.add(AddTube);}
AddTube.setBounds(505,34,125,30);
JButton AddEnvelope = new JButton("Add Envelope"); {MP.add(AddEnvelope);}
AddEnvelope.setBounds(505,66,125,30);
JButton ClearAll = new JButton("Clear All"); {MP.add(ClearAll);}
ClearAll.setBounds(505,98,125,30);
JButton CurrentCharge = new JButton("Current Charge"); {MP.add(CurrentCharge);}
CurrentCharge.setBounds(505,418,125,30);
JButton TotalCharge = new JButton("Total Charge"); {MP.add(TotalCharge);}
TotalCharge.setBounds(378,418,125,30);
JButton Save = new JButton("Save"); {MP.add(Save);}
Save.setBounds(2,418,125,30);
JButton Load = new JButton("Load"); {MP.add(Load);}
Load.setBounds(130,418,125,30);
//=================IMAGES=================
ImageIcon imageB = new ImageIcon ("..\\Images\\box.png");
ImageIcon imageBL = new ImageIcon ("..\\Images\\box-large.png");
ImageIcon imageEL = new ImageIcon ("..\\Images\\envelope-large.png");
ImageIcon imageEM = new ImageIcon ("..\\Images\\envelope-medium.png");
ImageIcon imageES = new ImageIcon ("..\\Images\\envelope-small.png");
ImageIcon imageT = new ImageIcon ("..\\Images\\tube.png");
ImageIcon imageTL = new ImageIcon ("..\\Images\\tube-large.png");
//=================LABELS=================
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel();
JLabel label4 = new JLabel();
JLabel label5 = new JLabel();
JLabel label6 = new JLabel();
JLabel label7 = new JLabel();
GridLayout experimentLayout = new GridLayout(4,3);
MP.setLayout(experimentLayout);
}
}

You are not adding your JPanel to your JFrame nor adding any JLabel or JButton to your JPanel.
Try :
add(MP); //somewhere in your UIControls constructor
Then, but this is another problem, why are you doing :
MP.setLayout(null);
First of all you should avoid null layout, then this method call is completely unuseful because after in your code you are setting MP layout to be a GridLayout (MP.setLayout(experimentLayout);)
In addition to that you are not constructing anywhere UIControls class.

In addition to 0verbose answer, I don't see why UIControl extends the UI class.
What you should do is organize your classes in a better way. One main class that "launch" and create the JFrame. For the UIControl class, you can add it as an attribute of the UI class, then instantiate it when the UI object is created, and add it to the panel/
public class Launcher {
public static void main(String[] args)
{
UI uiFrame = new UI();
}
}
public class UI extends JFrame {
// the panel that will be added to the JFrame
private UIControl uiControlPanel;
public UI()
{
super("JFrame title");
// set size, layout, and other stuffs here
//
this.uiControlPanel = new UIControl();
this.add(this.uiControlPanel);
// make the window visible
this.setVisible(true);
}
}
By the way, you might wanna name your classes with more explicit names than "UI", call them "MainFrame", "MainFramePanel", and so on so you can guess the type of the component just reading its name.
I think you should go through Swing tutorials of (Sun) Oracle again.

Related

How can I add my button on top of my Gif/Png [duplicate]

This question already exists:
Using an image for background
Closed 8 months ago.
Earlier I made a post of having both of them showing up and that got solved but the other problem I ran into is that I am having a hard time stacking them over each other
This is how I have it currently
The way I want it to have is the blue box being on top of the Signup part of the image
Like this
import javax.swing.*;
import java.awt.*;
public class Panel extends JFrame {
private ImageIcon FirstPageImage;
private JLabel FirstPageLabel;
private JLayeredPane SignupButtonLayer;
private JButton Button;
public Panel(){
setLayout (new FlowLayout());
FirstPageImage = new ImageIcon(getClass().getResource("FirstPageAnimationUsing.gif"));
FirstPageLabel = new JLabel(FirstPageImage);
FirstPageImage.setImage(FirstPageImage.getImage().getScaledInstance(343,820,Image.SCALE_DEFAULT));
add(FirstPageLabel);
Button = new JButton();
SignupButtonLayer = new JLayeredPane();
SignupButtonLayer.setPreferredSize(new Dimension(370,850));
//Button.setOpaque(true);
Button.setBackground(Color.cyan);
Button.setBounds(94,617,159,82);
SignupButtonLayer.add(Button, JLayeredPane.DEFAULT_LAYER);
add(SignupButtonLayer);
}
public static void main(String[] args) {
Panel gui = new Panel();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setTitle("Reminder App");
gui.setVisible(true);
//gui.setSize(360,850);
}
}
I have a feeling that it has something to do with the Layout but I am not sure

Frames and Buttons

Hi though i did complete the basics of java which im fairly new of, i keep getting errors when i try to add buttons on a new Frame/Panel. Care to educate me on what the problem might be?
import javax.swing.*;
import java.awt.*;
class MainClass {
String cont_orders;
private JFrame frame1;
private JPanel mainpanel;
JButton bt1, bt2, bt3, bt4, bt5;
private JButton btotal = new JButton("Order");
private JButton clearOr = new JButton("Clear");
private JTextField pricetotal = new JTextField();
private JTextField list_of_orders = new JTextField();
public MainClass(){
gui();
}
private void gui(){
frame1 = new JFrame("Order");
frame1.setSize(500,430);
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setResizable(false);
mainpanel = new JPanel();
mainpanel.setBackground(Color.BLUE);
mainpanel.add(bt1);
bt1 = new JButton("M-Item 1 [Soda]");
frame1.add(mainpanel,BorderLayout.CENTER);
}
public static void main (String[]args){
new MainClass();
}
}
im trying to practice on coding normally instead of relying on that automatic one in NetBeans [JFrame Form/JPanel Form]
care to help?
Now this cannot be done in java
mainpanel.add(bt1);
bt1 = new JButton("M-Item 1 [Soda]");
Turn it around.
Explanation: the field bt1 is at that time a variable holding the null object.
That object (value) is added, not some variable address as in other languages.
Reverse it bt1 = new JButton("M-Item 1 [Soda]"
mainpanel.add(bt1);
Because if not the value of bt1 would be null so you must fill it first then use it .
Or
mainpanel.add(new JButton("..."));

Java - updating values in JFrame/JLabels

I am a beginner Java-coder and a few days ago I felt confident enough in my skills to start my first "big" project. It was basically a calculator, a GUI(only JFrame, JPanels, JLabels and Buttons) that would display data, accept user input, grab some more data from other classes, then calculate stuff and finally update the GUI with the new JLabel values. However I never managed to get the update part done properly, whenever I would press the 'process'-button it would create a new JFrame with the new values, while the old one was still up.
I tried the obvious stuff (repaint(), revalidate(), etc) but that didn't work at all, then I started to shift things around, put parts of the code into new classes, copied code from the net until it eventually worked. However the code was a total mess and I didn't even really understand what went exactly wrong in the first place, so I trashed the entire thing.
Here is a very simplified version of my code before things went downhill:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test_1 extends JFrame {
public static class clicks{
static int clicks = 0;
public int getclicks(){
return clicks;
}
public void setclicks(){
clicks = clicks+1;
}
}
public Test_1(){
clicks getNumber = new clicks();
int x = getNumber.getclicks();
//FRAME AND LAYOUT
JFrame window = new JFrame();
window.getContentPane().setBackground(Color.darkGray);
window.getContentPane().setLayout(new BorderLayout(20,10));
window.setTitle("Test Frame 1");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(true);
// Top JPanel
JPanel northpanel = new JPanel();
LayoutManager northlayout = new FlowLayout();
northpanel.setLayout(northlayout);
// Top JPanel content
JLabel nlabel1 = new JLabel("Hello North");
nlabel1.setPreferredSize(new Dimension(100,20));
northpanel.add(nlabel1);
JPanel westpanel = new JPanel();
LayoutManager westlayout = new BoxLayout(westpanel, BoxLayout.Y_AXIS);
westpanel.setLayout(westlayout);
JLabel wlabel1 = new JLabel("Hello West");
wlabel1.setPreferredSize(new Dimension(100,20));
westpanel.add(wlabel1);
JPanel eastpanel = new JPanel();
LayoutManager eastlayout = new BoxLayout(eastpanel, BoxLayout.Y_AXIS);
eastpanel.setLayout(eastlayout);
JLabel elabel1 = new JLabel ("Hello East");
elabel1.setPreferredSize(new Dimension(100,20));
eastpanel.add(elabel1);
JButton southbutton = new JButton("start");
southbutton.setPreferredSize(new Dimension(400,50));
southbutton.addActionListener(new Action());
JPanel centralpanel = new JPanel();
JLabel clabel1 = new JLabel("Clicks: " + x);
centralpanel.add(clabel1);
window.add(centralpanel, BorderLayout.CENTER);
window.add(southbutton, BorderLayout.SOUTH);
window.add(eastpanel, BorderLayout.EAST);
window.add(westpanel, BorderLayout.WEST);
window.add(northpanel, BorderLayout.NORTH);
window.pack();
window.setVisible(true);
}
public static void main(String[] args) {
Test_1 window_start = new Test_1();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e){
clicks Numbers = new clicks();
Numbers.setclicks();
int test = Numbers.getclicks();
System.out.println("Button works, Number of clicks: "+test);
Test_1 updateData = new Test_1();
}
}
}
I know that the ActionListener creates a new instance of my JFrame, however that was the closest I ever came to "updating the JFrame" before I turned the code into Spaghetti. I assume that the way I build my code is the cause of my problem but creating the Frame and its content it different classes didn't work at all.
So my questions are:
Is there something really obvious I missing? Would it be possible to make this run the way I want to without completely changing it?
Is there a more efficient way to create a GUI? I get the feeling that the way I made this is total garbage.
I read other questions that dealt with similar problems but maybe it's because I am still pretty bad at Java but I couldn't really tell if they were related to my problem. Also I really want to understand this, so copying someone elses code wouldn't help at all.
Any help or comments are appreciated.
btw, the class click is something I just put there as a placeholder.
Alrighty I managed to get it to work. It's probably against the Etiquette to answer to his own question but I thought it might be useful for some beginners(like me yesterday). So here is my new code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test_1 extends JFrame {
public static class clicks{
static int clicks = 0;
public int getclicks(){
return clicks;
}
public void setclicks(){
clicks = clicks+1;
}
}
clicks getNumber = new clicks();
int x = getNumber.getclicks();
JPanel northpanel, westpanel, eastpanel, southpanel, centralpanel;
static JLabel nlabel1, nlabel2, nlabel3, nlabel4, nlabel5;
static JLabel wlabel1, wlabel2, wlabel3, wlabel4, wlabel5;
static JLabel elabel1, elabel2, elabel3, elabel4, elabel5;
static JLabel clabel1;
JButton southbutton;
String TextnL, TextwL, TexteL;
public Test_1(){
setBackground(Color.darkGray);
setLayout(new BorderLayout(20,10));
setTitle("Test Frame 1");
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLocationRelativeTo(null);
setVisible(true);
nlabel1 = new JLabel("North_1");
nlabel2 = new JLabel("North_2");
nlabel3 = new JLabel("North_3");
nlabel4 = new JLabel("North_4");
nlabel5 = new JLabel("North_5");
wlabel1 = new JLabel("West_1 ");
wlabel2 = new JLabel("West_2 ");
wlabel3 = new JLabel("West_3 ");
wlabel4 = new JLabel("West_4 ");
wlabel5 = new JLabel("West_5 ");
elabel1 = new JLabel("East_1");
elabel2 = new JLabel("East_2");
elabel3 = new JLabel("East_3");
elabel4 = new JLabel("East_4");
elabel5 = new JLabel("East_5");
clabel1 = new JLabel("START");
southbutton = new JButton("Process");
southbutton.addActionListener(new Action());
northpanel = new JPanel();
northpanel.add(nlabel1);
northpanel.add(nlabel2);
northpanel.add(nlabel3);
northpanel.add(nlabel4);
northpanel.add(nlabel5);
add(northpanel, BorderLayout.NORTH);
westpanel = new JPanel();
LayoutManager wBox = new BoxLayout(westpanel, BoxLayout.Y_AXIS);
westpanel.setLayout(wBox);
westpanel.add(wlabel1);
westpanel.add(wlabel2);
westpanel.add(wlabel3);
westpanel.add(wlabel4);
westpanel.add(wlabel5);
add(westpanel, BorderLayout.WEST);
eastpanel = new JPanel();
LayoutManager eBox = new BoxLayout(eastpanel, BoxLayout.Y_AXIS);
eastpanel.setLayout(eBox);
eastpanel.add(elabel1);
eastpanel.add(elabel2);
eastpanel.add(elabel3);
eastpanel.add(elabel4);
eastpanel.add(elabel5);
add(eastpanel, BorderLayout.EAST);
centralpanel = new JPanel();
centralpanel.add(clabel1);
add(centralpanel, BorderLayout.CENTER);
add(southbutton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
Test_1 window_start = new Test_1();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e){
clicks Numbers = new clicks();
Numbers.setclicks();
int test = Numbers.getclicks();
clabel1.setText("clicks: "+test);
}
}
}
And again, any comments/suggestions are welcome.

Java GUI - JButton opens another frame from another class

i'm having trouble to get the 2nd frame to display the GUI Components. i've opened the frame using the JButton from the 1st frame.
Here's the screen shot
This is the first frame - ClientModule.java
2nd frame - ClientMenu.java
Here's the codes i've tried
ClientModule.java
import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ClientModule extends JFrame implements Runnable{
private JPanel panel;
private JFrame frame;
private JLabel titleLbl, userLbl, passLbl, hostLbl, portLbl, ipLbl;
private JTextField userTxt, hostTxt, portTxt, ipTxt;
private JPasswordField passTxt;
private JButton loginBtn;
public static void main(String[] args)
{
new ClientModule().run();
}
public ClientModule()
{
frame = new JFrame("DMS(Drawing Message System)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setPreferredSize(new Dimension(500,500));
panel.setLayout(new FlowLayout());
titleLbl = new JLabel("LogIn to Drawing Message System(DMS)");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
userLbl = new JLabel("Username:");
passLbl = new JLabel("Password:");
hostLbl = new JLabel("Hostname:");
portLbl = new JLabel("Port No.:");
ipLbl = new JLabel("IP Address:");
userTxt = new JTextField();
userTxt.setPreferredSize(new Dimension(100,30));
passTxt = new JPasswordField();
passTxt.setEchoChar('*');
passTxt.setPreferredSize(new Dimension(100,30));
portTxt = new JTextField();
portTxt.setPreferredSize(new Dimension(100,30));
ipTxt = new JTextField();
ipTxt.setPreferredSize(new Dimension(100,30));
hostTxt = new JTextField();
hostTxt.setPreferredSize(new Dimension(100,30));
loginBtn = new JButton("Login!");
loginBtn.setPreferredSize(new Dimension(90,30));
loginBtn.addActionListener(new LoginBtnListener());
panel.add(titleLbl);
panel.add(userLbl);
panel.add(userTxt);
panel.add(passLbl);
panel.add(passTxt);
panel.add(hostLbl);
panel.add(hostTxt);
panel.add(portLbl);
panel.add(portTxt);
panel.add(ipLbl);
panel.add(ipTxt);
panel.add(loginBtn);
frame.add(panel);
}
private class LoginBtnListener implements ActionListener
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
//thinking this frame will close after ClientMenu's frame is open
ClientModule client = new ClientModule();
client.setVisible(false);
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
}
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
ClientMenu.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class ClientMenu extends JFrame{
JFrame frame;
JPanel panel;
JLabel titleLbl;
JButton sendBtn,receiveBtn,logoutBtn;
public ClientMenu()
{
frame = new JFrame("Drawing Message System(DMS)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setPreferredSize(new Dimension(500,500));
titleLbl = new JLabel("Main Menu");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
sendBtn = new JButton("Send a Drawing");
sendBtn.setPreferredSize(new Dimension(100,30));
receiveBtn = new JButton("Receive a Drawing");
receiveBtn.setPreferredSize(new Dimension(100,30));
logoutBtn = new JButton("Logout");
logoutBtn.setPreferredSize(new Dimension(100,30));
logoutBtn.addActionListener(new LogoutBtnListener());
panel.add(titleLbl);
panel.add(sendBtn);
panel.add(receiveBtn);
panel.add(logoutBtn);
frame.add(panel);
}
private class LogoutBtnListener implements ActionListener
{
//#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
ClientModule client = new ClientModule();
client.setVisible(true);
ClientMenu menu = new ClientMenu();
menu.setVisible(false);
}
}
public static void main(String[] args)
{
new ClientMenu().run();
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
I'm not sure if i'm missing something, or coded something wrong, or something else. I've already searched and tried..
any help and understanding is appreciated (:
I managed to get the second frame displayed (including its contents) by adding a call to the run() method:
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
menu.run();
That being said, there are quite some problems with your code:
You have a main method in each of your classes. You should have only 1 main method per application. Since ClientModule seems to be the first Frame you want to have opened, your might want to keep the main method there and remove the one in the other class.
You have a run() method in each class. Personally, I tend to avoid naming methods like this, since it might cause confusion with the run() method which needs to be overridden when dealing with threads. You are clearly attempting to do some multi threading in your ClientModule, but will not work. Please look into this concurrency tutorial to better understand threads. You should also understand that you should never call run() yourself. The tutorial should make that clear.
Swing applications are started a little bit differently that other applications. Please refer to this tutorial for more information.
You have both your classes extend JFrame but then, provide your own. This results in other JFrames being created, which is what happened in my case (I get 2 JFrames per instantiation). If you want your class to behave like a JFrame, consider extending it, if you want to use a JFrame, then compose your class of one, not both (at least not in this case).
Lastly, to get rid of the previous JFrame you could call dispose() on the it. That being said, the approach usually is to use the Card Layout. This would allow you to have 1 frame with multiple content.
Sorry for the long post, but please consider re factoring as per the above prior to continuing.
You can use the setVisible property to 'true' or 'false'.

Using .setVisible() outside the constructor breaks my GUI

I am just now learning the basics of java GUI. I have this weird situation that I can't really explain.
I have a GUI class, where I build a simple JFrame. If I use .setVisible(true) within the constructor everything works fine, if I use it outside, nothing loads (the window is visible, but the buttons and what not aren't).
Why is this happening ?
public class GUI extends JFrame {
private JTextField humanYears_TextField = new JTextField(3);
private JTextField dogYears_TextField = new JTextField(3);
private JButton convert_Button = new JButton("Convert");
private JLabel greeting = new JLabel ("Dog years to Human years!");
public GUI () {
JFrame window = new JFrame();
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(this.greeting);
content.add(new JLabel("Dog Years: "));
content.add(this.dogYears_TextField);
content.add(this.convert_Button);
content.add(new JLabel("Human Years: "));
content.add(this.humanYears_TextField);
window.setContentPane(content);
pack(); // aplica contentPane-ul
window.setLocationRelativeTo(null);
window.setTitle("Dog Year Converter");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true); // IF IT'S HERE IT WORKS
}
}
public static void main(String[] args) {
GUI dogYears = new GUI();
//dogYears.setVisible(true); // IF IT'S HERE
//NOTHING EXCEPT THE WINDOW LOADS
}
Why is this happening ?
In this example it doesn't matter, but what if I want to make a window visible only if I click a button or something ?
1) You create 2 instances of JFrame the first from extending JFrame on the class and the second from JFrame window=... You than go on to call setVisible(..) on the window and in your main you attempt to call setVisible(...) on your dogYears.
Solution
You should only create one JFrame per Swing GUI. Get rid of the extends JFrame (and the code that goes with it), as its not good practice to extend JFrame in Swing. Thus of course you wont be able to call setVisible(true) in your constructor which is fine either call it after creating the GUI in the constructor or make a method like setVisible in GUI class which will be a wrapper for your JFrames setVisble(boolean b) method.
Other suggestions
Always create your Swing components on the Event Dispatch Thread which you should do in via SwingUtilitites.invokeLater(Runnable r) block. Have a read on Concurrency in Swing.
Remember to call pack before setting JFrame visible and after adding components.
setLocationRelativeTo(..) should come after pack().
Better to use JFrame.DISPOSE_ON_CLOSE unless using Timers.
Also no need for setContentPane simply call add(..) on JFrame instance.
Here is your code with above mentioned fixes:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class GUI {
private JTextField humanYears_TextField = new JTextField(3);
private JTextField dogYears_TextField = new JTextField(3);
private JButton convert_Button = new JButton("Convert");
private JLabel greeting = new JLabel("Dog years to Human years!");
private JFrame window = new JFrame();
private JPanel content = new JPanel();
public GUI() {
content.setLayout(new FlowLayout());
content.add(this.greeting);
content.add(new JLabel("Dog Years: "));
content.add(this.dogYears_TextField);
content.add(this.convert_Button);
content.add(new JLabel("Human Years: "));
content.add(this.humanYears_TextField);
window.add(content);
window.setTitle("Dog Year Converter");
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
window.pack();
window.setLocationRelativeTo(null);
//window.setVisible(true); //works here now
}
//our wrapper method so we can change visibility of our frame from outside the class
void setVisible(boolean visible) {
window.setVisible(visible);
}
public static void main(String[] args) {
//Create Swing components on EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI dogYears = new GUI();
dogYears.setVisible(true);//works here too
}
});
}
}
You've got two JFrames, the GUI class itself and the internal variable "window". Use only one.
Make sure that GUI does not extend JFrame (there's no need for this), and give the class a public void setVisible(boolean) method that sets the window to visible.
public class GUI {
private JTextField humanYears_TextField = new JTextField(3);
private JTextField dogYears_TextField = new JTextField(3);
private JButton convert_Button = new JButton("Convert");
private JLabel greeting = new JLabel ("Dog years to Human years!");
private JFrame window = new JFrame();
public GUI () {
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(this.greeting);
content.add(new JLabel("Dog Years: "));
content.add(this.dogYears_TextField);
content.add(this.convert_Button);
content.add(new JLabel("Human Years: "));
content.add(this.humanYears_TextField);
window.setContentPane(content);
pack(); // aplica contentPane-ul
window.setLocationRelativeTo(null);
window.setTitle("Dog Year Converter");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// window.setVisible(true); // IF IT'S HERE IT WORKS
}
public void setVisible(boolean visible) {
window.setVisible(visible);
}
}
You have two different instances :-)
in your constructor:
JFrame window = new JFrame();
window.setVisible(true); // IF IT'S HERE IT WORKS
in your main:
GUI dogYears = new GUI();
dogYears.setVisible(true);
// dogYears != local var window in constructor
Which might get me starting on not extending classes, but using them.
Your class GUI extends from a JFrame, but in the constructor, you are initializing another JFrame, which results in having two different JFrames.
Try this:
public class GUI {
private JTextField humanYears_TextField = new JTextField(3);
private JTextField dogYears_TextField = new JTextField(3);
private JButton convert_Button = new JButton("Convert");
private JLabel greeting = new JLabel ("Dog years to Human years!");
public GUI () {
JFrame window = new JFrame();
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(this.greeting);
content.add(new JLabel("Dog Years: "));
content.add(this.dogYears_TextField);
content.add(this.convert_Button);
content.add(new JLabel("Human Years: "));
content.add(this.humanYears_TextField);
window.setContentPane(content);
pack(); // aplica contentPane-ul
window.setLocationRelativeTo(null);
window.setTitle("Dog Year Converter");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
// main
}
you are creating an instance of JFrame in constructor of GUI which also extends JFRame.
Now you are creating different components and added them on 'window' object.
As you know a frame is set as visible= false and undecorated=false.
So to set a particular JFrame instance you need to call setVisible() method on that instance.
Here you are just creating an instance of GUI and didn't added any component on it.
write a statement in constructor as following rather than "window.setContentPane(content);":
setContentPane(content);
and then call setVisible() method on your instance of GUI class i.e d*ogYears.setVisible(true);*!!

Categories

Resources