Layouts Issue on Different Components? - java

I'm writing a gui program in which use flow layout to set components.I know this layout start from default center and goes left to right like this
I also know structure of all other layouts but i want to make a gui like this
All components in center.But layout use in that picture is null.I only want to know about how can we do that in these type of layout like border,flow etc.
Code :
public class Main {
public static void main(String[] args) {
JFrame obj = new JFrame();
obj.setTitle("My Frame");
obj.setSize(800, 600);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setLocationRelativeTo(null);
JLabel l1 = new JLabel("Enter Name");
l1.setFont(new Font("Tahoma", Font.PLAIN, 21));
JTextField t1 = new JTextField(20);
t1.setFont(new Font("Tahoma", Font.PLAIN, 16));
JButton b1 = new JButton("Submit");
obj.setLayout(new FlowLayout());
obj.add(l1);
obj.add(t1);
obj.add(b1);
obj.setVisible(true);
}
}

You could use a BoxLayout. Something like:
box.add(label);
box.add(textField);
box.add(button);
box.add(Box.createVerticalGlue());
You may have to play with the setAlignmentX(...) property to allow the components to be centered horizontally.
Read the section from the Swing tutorial on How to Use BoxLayout for more information and examples.
Or you could use a GridBagLayout. The tutorial also has a section on How to Use GridBagLayout.

Related

How set JLabel at center of JDialog on X? [duplicate]

I'm using the NetBeans GUI builder to handle my layout (I'm terrible with LayoutManagers) and am trying to place a simple JLabel so that it is always centered (horizontally) inside its parent JPanel. Ideally, this would maintain true even if the JPanel was resized, but if that's a crazy amount of coding than it is sufficient to just be centered when the JPanel is first created.
I'm bad enough trying to handle layouts myself, but since the NetBeans GUI Builder autogenerates immutable code, it's been impossible for me to figure out how to do this centering, and I haven't been able to find anything online to help me.
Thanks to anybody who can steer me in the right direction!
Here are four ways to center a component:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class CenterComponent {
public static JLabel getLabel(String text) {
return getLabel(text, SwingConstants.LEFT);
}
public static JLabel getLabel(String text, int alignment) {
JLabel l = new JLabel(text, alignment);
l.setBorder(new LineBorder(Color.RED, 2));
return l;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel p = new JPanel(new GridLayout(2,2,4,4));
p.setBackground(Color.black);
p.setBorder(new EmptyBorder(4,4,4,4));
JPanel border = new JPanel(new BorderLayout());
border.add(getLabel(
"Border", SwingConstants.CENTER), BorderLayout.CENTER);
p.add(border);
JPanel gridbag = new JPanel(new GridBagLayout());
gridbag.add(getLabel("GridBag"));
p.add(gridbag);
JPanel grid = new JPanel(new GridLayout());
grid.add(getLabel("Grid", SwingConstants.CENTER));
p.add(grid);
// from #0verbose
JPanel box = new JPanel();
box.setLayout(new BoxLayout(box, BoxLayout.X_AXIS ));
box.add(Box.createHorizontalGlue());
box.add(getLabel("Box"));
box.add(Box.createHorizontalGlue());
p.add(box);
JFrame f = new JFrame("Streeeetch me..");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
By using Borderlayout, you can put any of JComponents to the CENTER area. For an example, see an answer to Stack Overflow question Get rid of the gap between JPanels. This should work.
Even with BoxLayout you can achieve that:
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS ));
JLabel label = new JLabel();
listPane.add(Box.createHorizontalGlue());
listPane.add(label);
listPane.add(Box.createHorizontalGlue());
mKorbel's solution is perfect for your goal. Anyway I always like to suggest BoxLayout because it's very flexible.
Mara: "thanks for your response, however the NetBeans GUI Build uses GroupLayout and this is not overridable."
Not true! Right click anywhere inside JFrame (or any other GUI container) in NetBeans GUI builder and select "Set Layout". By default is selected "Free Design", which is Group layout, but you can select any other layout including Border layout as advised by mKorbel.
There's many ways to do this, depending on the layout manager(s) you use. I suggest you read the Laying Out Components Within a Container tutorial.
I believe the following will work, regardless of layout manager:
JLabel.setHorizontalAlignment(SwingConstants.CENTER)

How to change the size of the JButton?

