Why i cant move(locate) the button - java

i try to locate my buttons in frame to center, or, if to be honest, make my layout more flexible. But when i set properties like as .setBounds, my buttons have no reaction. Why? Thx for any help!
import com.sun.beans.editors.ColorEditor;
import javax.swing.*;
import java.awt.*;
public class windowsInterface extends JFrame{
windowsInterface(){
super("When the nearest HB");
setSize(800, 800);
JPanel panelForAddDel = new JPanel();
panelForAddDel.setSize(800, 100);
panelForAddDel.setLocation(0, 0);
panelForAddDel.setBackground(Color.gray);
JTextField nameOfStaff = new JTextField();
JTextField dateOfBirth = new JTextField();
JButton addRec = new JButton("Добавить");
addRec.setBounds(100, 100, 200, 50);
JButton delRec = new JButton("Удалить");
delRec.setBounds(100, 100, 200, 50);
addRec.setBounds(320, 125, 200, 50);
delRec.setBounds(420, 125, 200, 50);
JPanel panelForWatch = new JPanel();
panelForWatch.setLocation(0, 100);
panelForWatch.setSize(800, 600);
panelForWatch.setBackground(Color.BLUE);
add(panelForAddDel);
add(panelForWatch);
panelForAddDel.add(nameOfStaff);
panelForAddDel.add(dateOfBirth);
panelForAddDel.add(addRec);
panelForAddDel.add(delRec);
}
}

But when i set properties like as .setBounds, my buttons have no reaction. Why?
Because there is a default layout in the Java Components. For instance, JFrame uses a default BorderLayout manager which determines how your added components within the JFrame will position and overrules your setBounds() methods, hence giving you the impression that it isn't working.
You will realise that if you remove this layout by setting it to null this.setLayout(null), setBounds() will seem to function again.
However, it is recommended that you choose an appropriate layout based on your needs instead of using null layout.
I would recommend you to add your components to a JPanel and add the JPanel to the JFrame instead of adding directly into the JFrame.
Set an appropriate layout for your JPanel
If needed, you can use nested JPanels with each having different layout to meet your needs.

This might be because the default layout for panel is flow layout. Read about it
http://www.javatpoint.com/FlowLayout. A more flexible layout is GridBagLayout you can change the layout of panels or JFrames to your choice.
To learn about GridBagLayout: https://www.tutorialspoint.com/swing/swing_gridbaglayout.htm

Related

why the last GUI element i declare is filling the whole panel?

public class add extends JPanel {
private JPanel add = new JPanel();
JFrame frame;
public add(){
frame = new JFrame("Add");
frame.setBounds(550, 300, 700,500);
frame.setVisible(true);
JLabel nameLabel = new JLabel("Name");
final JTextField nameField = new JTextField();
frame.add(nameLabel);
frame.add(nameField);
nameLabel.setBounds(200, 40, 150, 30);
nameField.setBounds(350, 40, 150, 30);
...
JButton registerButton = new JButton("Salveaza");
frame.add(registerButton);
registerButton.setBounds(200,300,300, 30);
registerButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
}
}
and if i delete the JButton, than a label, which would be the last element, will fill the whole JPanel when i run the programm.
what can i do so i can make it work properly?
You're adding components to a container, the JFrame's contentPane, that uses a BorderLayout as its default layout manager. When you do this and don't specify constants, the component gets added BorderLayout.CENTER, covering up any components added before.
Good Solution: learn and use layout managers, including using nested JPanels, each using its own layout manager and components.
Bad Solution: use null layout with absolute positioning. While to a newbie this seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.

How to use setBounds method for a JLabel?

I'm making a window application with Swing. I am using the setBounds() method for the JLabel spacing but it's not working.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FullScreenJFrame extends JFrame
{
public FullScreenJFrame( String title )
{
super(title);
//JFrame frame = new JFrame();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
getContentPane()
.add(new JLabel(" HIGHCOURT OF JUDICATURE AT ALLHAHABAD"), BorderLayout.NORTH);
JLabel label = new JLabel("JJ");
label.setBounds(20, 20, 150, 20);
// label.setText(s);
add(label);
}
public static void main( String[] args )
{
FullScreenJFrame frame = new FullScreenJFrame("");
//JFrame frame1 = new JFrame();
//JLabel label = new JLabel("dd");
//label.setBounds(370, 340, 150, 20);
//frame1.add(label);
frame.setVisible(true);
}
}
One advice, It seems you are going to show your application using all screen so try to avoid the use of absolute positions like setBoundMethod.
You should fit your application within a layout that uses other layouts within it. Check this link.
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Don't use setBounds() to resize a component. Use a Layout Manager and you won't be worried about manually doing this.
Why?
Why are going for absolute positioning, when Layout Managers do it for you.
One more thing, If your JFrame does not contain any title so there is no need to add empty title as it is bad practice.
Replace
FullScreenJFrame frame = new FullScreenJFrame("");
By
FullScreenJFrame frame = new FullScreenJFrame();
And
public FullScreenJFrame( String title )
By
public FullScreenJFrame()
No need to call
super(title);
Or in order to set your layout as null right click on your form and click set layout then click null layout.
Are null layouts recommended? As other have suggested, the answer is NO.
See Laying out Components in a Container to get some practice in with LayoutManagers
Will I still answer your question? Sure. Just so you know.
"I am using the setBounds() method for the JLabel spacing but it's not working. Please, can any one tell me why it is not working?"
Yes, your bounds aren't working because the JFrame has a default Borderlayout. In order for setBounds to work, the layout needs to be null.
setLayout(null);
Also, keep in mind that when you do use a null layout, any components in which you don't setBounds for will not appear.
See Laying out Components in a Container to get some practice in with LayoutManagers

