Why isn't my GUI showing up? - java

I have been working on a GUI calculator, but it is not working properly. When i run the program, the frame does not show up. This is my program:
package mycalc;
/**
*
* #author haysa
*/
import javax.swing.*;
import java.awt.event.*;
public class MyCalc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame f;
JTextField first, second;
JButton bdiv,bmul,bsub,badd,beq;
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
beq=new JButton("=");
bsub.setBounds(250,240,50,40);
bmul.setBounds(250,170,50,40);
bdiv.setBounds(250,100,50,40);
badd.setBounds(250,310,50,40);
beq.setBounds(180,310,50,40);
first=new JTextField("");
second=new JTextField("");
f=new JFrame("Calculator");
f.add(bdiv);
f.add(bmul);
f.add(bsub);
f.add(badd);
}
}
I'm not sure what is wrong with my program. It keeps saying that build is successful but nothing appears. I know I need to add something, but I'm not sure what to add, or where to put it. Please help me :D

After you declare your frame, f, you have to use setVisible(true);, or else the window will not appear. You may notice the java icon in your desktop, because it did open the window, however it can not be clicked, moved, or (obviously) seen.
//...
f=new JFrame("Calculator");
f.setVisible(true); //added this line
f.add(bdiv);
f.add(bmul);
f.add(bsub);
f.add(badd);
//...
As of now, your window will be very small(set the size using f.setSize(x, y)), and it will appear in the top left corner of your screen. To make the top left of your window appear in the middle of your screen, use f.setLocationRelativeTo(null);. And one more thing is you have to set the layout to null (f.setLayout(null)) otherwise your setBounds() method won't work. Please comment below if you have any questions.

You have to add the f.setVisible(true) function and if you use setBounds(x,y,w,h) then you need to set the layout of JFrame to null like this f.setLayout(null);
class MyCalc{
public static void main(String[] args) {
// TODO code application logic here
JFrame f=new JFrame("Calculator");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(555,555);
f.setLayout(null);
JTextField first, second;
JButton bdiv,bmul,bsub,badd,beq;
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
beq=new JButton("=");
bsub.setBounds(250,240,50,40);
bmul.setBounds(250,170,50,40);
bdiv.setBounds(250,100,50,40);
badd.setBounds(250,310,50,40);
beq.setBounds(180,310,50,40);
first=new JTextField("");
second=new JTextField("");
f.add(bdiv);
f.add(bmul);
f.add(bsub);
f.add(badd);
f.setVisible(true);
}
}

Related

Java Swing adding a JButton to a JFrame doesn't work

I have been coding with Swing for a long moment in windows and when I switched to Manjaro Linux, something as basic as adding a JButton to a JFrame wouldn't work. (Also I have no output in the console, no missing libraries only a blank window).
Can someone help me figure this out?
Here is the code:
package test;
import javax.swing.JButton;
import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
JFrame window = new JFrame();
JButton button = new JButton("My button");
window.setSize(600,600);
window.setVisible(true);
window.add(button);
}
}
As mentioned in a comment:
window.setSize(600,600);
window.setVisible(true);
window.add(button);
Should instead be
window.add(button);
window.pack();
window.setVisible(true);
Always add all the components before setting the window visible.
window.setSize(600,600); is no better than a guess, whereas window.pack(); makes the window the size it needs to be.
This is the code used for the above screenshot. Further details in code comments.
import java.awt.Insets;
import javax.swing.*;
public class DisplayButton {
public static void main(String[] args) {
JFrame window = new JFrame();
JButton button = new JButton("My button");
// This is a random guess as to how big the window should be. DON'T GUESS
//window.setSize(600,600);
// The button should be added before the frame is packed to size and displayed
window.add(button);
// But since you want it BIG, let's make it so,
// usefully by first increasing the text size
button.setFont(button.getFont().deriveFont(60f));
// Then add a chunk of insets - adjust to need.
button.setMargin(new Insets(20, 100, 20, 100));
// Make the window the size it NEEDS to be to display the button.
window.pack();
window.setVisible(true);
}
}

How to display one Jframe at a time? [duplicate]

I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).

JFrame not displaying button or background color

My JFrame is not displaying the button or background color that is set in the constructor. I am only getting a blank box when I start the program. Not sure what is wrong with the code.
//imports
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;;
public class StartingTheCode{
JButton CalculateButton;
JTextField Ans;
JPanel p;
JFrame f;
public static void main (String[] args){
new StartingTheCode();
}
//constructor
StartingTheCode(){
f = new JFrame("test");
f.setVisible(true);
f.setSize(600,600);
f.setLocationRelativeTo(null);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p = new JPanel();
p.setBackground(Color.BLUE); // not displaying blue background
CalculateButton = new JButton("+"); // should display button
CalculateButton.setSize(30,30);
CalculateButton.setLocation(5,5);
}
}
You're not adding your button or your JPanel to anything, and so no JFrame is magically going to display them.
You should add your JButton to your JPanel via its add(...) method, and then add the JPanel to the JFrame via its add(...) method, and do so before setting the JFrame visible.
Most importantly, you should read the Swing tutorials, since I speak from experience when saying you'll get no-where just guessing at this stuff. This is all well explained there.
As an aside, avoid setting the sizes of any components and instead read the tutorial section on use of the layout managers as it will allow you to simplify and empower your code greatly.
You need to add your calculateButton to the JPanel with p.add(calculateButton) and add the panel to the frame with f.add(p)

