The same Java-source leading to various results - java

I'm trying to learn Java and want to program a GUI. Trying to start with a simple calculator I ran into a problem while experimenting with JTextField. Compiling the following code sometimes results in an empty frame and sometimes in one with the panel and buttons in it.
This happens no matter if I use javac or eclipse.
I use the following code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Mainframe extends JFrame {
private JButton button1;
private JPanel mainpanel;
private JLabel headline;
private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JTextField number1;
JTextField number2;
public Mainframe(String s) {
super(s);
setSize(screenSize.width, screenSize.height);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainpanel = new JPanel(new BorderLayout(100, 100));
number1 = new JTextField(20);
number2 = new JTextField(20);
headline = new JLabel("Simple Calculator");
button1 = new JButton("1");
mainpanel.add(headline, BorderLayout.NORTH);
mainpanel.add(number1, BorderLayout.SOUTH);
mainpanel.add(button1, BorderLayout.EAST);
mainpanel.add(number2, BorderLayout.CENTER);
mainpanel.validate();
getContentPane().add(mainpanel);
}
public static void main(String[] args) {
Mainframe mainframe1 = new Mainframe("Title");
}
}
I want to repeat: This is not about differences between javac and eclipse but about a problem/occurence I have with both compilers - sometimes the result is as wanted, sometimes not. Why does that happen?
Thanks in advance!

Make sure that the call to JFrame.setVisible(true) is the last line you invoke.
So just move the line:
setVisible(true);
to the end of your constructor.
A few more remarks:
Don't extend if not needed (here it is not needed)
Make sure that all the UI-related operations are done on the EDT (use a SwingUtilities.invokeLater() block to start your UI)
Don't call setSize(screenSize.width, screenSize.height); but frame.setExtendedState(Frame.MAXIMIZED_BOTH); to make a window take the whole screen space. Consider also calling pack() before making the frame visible (but before calling frame.setExtendedState(Frame.MAXIMIZED_BOTH);) so that all components are properly laid out and this will also set the size of the frame to its computed preferred size.

Move your setVisible( true ) to a moment where you have added all your components.
If you do not do this, you need to re-validate the layout as indicated in the javadoc of the Container#add method:
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.

Related

JPanel not showing inside JFrame in Java