Placing a JLabel at a specific x,y coordinate on a JPanel

I'm trying to place a series of JLabels at specific X and Y coordinates on a JPanel (and set its height and width, too). No matter what I do, each label winds up immediately to the right of the previous label and has the exact same size as all of the others.
Right now, my Jpanel is in a Grid Layout. I've tried Absolute Layout (illegal argument exception results), Free Design (no labels appear), Flow Layout (everything just gets squeezed to the center), and a few others.
Not sure what I need to do to make this work. Can anyone help? Thanks!
JLabel lbl1 = new JLabel("label 1");
JLabel lbl2 = new JLabel("label 2");
JLabel lbl3 = new JLabel("label 3");
JLabel lbl4 = new JLabel("label 4");
JLabel lbl5 = new JLabel("label 5");
myPanel.add(lbl1);
myPanel.add(lbl2);
myPanel.add(lbl3);
myPanel.add(lbl4);
myPanel.add(lbl5);
lbl1.setLocation(27, 20);
lbl2.setLocation(123, 20);
lbl3.setLocation(273, 20);
lbl4.setLocation(363, 20);
lbl5.setLocation(453, 20);
lbl1.setSize(86, 14);
lbl2.setSize(140, 14);
lbl3.setSize(80, 14);
lbl4.setSize(80, 14);
lbl5.setSize(130, 14);
You have to set your container's Layout to null:
myPanel.setLayout(null);
However is a good advise also to take a look at the Matisse Layout Manager, I guess it is called GroupLayout now. The main problem with absolute positioning is what happens when the window changes its size.
Set the container's layout manager to null by calling setLayout(null).
Call the Component class's setbounds method for each of the container's children.
Call the Component class's repaint method.
Note:
Creating containers with absolutely positioned containers can cause problems if the window containing the container is resized.
Refer this link:
http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
Layout managers are used to automatically determine the layout of components in a container. If you want to put components at specific coordinate locations, then you should not use a layout manager at all.
myPanel = new JPanel(null);
or
myPanel.setLayout(null);
My advise is to use an IDE like NetBeans with its GUI editor. To inspect the code and because there are many ways:
Setting the layout manager, or for absolute positioning doing a myPanel.setLayout(null), has several influences.
In general, assuming you do your calls in the constructor of a JFrame, you can call pack() to start the layouting.
Then, every layout manager uses its own implementation of add(Component) or add(Component, Constraint). BorderLayout's usage is with add(label, BorderLayout.CENTER) and so on.
// Best solution!!
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = (JPanel) frame.getContentPane();
panel.setLayout(null);
JLabel label = new JLabel("aaa");
panel.add(label);
Dimension size = label.getPreferredSize();
label.setBounds(100, 100, size.width, size.height);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
You can use your own method that calling by setSize, setLocation values for directly....! `
As well i show you how to use JProgress Bar
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class installComp{
void install(Component comp, int w, int h, int x, int y){
comp.setSize(w,h);
comp.setLocation(x,y);
}
}
class MyFrame extends JFrame{
int cur_val = 0;
JButton btn = new JButton("Mouse Over");
JProgressBar progress = new JProgressBar(0,100);
MyFrame (){
installComp comp=new installComp();
comp.install(btn,150,30,175,20);
comp.install(progress,400,20,50,70);
btn.addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent evt){
cur_val+=2;
progress.setValue(cur_val);
progress.setStringPainted(true);
progress.setString(null);
}
});
add(btn);
add(progress);
setLayout(null);
setSize(500,150);
setResizable(false);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
setVisible(true);
}
}
class Demo{
public static void main(String args[]){
MyFrame f1=new MyFrame();
}
}

Java Swing JFrame Layout

I just wrote a simple code where I want a textfield and a button to appear on the main frame, but after running all I see is the textfield.
If I write the code of the button after the textfield then only the button is displayed.
Any idea why?
JFrame mainframe=new JFrame();
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setBounds(0,0,200,200);
JButton jb=new JButton();
jb.setText("Leech");
mainframe.add(jb);
JTextField link=new JTextField(50);
mainframe.add(link);
mainframe.pack();
mainframe.setVisible(true);
The default layout on a JFrame is a BorderLayout. Calling the add method on a Container with such a layout is equivalent to a call add(..., BorderLayout.CENTER). Each of the locations of the BorderLayout can contain only one element. Hence making two calls
mainframe.add(jb);
mainframe.add(link);
results in a CENTER containing the last component you added. If you want to avoid this you can either add it to different locations, or use another layout manager (for example a FlowLayout) by calling JFrame#setLayout
Instead of adding directly Components to the JFrame, use a JPanel as container with the desired LayoutManager.
Here you can find several tutorials on layout managers.
Basically in Swing the LayoutManager is responsible for laying out the children Components (establishing their position and their size), so every container component you use inside your app, should be configured with the appropiate LayoutManager.
Add your components to a JPanel and then add that panel to the ContentPane of JFrame.
JFrame window = new JFrame();
JPanel mainframe = new JPanel();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(0,0,200,200);
JButton jb = new JButton();
jb.setText("Leech");
mainframe.add(jb);
JTextField link = new JTextField(50);
mainframe.add(link);
window.getContentPane().add(mainframe);
window.pack();
window.setVisible(true);
You can also use something like Flow Layout which is the default layout used by JPanel. It is used to arrange components in a line or a row. For example from left to right or from right to left:
Flow layout arranges components in line and if no space left all remaining components goes to next line. Align property determines alignment of the components as left, right, center etc.
To use it you will need to set JFrame layout by using JFrame.setLayout(layout) and to pass flow layout as a parameter.
Following example shows components arranged in flow layout:
package example.com;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FlowLayoutExample {
FlowLayoutExample(){
JFrame frame = new JFrame("Flow Layout");
JButton button, button1, button2, button3, button4;
button = new JButton("button 1");
button1 = new JButton("button 2");
button2 = new JButton("button 3");
button3 = new JButton("button 4");
button4 = new JButton("button 5");
frame.add(button);
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.setLayout(new FlowLayout());
frame.setSize(300,300);
frame.setVisible(true);
}
public static void main(String[] args) {
new FlowLayoutExample();
}
}
Check out to learn more about JFrame layouts.
JFrame's default Layout Manager is BorderLayout. If you want the automatic layout, you may use the FlowLayout:
mainframe.setLayout(new FlowLayout());
If you want to specify coordinates by setBounds() method, you have to cancel the setting of layout manager on JFrame:
mainframe.setLayout(null);
jb.setBounds(10,10,100,50);
link.setBounds(10,70,180,100);
if you see BorderLayout Documentation
mainframe.add(jb); is equals to mainframe.add(jb,BorderLayout.CENTER);
mainframe.add(link); is equals to mainframe.add(jb,BorderLayout.CENTER);
so it just show the last one

Java Swing - JLabel Location

I have problem while setting the Jlabel location.
I set the content pane to some JPanel, I created and tried to add my JLabel.
JLabel mainTitle = new JLabel("SomeApp");
mainTitle.setFont(new Font("Arial",2 , 28));
mainTitle.setBounds(0,0, 115, 130);
getContentPane().add(mainTitle);
I want that my JPanel will be on the top left corner on my application and what I am getting is "SomeApp" on the top center.(and not top left).
btw I tried to add JButton the and the I can`t change the width,height,x,y of the JButton.
Swing uses Layout Managers to place the components.
You have to understand how they work to use them effectively. You can set the layout manager to null, and do the layout your self, but is not recommendable because you'll have to keep track of new components each time, and perform layout computation your self when the window moves shrink etc.
Layout managers are a bit hard to grasp at first.
Your windows could be like this:
Using this code:
import javax.swing.*;
import java.awt.Font;
import java.awt.FlowLayout;
class JLabelLocation {
public static void main( String [] args ) {
JLabel mainTitle = new JLabel("SomeApp");
mainTitle.setFont(new Font("Arial",2 , 28));
//mainTitle.setBounds(0,0, 115, 130); //let the layout do the work
JFrame frame = new JFrame();
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));// places at the left
panel.add( mainTitle );
frame.add( panel );// no need to call getContentPane
frame.pack();
frame.setVisible( true );
}
}
Where a particular widget ends up in its container depends on the layout manager that it's using. The layout manager determines how to resize and arrange the widgets to make them fit appropriately. Obviously, the default layout for the content pane decided that the top center was the best place to put the JLabel.
If you want to get to not use a layout manager and just place everything yourself (which generally isn't the best way to lay things out btw), then add:
getContentPane().setLayout(null);
Using layouts is usually a better idea since they allow for dynamic resizing of components. Here's how you'd do it with a BorderLayout:
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add (new JLabel ("Main title"), BorderLayout.NORTH);
If you want to add something to the right of the label you could create an additionnal panel with it's own layout :
// Create a panel at the top for the title and anything else you might need
JPanel titlePanel = new JPanel (new BorderLayout());
titlePanel.add(new JLabel ("Main title"), BorderLayout.WEST);
// Add the title panel to the frame
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(titlePanel, BorderLayout.CENTER);
Here are some usefull links to get started with layouts:
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/visual.html
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/using.html

Categories

Resources