Here is my code. The button is the same size as the FlowLayout. How can I make the button smaller?
public class javalearning extends JFrame{{
FlowLayout f = new FlowLayout();
this.setSize(600,600);
JFrame j = new JFrame();
this.setTitle("this is a tittle");
JButton button = new JButton();
button.setText("Button");
this.add(button);
button.setBounds(10, 10, 10, 10);
this.setVisible(true);
}
}
I think you forget to setLayout, it works fine when I do. Don't use setBounds and put it in a javalearning constructor and I also suggest you setDefaultCloseOperation like
public javalearning() {
FlowLayout f = new FlowLayout();
this.setLayout(f);
this.setSize(600, 600);
this.setTitle("this is a tittle");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton();
button.setText("Button");
this.add(button);
// button.setBounds(10, 10, 10, 10);
this.setVisible(true);
}
public static void main(String[] args) {
javalearning m = new javalearning();
}
Finally, by convention, Java class names start with a capital letter and are camel case. Something like JavaLearning would follow that convention.
You never set the layout manager (FlowLayout) to the frame, therefore the JFrame is still using it's default layout manager of BorderLayout...
Try using something more like...
FlowLayout f = new FlowLayout();
setLayout(f);
this.setTitle("this is a tittle");
JButton button = new JButton();
button.setText("Button");
this.add(button);
this.pack();
this.setVisible(true);
instead...
Take a closer look at Laying Out Components Within a Container for more details
FlowLayout will lay out Components left-to-right (or right-to-left) wrapping them if required. If you wish to explicitly set the size of each JButton you should use setPreferredSize rather than setSize or setBounds as layout managers typically make use of the minimum, preferred and maximum sizes when performing a layout.
button.setBounds(x, y, height, width);
you can give height and width less than 10!
also you can use GridLayout for smaller buttons in one button with for loop

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.

Layout inside Layout

I have a JPanel with a vertical BoxLayout, for one element i want to be able to use another BoxLayout which places elements horisontally.
The code will explain what i'm trying to do:
private void prepareGUI() {
setBorder(new EmptyBorder(20, 0, 20, 0));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JLabel lblTitle = new JLabel("Downloading");
lblTitle.setFont(new Font("Arial", Font.PLAIN, 20));
lblTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
add(lblTitle);
Component verticalStrut = Box.createVerticalStrut(20);
add(verticalStrut);
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setBorder(null);
progressBar.setValue(50);
Dimension size = new Dimension(300, 25);
progressBar.setMinimumSize(size);
progressBar.setMaximumSize(size);
progressBar.setPreferredSize(size);
add(progressBar);
BoxLayout textLayout = new BoxLayout(this, BoxLayout.Y_AXIS);
JLabel lblTest_1 = new JLabel("Test 1!");
textLayout.add(lblTest_1);
JLabel lblTest_2 = new JLabel("Test 2!");
textLayout.add(lblTest_2);
add(textLayout);
}
Now obviously this isn't possible as BoxLayout isn't a Container (It even asks for the container to be linked to on construction.
My question is what is the best way to achieve what i want? Should i create another JPanel and put that inside the first JPanel? I was thinking that but it seems a little too complicated, there must be a simpler way?
BoxLayout is not a container, it's a LayoutManager, so, components can't be added to BoxLayout since box layout is not inheriting anything from abstract class Component, it's will add to some container like JPanel or frame's container....
So, it's wrong to say:
textLayout.add(lblTest_1);
Or even
add(textLayout);
Because this method addes a component to the frame's container, and BoxLayout is not a component.
Should i create another JPanel and put that inside the first JPanel?
Except what you did and avoiding null layout, you're free to do anything, as, design is upon to you, as far as I am preferring multiple panels if wanted.

Having trouble re-sizing JButton in Java

Whenever I add my jbutton to my container it's really huge. I thought using the label.setBounds() function would work but it didn't
public Liability_Calculator(String s)
{
super(s);
setSize(325,200);
Color customColor = Color.WHITE;
c = getContentPane();
c.setLayout(new BorderLayout());
//the button
ok = new JButton("OK");
//ok.setSize(50, 50);
//HERE IS WHERE I TRY AND RESIZE!
ok.setBounds(30,30,50,50);
c.add(ok, BorderLayout.SOUTH);
setVisible(true);
}
Suggestions:
You will want to read up on the layout managers to
understand why your GUI is behaving this way
and to see how to use the layout managers to your advantage to create better looking GUI's in an easy way.
You'll also want to avoid setting bounds on any gui components.
For instance, a JPanel uses FlowLayout(FlowLayout.CENTER)) by default, and you can use that to your advantage by placing your ok JButton into a JPanel and then the JPanel into the contentPane:
ok = new JButton("OK");
// ok.setBounds(30, 30, 50, 50);
JPanel southPanel = new JPanel();
southPanel.add(ok);
c.add(southPanel, BorderLayout.SOUTH);
This will change the first image to the second:

Categories

Resources