I know this question has been asked a lot and I have done my research but still can not find anything. Below is proof of this before anyone gets upset:
I found this link:
https://coderanch.com/t/563764/java/Blank-Frame-Panel
and this:
Adding panels to frame, but not showing when app is run
and this:
Why shouldn't I call setVisible(true) before adding components?
and this:
JPanel not showing in JFrame?
But the first question says use repaint which I tried with no fix and the second and third to last questions talk about putting setVisible after components added which I have.
The last one talks about making the users JPanelArt a extension (done so) of JPanel instead of JFrame and not to make a frame in a frame constructor (also have not done)
When ever I run this I just get a blank frame, as if the panel was never added in.
I apologise if I have missed something in those links. Anyway below is my classes:
GUI.java (extends JFrame)
package javaapplication2;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI extends JFrame{
public GUI(String name) {
super(name);
getContentPane().setLayout(null);
JPanel myPanel1 = new GUIPanel();
myPanel1.setLocation(20, 20);
getContentPane().add(myPanel1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setResizable(true);
}
public static void main(String[] args) {
JFrame frame = new GUI("Game");
frame.setVisible(true);
}
}
GUIPanel.java (extends JPanel)
package javaapplication2;
import java.awt.*;
import javax.swing.*;
public class GUIPanel extends JPanel {
JButton start;
JButton inspect1;
JButton inspect2;
JButton inspect3;
JButton suspect;
public GUIPanel() {
setLayout(new BorderLayout());
start = new JButton("Start Game");
inspect1 = new JButton("Inspect 1");
inspect2 = new JButton("Inspect 2");
inspect3 = new JButton("Inspect 3");
suspect = new JButton("Choose Suspect");
add(start, BorderLayout.WEST);
add(inspect1, BorderLayout.WEST);
add(inspect2, BorderLayout.WEST);
add(inspect3, BorderLayout.WEST);
add(suspect, BorderLayout.WEST);
}
}
I know it is very simple, but that is because I am following a tutorial from my lecturer to get the hang of things as I previously used a GUI builder which someone in this community pointed out to me is not good to start with (very correct!)
The issue lies in your GUI class when you call getContentPane().setLayout(null). Because of this method call, your JFrame is not displaying anything. If you remove it, your elements should show up.
I also noticed that you were setting each JButton to have a constraint of BorderLayout.WEST. This will most likely put your JButtons on top of each other and render only one of them.

Can not display the features using JFrame [duplicate]

I'm fairly new to JFrame and I want to know why my items are not showing up on the window. I know i dont have a ActionHandler but I just want my textfield's to show up on my window. Here's my code:
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class FirstGUI extends JFrame{
public void GUI(){
setTitle("Welcome");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(600,600);
JLabel title = new JLabel();
title.setText("Apple Inc. Member Login Port");
title.setFont(new Font("Arial", Font.PLAIN, 24));
JTextField login = new JTextField("Login",10);
JPasswordField pass = new JPasswordField("Password");
add(title);
add(login);
add(pass);
}
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
}
}
but when i run it i get this:
but when i run it i get this:
You get an empty screen because you add the components to the frame after the frame is visible.
As has already been suggested you need to use an appropriate layout manager. FlowLayout is the easiest to start with.
invoke setVisible(true) AFTER adding the components to the frame.
So the code should be more like:
panel.add(...);
panel.add(...);
add(panel);
pack();
setVisible(true);
I agree to MadProgrammer's suggestions (+1)
Well, lets take a look at your program though
You actually have created a JFrame with components in it. Its working fine as well, but your question of "why are my items not showing up in the JFrame" is not because you did something wrong but because missed out something i.e. revalidate()
Try:
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
a.revalidate();
}
I'm not saying this will give you perfect UI.. what I'm trying to say is this will help you understand the Swing better. Learn about Swing Layout managers and then work on your UI to have better results
revalidate(): This component and all parents above it are marked as needing to be laid out. This means the Layout Manager will try to realign the components. Often used after removing components. It is possible that some really sharp swing people may miss this. I would think that you will only know this if you are actually using Swing.
The default layout manager for JFrame is BorderLayout.
This means that your components are essentially all been added ontop of each other.
Try changing the layout manager to something like FlowLayout (for example)...
Take a look at A Visual Guide to Layout Managers and Using Layout Managers for more details.
Also, avoid setSize where possible, use Window#pack instead
Update
I'd also like to introduce you to Initial Threads which should be used to launch your UI code...
The only one reason :
setVisible(True); method for the frame should be put on the end of the code.
if you give this line on the top of the code that is when you create a frame. This will cause that problem.
Don't add the components directly to your frame. Instead add to the content pane, which is where a JFrame stores all of the components that it draws. Usually this is a JPanel.
Here is an example:
public class GUI
{
private JPanel content;
public void GUI
{
/*Other code*/
content = new JPanel();
add(content); //make content the content pane
content.add(title);
content.add(login);
content.add(pass);
}
If that fails, call setVisible(true) and setEnabled(true) on all of your components.
On a side note you may want to make your GUI function a constructor.
import javax.swing.*;
import java.awt.*;
class Myframec extends JFrame
{
Myframec()
{
Container c = this.getContentPane();
c.setLayout(null);
this.setBounds(10,10,700,500);
this.setTitle("Welcome");
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBounds(0,0,700,500);
panel.setBackground(Color.gray);
panel.setLayout(null);
c.add(panel);
Font f = new Font("Arial",Font.BOLD,25);
Font f1 = new Font("Arial",Font.BOLD,20);
JLabel lable = new JLabel();
lable.setBounds(130,10,400,100);
lable.setText("Apple Inc. Member Login Port");
lable.setFont(f);
panel.add(lable);
JTextField login = new JTextField("Login",10);
login.setBounds(120,150,400,30);
login.setFont(f1);
panel.add(login);
JPasswordField pass =new JPasswordField("Password");
pass.setBounds(120,200,400,30);
pass.setFont(f1);
lable.setFont(f);
panel.add(pass);
c.setVisible(true);
this.setVisible(true);
}
public static void main(String[] argm)
{
Myframec frame = new Myframec();
frame.setVisible(true);
}
}

Aligning JButton

I have to align a button on my program to the exact middle, the current code I have runs it but displays the button as large as the program, I am wanting a center button that is a specific size, here is what I tried
/**
* Created by Timk9 on 11/04/2016.
*/
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
{
JFrame window = new JFrame("Test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(true);
window.setSize(600, 600);
window.setVisible(true);
window.setLocationRelativeTo(null);
JPanel p = new JPanel(new GridBagLayout());
//Button does not appear until I resize the program?
JButton b1 = new JButton("Click here");
GridBagConstraints c = new GridBagConstraints();
p.add(b1);
window.add(p);
}
public static void main(String[] args) {
new Test();
}
}
JPanel p = new JPanel(new GridBagLayout());
You create a panel with a GridBagLayout which is a good layout manager to use to center the component.
p.add(b1);
But then you add the button to the panel without using any contraints.
The code should be:
p.add(b1, c);
//Button does not appear until I resize the program?
All components should be added to the frame BEFORE the frame is made visible. The setVisible(...) statement should be the last statement of the constructor.
Also could you point out which part is an instance initializer block, I thought I was using a constructor
See the FrameDemo example from the Swing tutorial on How to Make Frames for a better way to structure your code so you follow Swing conventions. Start with the working code and make the changes to add your panel containing the button, instead of using the JLabel. Note you no longer need to use the getContentPane() method, you can just add the panel directly to the frame.
It is the LayoutManager that defines how components are layed out where and how big. GridLayout which you are using e. g. divides the available space in equal grid fields and makes the components completely fill this space which is why your button is as big as your application. See here for more info about LayoutManagers: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Btw. your code is not compilable: new JButton("he"),JButton.ALIGN_CENTER)

