I can't understand why in the following code only the button is being displayed , and why aren't label and textfield displayed.
import javax.swing.*;
import java.awt.*;
class Invent extends JFrame
{
public Invent(){
JFrame c=new JFrame("trying");
JLabel label1;
JTextField txtfld1;
JButton buttoncomp;
label1=new JLabel("Enter the path");
txtfld1=new JTextField();
buttoncomp=new JButton("Update");
c.add(label1);
c.add(txtfld1);
c.add(buttoncomp);
c. pack();
c.setVisible(true);
}
public static void main(String[] args)
{
new Invent();
}
}
Kindly help ...
The default layout of a JFrame's content pane is BorderLayout. You're adding all of your components to the BorderLayout.CENTER location (by calling the single-argument add() function), which means that only the last component is added.
Either use a different layout manager, or add the components to different locations in the BorderLayout.
More info about BorderLayout can be found here.
Btw, your title has nothing to do with your actual question: the difference between a JFrame and a content pane is that a JFrame contains a content pane. The JFrame class passes calls like setLayout() and add() to its content pane.
It works incorrect(for you but java does what you say :) )
cause you add (these)three components to JFrame in row(the next remove the last)
you must work as follows:
label1.add(txtfld1);
label1.add(buttoncomp);
c.add(label1);
c.pack();
c.setVisible(true);
And something other...
You had made a new JFrame you dont need to extend it(in you class).
It's not good to add label(without panel) in HeavyWeight Component like JFrame you may have problems with Listeners(mouse,action,whatever...)
Let me know if that works for you...
Related
I tryed to learn about GUI and tryed to create the window with two buttons and jne Label on the screen. But I don't understand why I can't see these elements simultaneously. When I comment out lines for buttons I can see the Label element.
Here is my code:
import java.awt.*;
import javax.swing.*;
public class MyWin {
public static void main(String[] args) {
JFrame w = new JFrame("My Window");
w.setSize(1000,800);
w.setVisible(true);
JButton b = new JButton("My button");
b.setVisible(true);
b.setSize(150, 100);
b.setLocation(500, 20);
JButton b2 = new JButton("Second button");
b2.setVisible(true);
b2.setSize(150,100);
b2.setLocation(500, 600);
JLabel l = new JLabel("My label");
l.setVisible(true);
w.getContentPane().add(b);
w.getContentPane().add(b2);
w.getContentPane().add(l);
}
}
The default layout for the JFrame is BorderLayout and when you add your JLabel through single parameter add method you add it with a BorderLayour.CENTER constraint as a default, this causes to fill all the available space. So you might want to use layout manager suitable for your needs, then the components won't overlay themselves.
Visual Guide to Layour Managers
First of all, JFrame uses BorderLayout as a default layout and just adding the components (w.getContentPane().add(b)) sets them in BorderLayout.CENTER; where they occupy the whole JFrame to fill the empty space. Thus, is recommended to add components in a JPanel. So, you should create first a JPanel, add the components to the JPanel and finally add it to the JFrame.
The setSize(...); statement is not applied due to the default layout (FlowLayout) in JPanels and also is discouraged. (Because it won't work properly in different computers with different screen resolutions)
If you want to change the size of the components you should change the default layout and use instead a customLayout, borderLayout, gridLayout...
If you want to understand deeply how layouts work and all the available layouts in Java check this
I am making simple login screen. I added two JLabel's in JFrame in my program and it's running successfully but the problem is that when I run the program I got blank screen and empty jframe, however I have added two jlabel's in that frame but it's not showing me any thing and then if I minimize the window and after some time if I open that window again then I can see those components.
Here is my code:
package javaapplication41;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.*;
public class JavaApplication41 {
JavaApplication41()
{
JFrame cpec=new JFrame();
cpec.setBounds(300,200,600,350);
cpec.setUndecorated(false);
cpec.setVisible(true);
cpec.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel l = new JLabel(new ImageIcon("C:\\Users\\MUHAMMAD SHAHAB\\Documents\\NetBeansProjects\\Real Estate\\src\\real\\estate\\file (2).jpg"));
l.setBounds(100,100,200,125);
//l.setLayout(null);
cpec.add(l);
JLabel kiq=new JLabel(new ImageIcon("C:\\Users\\MUHAMMAD SHAHAB\\Documents\\NetBeansProjects\\Real Estate\\src\\real\\estate\\bla.jpg"));
kiq.setBounds(100,100,100,100);
//kiq.setLayout(null);
l.add(kiq);
}
public static void main(String[] args) {
JavaApplication41 ne=new JavaApplication41();
}
}
I am getting this output when I run program:
and when I minimize this window and again open this, then I am getting the desired output here it is:
what am I doing wrong?
You have to put cpec.setVisible(true); after adding all the items in your jframe.I hope this will surely solve your problem
You have set the visibility of JFrame at a very early stage. At that time the JLabel was not added. When you minimized and resized your frame, it got rendered again resulting in showing your added components.
Remember to add components before setting the Frame's visibility( set visibility at last).
Also I would suggest you to use GUI threads when working on swing components. Refer to swing utilities here : https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
Lastly set the layout of JFrame to null as you are trying to add labels to specific coordinates with setBounds() method.
Default layout of jframe is BorderLayout, so if you want you can change layout by reference of java.awt.Container abstract class.
It is initialized by getContentPane() of javax.swing.JFrame class.
The components are added only through reference of java.awt.Container class.
java.awt.Container c=cpec.getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT));
c.add(l); //label will get added to JFrame instance that is referenced
//then define size and at last define visibility
cpec.setSize(500, 500);
cpec.setVisible(true);
Set the Layout manager of the container as null. By default it uses BorderLayout as its Layout manager. You just have to call the getContentPane() method using the reference of the JFrame, which returns a container reference. Example:
Container c = frame.getContentPane();
c.setLayout(null);
For more information you can go through my Website.
I am very new and still have a lot to learn. Thank you so much for anyone who takes the time to help me with this. I have tried a variety of different methods to position my button at specific coordinates with the frame, but for some reason, none of the usual statements that work for placing JButtons is working. Any suggestions?
Here is my current working code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class GUI extends JFrame
{
JButton b1; // Declares Swing button variable and gives identifier (b1)
JButton b2; // Declares Swing label variable and gives identifier (l1)
public GUI()
{
setTitle("Virus Explortation");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Pictures\\matrix.gif")));
setLayout(new FlowLayout());
b1=new JButton("I am a button");
add(b1);
b2=new JButton("I am also a button");
add(b2);
setSize(399,399);
setSize(400,400);
}
public static void main(String args[])
{
new GUI();
}
}
Why can't I position the JButton using setLocation in this code?
It is because all the containers in Java swing has a default layout. You are adding the button directly into the JFrame where I see you using a BorderLayout for the frame. (BorderLayout is also the default layout for JFrame).
When a layout is used, the layout manager will decide on the position (and sometimes the dimension) for your added components. Which means your attempt of manually setting the position may become futile.
If you want to set the components' position to exactly where you want, you will have to set the layout of the container (such as JFrame or JPanel) to null:
JPanel pnlMain = new JPanel();
pnlMain.setLayout(null);
After you set it to null, you will have to set the location for every components you add to the container. If not, it won't show up. You may use the setBounds method to set the size and location:
JButton btn = new JButton();
btn.setBounds(x, y, width, height);
However, setting layout to null is not recommended for many reasons. One of the most prominent reason being that you loses control and predictability on how your UI will present on different Systems and different usage by the users.
It is also advisable not to extends from JFrame but rather extends from a container like JPanel. Then add the container to the frame. It is quite rare that you need to make a customized JFrame.
I am trying to insert a jpanel inside a jframe without using any netbeans drag/drop methods. The problem I encountered is when I give a specific color to Jpanel the same color adheres to entire JFrame. Please help me solve this.
This is my code:
package lookandfeel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.*;
public class LookandFeel {
public static void main(String[] args) {
JFrame window =new JFrame();
JPanel P1=new JPanel();
window.add(P1);
window.setExtendedState(window.MAXIMIZED_BOTH);
window.setResizable(false);
P1.setSize(300, 200);
// window.setLayout(new BorderLayout());
// window.add(P1, BorderLayout.CENTER);
for (Component comp:window.getContentPane().getComponents()) {
if (comp == P1) {
comp.setBackground(Color.DARK_GRAY);
}
else {
comp.setBackground(Color.red);
}
}
window.setUndecorated(true);
window.setVisible(true);
window.getContentPane().setBackground(Color.CYAN);
}
}
The P1 (btw it's better to name variables starting lowercase) fill entire content pane (because it's added to content pane and default layout is BorderLayout which tries to fill all available space).
So P1.setSize(300, 200); is futile
BorderLayouts attempt to fill all available space in the JFrame with the given components. Since you only have one single JPanel, that panel fills the entire space.
BorderLayout is the default layout for all JFrames, unless otherwise stated.
Click here to see a visual of different Layouts.
The above link will give you a visual representation of different layouts and how they operate. If you notice, the BorderLayout at the top of the page has absolutely no space left in the window - it's all being taken up by the buttons. The same thing is happening with your JPanel.
You can override the default layout with the method setLayout on your JFrame, such as:
window.setLayout(new GridLayout(0,2));
As stated before, variable naming conventions for Java should be in camelCase (or mixedCase), wherein the first word of the variable is lowercased and all other words capitalized.
my question is could be very basic in terms of understanding this simple code. I wrote this code myself grabbing bits of code from here and there to understand. I would like to actually follow this code line by line as to what each line means?
I have added my understanding as comments above the line of code, it could be wrong or some of them marked as **** means I just dont know what it means. If you could help me out here, it will be great.
Thanks
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.text.ParseException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TestingSwingComponents {
public TestingSwingComponents() {
//Create a frame which is the window that pops up
JFrame myframe = new JFrame();
//*****
myframe.getContentPane().setLayout(new BorderLayout());
//set the frame size to be 600 X 600 size
myframe.setSize(600, 600);
// create Pane1
JPanel myPanel = new JPanel();
//set the Layout component of Panel, as how you would like it to be
//here it is 2 rows and 15 columns
myPanel.setLayout(new GridLayout(2, 15));
//create a button with text in it
JButton letterButton = new JButton("click Me");
//add the created button component to the panel
myPanel.add(letterButton);
//******
myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
// create another panel
JPanel panelFormat = new JPanel();
//create a textfield
JTextField txtfield = new JTextField();
//create a label for the textfield
JLabel label = new JLabel("Guesss");
//set the layout type for this panel
panelFormat.setLayout(new BorderLayout());
//add label to panel
panelFormat.add(label);
//add textfield to panel
panelFormat.add(txtfield);
//I dont know the difference between the below two
//BorderLayout.CENTER still does not center the panel in the frame, I dont know why
myframe.getContentPane().add(panelFormat, BorderLayout.CENTER);
myframe.add(panelFormat);
// default settings
myframe.setTitle("Get buttons");
myframe.setVisible(true);
myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) throws ParseException {
new TestingSwingComponents();
}
}
myframe.getContentPane().setLayout(new BorderLayout());
To answer this, you need to understand the structure of a Swing window. A JFrame (in fact any Swing window) is made up a series of components which generate the view of the window.
(Picture from How to use Root Panes)
A JRootPane makes up the base of view, on-top of which is a JLayeredPane and what is know as the "glass pane". The JLayeredPane is responsible for managing the JMenuBar and the "content pane".
The content pane is where you components reside on the window.
So, what this line is saying is, "get the frame's content pane and set it's layout to use a BorderLayout"
The layouts API is an entire question on it's own and it would be use to you to have a read through Laying out components within a container for a more indeepth description, but basically, layout managers remove the need for you to care (a greate deal) about differences in rendering techniques employeed by different systems...
//******
myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
This comes back to the layout manager. Because you can have any number of layout managers, Swing allows you to pass a "constraint" to the layout manager when you add the component, giving the layout manager some idea of how you might like this component to be added.
If you take a closer look at BorderLayout you will see that it has five positions in which components can be added.
The line is basically saying, "please add myPanel to the SOUTH position within the frame/content pane"
Update from comments
If you have a look at this snippet...
panelFormat.setLayout(new BorderLayout());
//add label to panel
panelFormat.add(label);
//add textfield to panel
panelFormat.add(txtfield);
It sets the layout manager for panelFormat to BorderLayout. BorderLayout can only have a single component in any of it's five available positions. When you use add(Component) without passing it a layout constraint, BorderLayout use CENTER as the default position, this means you are trying to add two components to the CENTER position, this is not possible, so BorderLayout simply uses the last component that was added.
why not borderlayout fix the size of textfield instead of stretching
it all window
Because this is how BorderLayout works and no, GridLayout would probably do something simular.
You could try FlowLayout or GridBagLayout
Updated from comments
You seriously need to take the time to read through the linked (and other suggested) tutorials...but basically, you can use a GridBagLayout just like any other layout, you create an instance of it and apply it to the container...
// create another panel
JPanel panelFormat = new JPanel();
//create a textfield
JTextField txtfield = new JTextField(10);
//create a label for the textfield
JLabel label = new JLabel("Guesss");
//set the layout type for this panel
panelFormat.setLayout(new GridBagLayout());
//add label to panel
panelFormat.add(label);
//add textfield to panel
panelFormat.add(txtfield);
//I dont know the difference between the below two
//BorderLayout.CENTER still does not center the panel in the frame, I dont know why
myframe.getContentPane().add(panelFormat, BorderLayout.CENTER);
myframe.add(panelFormat);
A Swing top-level container, including a JFrame, JDialog is composed of several components all held together including a JRootPane which holds all together, a JLayeredPane, and a contentPane the latter of which holds most of the GUI excepting the top window bar. You can read more about the details in this tutorial here: Top Level Containers:
So when you add a component to a JFrame in a default way, you're actually adding it to its contentPane. In other words, this:
myJFrame.add(myComponent);
is functionally the same as this:
myJFrame.getContentPane().add(myComponent);
For learning Swing, I used this great tutorial which goes over everything you have, and explains it pretty clearly in depth.
The tutorial also goes over the elements that you are having trouble understanding.
Here is said tutorial.