Java - How to make contents of JFrame appear in the same Window instead of multiple windows

I am new to java and am getting to the advanced level of it, i have a problem in the GUI Controls, i made a button that when clicked opens up a new window like this:
JButton b = new JButton("Open New Window");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Window w = new Window();
w.setVisible(true);
}
});
this window contains other objects but i have been thinking of making the button in such a way that instead of opening a new JFrame, it opens everything in that same window without opening a new window, honestly i dont know how to do so please could i get some professional help
I think you want a card layout for this situation. Here is some code which should point you in the right direction.
class MyFrame extends JFrame {
public MyFrame() {
JComponent allMyStuff = new JComponent();
JComponent allMyOtherStuff = new JComponent();
this.getContentPane().setLayout(new CardLayout());
this.getContentPane().add(allMyStuff, "1");
this.getContentPane().add(allMyOtherStuff, "2");
CardLayout cl = (CardLayout) (this.getContentPane().getLayout());
cl.show(this.getContentPane(), "1");
JButton b = new JButton("Open New Window"); //add somewhere to first compoonent
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (this.getContentPane().getLayout());
cl.show(this.getContentPane(), "2");
}
});
}
}
I doubt the code runs but generally it holds the idea. You have stuff in one panel, and stuff in another panel, and you just want to switch between the two. The button of course needs to be added in the first panel (allMyStuff) somewhere.
I"m not clear on what it is exactly that you want to show in the GUI when the button is pressed, but perhaps you should consider creating different JPanel "views" and swap these views in the GUI using a CardLayout.
For example, check out these StackOverflow questions and answers:
Java CardLayout Main Menu Problem
Change size of JPanel using CardLayout
Java CardLayout JPanel moves up, when second JPanel added
Java swing; How to toggle panel's visibility?
Clear components of JFrame and add new componets on the same JFrame
gui multiple frames switch
JLabel displaying countdown, java
Within the action listener that you have introduced, you have the possibility to access to instance variables. Therefore you can add further elements to your GUI if you want. I've done a small demo, maybe this is kind of, what you want to do. In order to make your GUI better, you should consider of using layout managers.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GUI {
JFrame frame;
JButton btn;
JButton compToAdd;
public GUI() {
frame = new JFrame("Testwindow");
frame.setSize(500, 500);
frame.setLayout(null);
btn = new JButton("test btn");
btn.setBounds(20, 20, 200, 200);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
compToAdd = new JButton("new Button");
compToAdd.setBounds(20, 220, 200, 200);
frame.add(compToAdd);
frame.repaint();
}
});
frame.add(btn);
frame.setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}

Adding JFileChooser with no action causes panels to not render

This is a weird problem. I have a solution for it, but I don't know WHY the problem occurs in the first place. Observe the code below:
// VERSION 1
public class test {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Test");
JPanel inputPanel = new JPanel();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(BorderLayout.CENTER, inputPanel);
mainFrame.setBounds(100, 50, 200, 100);
mainFrame.setVisible(true);
JButton inputFileButton = new JButton("BROWSE");
inputPanel.add(inputFileButton);
}
}
It works as expected. The button does nothing, but it renders correctly. Now, I add a JFileChooser (which I plan to do something with later, but for now all I'm doing is instantiating it).
// VERSION 2
public class test {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Test");
JPanel inputPanel = new JPanel();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(BorderLayout.CENTER, inputPanel);
mainFrame.setBounds(100, 50, 200, 100);
mainFrame.setVisible(true);
JFileChooser inputFileChooser = new JFileChooser(); // NEW LINE
JButton inputFileButton = new JButton("BROWSE");
inputPanel.add(inputFileButton);
}
}
All of a sudden my button no longer renders. Why? I know two ways to make it work again, but neither makes 100% sense to me. One way to fix it:
// VERSION 3
public class test {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Test");
JPanel inputPanel = new JPanel();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(BorderLayout.CENTER, inputPanel);
mainFrame.setBounds(100, 50, 200, 100);
mainFrame.setVisible(true);
JButton inputFileButton = new JButton("BROWSE");
inputPanel.add(inputFileButton);
JFileChooser inputFileChooser = new JFileChooser(); // MOVE LINE TO END
}
}
So moving that line to the end allows the button to render again, but that still makes no sense to me what an instantiated JFileChooser has to do with the unconnected button. Another way I can fix this issue:
// VERSION 4
public class test {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Test");
JPanel inputPanel = new JPanel();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(BorderLayout.CENTER, inputPanel);
mainFrame.setBounds(100, 50, 200, 100);
JFileChooser inputFileChooser = new JFileChooser();
JButton inputFileButton = new JButton("BROWSE");
inputPanel.add(inputFileButton);
mainFrame.setVisible(true); // MOVE *THIS* LINE TO THE END
}
}
It kind of makes sense why the version above fixes the problem... obviously something about the JFileChoose instantiation was making my button invisible, but this setVisible() method afterwards bring it back into the light. But that still doesn't tell me WHY it went invisible in the first place.
Can somebody please help me figure out what I'm missing? Thanks!
You are making your mainFrame visible and adding the button afterwards. Take a look at this SO question on what steps you need to take to make sure your button is visible.
The reason why it works in your first example is probably pure luck. Your call to add the button will be performed before the EDT shows your component.
Note: please perform the Swing operations on the EDT

Categories