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

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);
}
}

Related

Why doesn't JTextfield in java display text at runtime?

Hope you are all well!
Hope you understand my Java question... I have created a JFrame window with text to display, but it doesn't display at run-time (as it should) unless I maximise the Frame window.
Can't understand it?
Here's some code:
package test;
import javax.swing.*;
class Test{
private String x;
private Test() {
x="150";
}
public static void main(String[] args) {
Test o1 = new Test();
JTextField l = new JTextField(o1.x, JTextField.CENTER);
l.setAlignmentX(0);
l.setAlignmentY(0);
JFrame window = new JFrame("Hello World!");
window.setSize(800, 600);
window.setResizable(true);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(l);
}
}
Altering the size of the frame (by maximising it) will cause it to be repainted. The reason it needs to be repainted is that you added content to it after you already made it visible.
Instead, you could move window.setVisible(true); to the end, so you don't show the window until you've added everything to it.

Why isn't my GUI showing up?

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);
}
}

JButton not changing size

I've researched the ways to change the size of a jbutton to be displayed on a JFrame.
I am trying both the button.setSize(200,200) and button.setPreferredSize(new Dimension(200,200)), but it does not change. Here's the code:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Index extends JFrame{
private String title = "This is the motherfucking title";
Dimension dim = new Dimension(500,500);
public Index(){
this.setResizable(false);
this.setTitle(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(dim);
this.getContentPane().setBackground(Color.BLACK);
JButton button = new JButton("Button");
button.setSize(200,200);
this.add(button);
}
public static void main(String args[]){
Index ih = new Index();
ih.setVisible(true);
}
}
Here's the result: http://i.imgur.com/Llj0pfo.png
What am I doing wrong?
try this:
JButton button = new JButton("Button");
button.setSize(200,200);
getContentPane().setLayout(null);
getContentPane().add(button);
setVisible(true);
inside your constructor.
this.add(button);
You are adding the button to the content pane of the frame. By default the content uses a BorderLayout and the component is added to the CENTER. Any component added to the CENTER will automatically get the extra space available in the frame. Since you set the size of the frame to (500, 500) there is lots of space available.
As a general rule you should NOT attempt to set the preferred size of a component, since only the component know how big it should be in order to paint itself properly. So your basic code should be:
JButton button = new JButton("...");
frame.add(button);
frame.pack();
frame.setVisible(true);
Now the button will be at its preferred size. However, the button will change size if you resize the frame. If you don't want this behaviour, then you need to use a different Layout Manager.
Use SwingUtilities.invokeLater(); create your Index() inside it, then call setVisible(true); at the end of constructor. At the same time remeber that by default JFrame uses BorderLayout.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Index();
}
});

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();
}
}

Java Swing blank screen instead of window displayed

I'm following through a book called "The JFC Swing Tutorial (Second Edition)" and I'm pretty much at the start I have followed this code and it should be displaying the button and the label in the content pane, but All im getting is a blank screen. any ideas?
Thanks.
import java.awt.GridLayout;
import javax.swing.*;
public class m extends JFrame
{
void UserFrame()
{
//JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Hellow You");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel(new GridLayout(0,1));
//makes label
JLabel label = new JLabel("Sup ");
//adds to the frames content pane a label
frame.getContentPane().add(label);
JButton button = new JButton("Hai");
frame.getContentPane().add(button);
jp.add(button);
jp.add(label);
jp.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
//pack set the window to what it needs AKA to display all components
frame.pack();
//frame.setSize(250, 250);
//shows window
frame.setVisible(true);
}
public static void main(String[] args)
{
final m window = new m();
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
window.UserFrame();
}
});
}
}
Simply add
frame.add(jp);
just before
frame.pack();
What's happening here? You correctly add all your widgets to a JPane, but you basically threw that JPane away and didn't use it anywhere.
This will be sufficient just to get it to work properly.
If you want to do it correctly, you should also remove frame.getContentPane().add(label); and frame.getContentPane().add(button); (Thank you #dic19 for noting that!). These will not work the way you used it.

Categories