How to reset or refresh Jframe with new values

I have a Jframe that the user enters new information through a Joptionpane, it is added to an array which is then appended and displayed to a contentpane.. the cycle then repeats till the user enters "STOP". Currently the program is outputting the new array under the old one. How would I clear away the old array in the content pane and only display the new values?
import java.awt.*;
import java.util.LinkedList;
import java.util.List;
public class Project1GUI {
static JFrame Frame;
static TextArea unsorted_words, sorted_words, linked_words;
public Project1GUI(String title){
//All this does is make an empty GUI FRAME.
Frame=new JFrame();//i made a new variable from the JFrame class
Frame.setSize(400,400);//Used the Variable from JFrame and used some of it functions. This function sets the hieght and width of the Frame
Frame.setLocation(200,200);//This sets where the Empty Frame should be
Frame.setTitle(title);//This puts a title up top of the Frame
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//places an x box that closes when clicked on
Frame.setVisible(true);//This activates the JFram when is set true.
Frame.setLayout(new GridLayout(1,2));//This sets the layout of the Frame and since i want a Grid i used a GirdLayout
//Functions and placed it inside the setlayout functions. to get 2 grids i places 1 meaning 1 row and 2 for 2 cols
unsorted_words=new TextArea(); //From the TextArea class i made three variables
sorted_words= new TextArea();
linked_words= new TextArea();
Container panel=new Container();
panel=Frame.getContentPane();
panel.add(unsorted_words);
panel.add(sorted_words);
panel.add(linked_words);
}
public void add_unsorted(String words){
unsorted_words.append(words+"\n");//add words to GUI
}
public void add_sorted(String words){
sorted_words.append(words+"\n");
}
public void add_linked(List<String> linked_words2){
linked_words.append(linked_words2+"\n");
}
}
For a more definitive answer, post an MCVE
Seeing as you haven't posted any code, I'm guessing you are using a JLabel or a JList or something of that sort to display the array. No matter which one you are doing, you need to tell the component to update it's content, it doesn't just do it itself. To do that, you need to call the components .setText() or similar method.
If you have a JLabel or JTextArea it could look like this.
labelOrTextArea.setText("New Text");
If you are using a JList you should update the lists Default List Model like this
dlm.addElement("New Text");
UPDATE
I see a couple things wrong with your code. First off JFrame Frame = new JFrame conventionally, variables should start with a lower case letter and they should not contain underscores '_'. You are also using AWT Components instead of Swing components. You should be using the likes of JTextArea, JPanel (Theres no JContainer), JLabel etc.
You are also never adding the panel to the frame.
frame.add(panel);
You should also not be adding stuff to the frame or panels after you set its visibility to true. So you should setup your frame like this
import javax.swing.*;
import java.awt.*;
import java.util.List;
public class Project1GUI
{
JTextArea unsorted_words, sorted_words, linked_words;
public Project1GUI()
{
JFrame frame = new JFrame("Title");
JPanel panel = new JPanel(new GridLayout(2, 1));
unsorted_words = new JTextArea();
sorted_words = new JTextArea();
linked_words = new JTextArea();
panel.add(unsorted_words);
panel.add(sorted_words);
panel.add(linked_words);
frame.add(panel);
frame.setSize(400,400);
frame.setLocation(200,200);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You can then implement the methods you currently have and call them in an ActionListener or such.
Result:
On top of all of that, you should not rely on the use of static as it takes away from the main points of OOP.

JFrame Image wont appear, require refresh? [duplicate]

I'm fairly new to JFrame and I want to know why my items are not showing up on the window. I know i dont have a ActionHandler but I just want my textfield's to show up on my window. Here's my code:
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class FirstGUI extends JFrame{
public void GUI(){
setTitle("Welcome");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(600,600);
JLabel title = new JLabel();
title.setText("Apple Inc. Member Login Port");
title.setFont(new Font("Arial", Font.PLAIN, 24));
JTextField login = new JTextField("Login",10);
JPasswordField pass = new JPasswordField("Password");
add(title);
add(login);
add(pass);
}
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
}
}
but when i run it i get this:
but when i run it i get this:
You get an empty screen because you add the components to the frame after the frame is visible.
As has already been suggested you need to use an appropriate layout manager. FlowLayout is the easiest to start with.
invoke setVisible(true) AFTER adding the components to the frame.
So the code should be more like:
panel.add(...);
panel.add(...);
add(panel);
pack();
setVisible(true);
I agree to MadProgrammer's suggestions (+1)
Well, lets take a look at your program though
You actually have created a JFrame with components in it. Its working fine as well, but your question of "why are my items not showing up in the JFrame" is not because you did something wrong but because missed out something i.e. revalidate()
Try:
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
a.revalidate();
}
I'm not saying this will give you perfect UI.. what I'm trying to say is this will help you understand the Swing better. Learn about Swing Layout managers and then work on your UI to have better results
revalidate(): This component and all parents above it are marked as needing to be laid out. This means the Layout Manager will try to realign the components. Often used after removing components. It is possible that some really sharp swing people may miss this. I would think that you will only know this if you are actually using Swing.
The default layout manager for JFrame is BorderLayout.
This means that your components are essentially all been added ontop of each other.
Try changing the layout manager to something like FlowLayout (for example)...
Take a look at A Visual Guide to Layout Managers and Using Layout Managers for more details.
Also, avoid setSize where possible, use Window#pack instead
Update
I'd also like to introduce you to Initial Threads which should be used to launch your UI code...
The only one reason :
setVisible(True); method for the frame should be put on the end of the code.
if you give this line on the top of the code that is when you create a frame. This will cause that problem.
Don't add the components directly to your frame. Instead add to the content pane, which is where a JFrame stores all of the components that it draws. Usually this is a JPanel.
Here is an example:
public class GUI
{
private JPanel content;
public void GUI
{
/*Other code*/
content = new JPanel();
add(content); //make content the content pane
content.add(title);
content.add(login);
content.add(pass);
}
If that fails, call setVisible(true) and setEnabled(true) on all of your components.
On a side note you may want to make your GUI function a constructor.
import javax.swing.*;
import java.awt.*;
class Myframec extends JFrame
{
Myframec()
{
Container c = this.getContentPane();
c.setLayout(null);
this.setBounds(10,10,700,500);
this.setTitle("Welcome");
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBounds(0,0,700,500);
panel.setBackground(Color.gray);
panel.setLayout(null);
c.add(panel);
Font f = new Font("Arial",Font.BOLD,25);
Font f1 = new Font("Arial",Font.BOLD,20);
JLabel lable = new JLabel();
lable.setBounds(130,10,400,100);
lable.setText("Apple Inc. Member Login Port");
lable.setFont(f);
panel.add(lable);
JTextField login = new JTextField("Login",10);
login.setBounds(120,150,400,30);
login.setFont(f1);
panel.add(login);
JPasswordField pass =new JPasswordField("Password");
pass.setBounds(120,200,400,30);
pass.setFont(f1);
lable.setFont(f);
panel.add(pass);
c.setVisible(true);
this.setVisible(true);
}
public static void main(String[] argm)
{
Myframec frame = new Myframec();
frame.setVisible(true);
}
}

Categories

Resources