How to put a JButton at a specific location? - java

I know that there are already very similar questions to my question on stackoverflow, but neither one of them answers my question.
I want to put my JButton on a specific location on my JFrame in JAVA. Here is my Code:
public class DetectMotion extends JFrame {
private JLabel label = null;
public DetectMotionExample() {
JPanel pnlButton = new JPanel();
label = new JLabel(nothing);
JButton btn = new JButton("Close");
pnlButton.setLayout(new BorderLayout());
setTitle("Motion Detector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Close")) {
//TO-DO
}
}
});
WebcamPanel panel = new WebcamPanel(webcam);
add(panel);
pnlButton.add(btn,BorderLayout.SOUTH);
pnlButton.add(label,BorderLayout.NORTH);
add(pnlButton);
pack();
setVisible(true);
}
}
I have a panel on my JFrame (webcamPanel) and a JPanel called pnlButton that includes the JButton (btn) and JLabel (label).
Now, how can I specifically change the location of my button instead of just using BorderLayout.NORTH?
Thanks!

Make use of appropriate layout managers to achieve your goals...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DetectMotion extends JFrame {
private JLabel label = null;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DetectMotion frame = new DetectMotion();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public DetectMotion() {
JPanel pnlButton = new JPanel();
label = new JLabel("nothing");
JButton btn = new JButton("Close");
pnlButton.setLayout(new GridBagLayout());
setTitle("Motion Detector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Close")) {
//TO-DO
}
}
});
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
panel.setBackground(Color.RED);
add(panel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weighty = 1;
pnlButton.add(label, gbc);
gbc.weighty = 0;
pnlButton.add(btn, gbc);
add(pnlButton, BorderLayout.EAST);
pack();
setVisible(true);
}
}
package javaapplication647;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DetectMotion extends JFrame {
private JLabel label = null;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DetectMotion frame = new DetectMotion();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public DetectMotion() {
JPanel pnlButton = new JPanel();
label = new JLabel("nothing");
JButton btn = new JButton("Close");
pnlButton.setLayout(new FlowLayout(FlowLayout.RIGHT));
setTitle("Motion Detector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Close")) {
//TO-DO
}
}
});
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
panel.setBackground(Color.RED);
add(panel);
pnlButton.add(label);
pnlButton.add(btn);
add(pnlButton, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}
Take a look at Laying Out Components Within a Container for more ideas

If you want to put the item into a specific coordinate you have to use null Layout:
Example:
public void newClass(){
public newClass(){
JPanel panel = new JPanel();
JButton button = new JButton("button1");
panel.setLayout(null);
button.setBounds(x,y,X,Y);
panel.add(button);
}
public static void main(String[] args){
newClass();
}
}
Doing Without a Layout Manager (Absolute Positioning)

Your best bet is to use a Java Drag-and-Drop GUI builder like NetBeans. Particularly if you're interested in very specific positioning, nothing really beats a GUI builder.

Related

Can't add JPanel to BorderLayout.CENTER

I am just Starting out with JAVA.
I have say a JPanel x, a JPanel y and a BorderLayout JPanel z.
When I try to change the contents of the center of z from default x t y, it works but it doesn't go back to x. I AM calling revalidate() after each. Help please.
The class below is where the problem is.
Main Class Below
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.LayoutManager;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
#SuppressWarnings({ "serial", "unused" })
public class Manager extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Manager frame = new Manager();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Manager() {
setTitle("Popper");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
height = height/5.1;
setSize((int)width, (int)height);
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(0,0,0,0));
setContentPane(contentPane);
contentPane.setBackground(new Color(14,99,165));
contentPane.setLayout(new BorderLayout(0, 0));
ImageIcon image = new ImageIcon("D:/popper26.png");
setIconImage(image.getImage());
JPanel pane = new JPanel();
calcu cal = new calcu();
curr nup = new curr();
stopc newst = new stopc();
pane.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel mainpanel = new JPanel();
BorderLayout x =new BorderLayout(0,0);
mainpanel.setLayout(x);
mainpanel.setBackground(Color.WHITE);
JLabel madeby = new JLabel("Project By Anant Bhasin");
madeby.setHorizontalAlignment(SwingConstants.RIGHT);
mainpanel.add(madeby, BorderLayout.SOUTH);
JPanel logo = new JPanel();
logo.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel jk = new JLabel(new ImageIcon("D:/popper2.png"));
logo.add(jk, BorderLayout.NORTH);
logo.setBackground(Color.decode("#1abc9c"));
mainpanel.add(logo, BorderLayout.NORTH);
mainpanel.add(cal, BorderLayout.CENTER);
contentPane.add(mainpanel, BorderLayout.CENTER);
JPanel newj = new JPanel();
BoxLayout bxl = new BoxLayout(newj, BoxLayout.PAGE_AXIS);
newj.setLayout(bxl);
newj.setBackground(new Color(58,115,144));
contentPane.add(newj, BorderLayout.WEST);
Border emptyBorder = BorderFactory.createEmptyBorder();
JButton calc = new JButton(new ImageIcon("D:/calc.png"));
newj.add(calc);
calc.setBorder(emptyBorder);
calc.setFocusPainted(false);
calc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mainpanel.add(BorderLayout.CENTER, cal);
mainpanel.revalidate();
}
});
JButton currb = new JButton(new ImageIcon("D:/curr.png"));
currb.setBorder(emptyBorder);
newj.add(currb);
currb.setFocusPainted(false);
currb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mainpanel.add(BorderLayout.CENTER, nup);
mainpanel.revalidate();
}
});
JButton stop = new JButton(new ImageIcon("D:/stop.png"));
stop.setBorder(emptyBorder);
newj.add(stop);
stop.setFocusPainted(false);
stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mainpanel.add(BorderLayout.CENTER, newst);
mainpanel.revalidate();
}
});
JButton timer = new JButton(new ImageIcon("D:/timer.png"));
timer.setBorder(emptyBorder);
newj.add(timer);
timer.setFocusPainted(false);
JButton memo = new JButton(new ImageIcon("D:/memo.png"));
memo.setBorder(emptyBorder);
newj.add(memo);
memo.setFocusPainted(false);
}
}
A BorderLayout is not designed to display multiple components with the same constraint because of the way ZOrder painting works in Swing.
If you need the ability to swap panels, then you should be using a CardLayout.
A CardLayout lets you specify the name of the panel that you want to display. Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
You set up the layout with code like:
JPanel main = new JPanel( new CardLayout() );
main.add(panelx, "X");
main.add(panely, "Y");
Then to swap a panel you use code like:
CardLayout cl = (CardLayout)(main.getLayout());
cl.show(main, "X");

How to make a border around Jbutton thicker?

I have the following JButton on the GUI interface I'm building.
I want to make the border around the button more thicker so it will stand out from the background. Is it possible to do this in Java?
You could simply use a LineBorder
JButton btn = ...;
btn.setBorder(BorderFactory.createLineBorder(Color.BLACK, 4));
Take a look at How to Use Borders for more details and ideas
Updating the border state based on the model state
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
protected static final Border NORMAL_BORDER = BorderFactory.createLineBorder(Color.BLACK, 4);
protected static final Border ROLLOVER_BORDER = BorderFactory.createLineBorder(Color.RED, 4);
public TestPane() {
JButton btn = new JButton("Click me!");
btn.setContentAreaFilled(false);
btn.setBorder(NORMAL_BORDER);
btn.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (btn.getModel().isRollover()) {
btn.setBorder(ROLLOVER_BORDER);
} else {
btn.setBorder(NORMAL_BORDER);
}
}
});
setLayout(new GridBagLayout());
add(btn);
}
}
}
Create a Border first -
Border border = new LineBorder(Color.WHITE, 13);
Then create a JButton and set the Border -
JButton button = new JButton("Button Name");
button.setBorder(border);
Hope it will Help.
Thanks a lot.

How to add JComponent into a JFrame with size and location specified?

I am trying to code in a way that when user clicks a button, a new row of jlabel and jtextfield will be added to the the gridlayout of the jframe. like this:
Let's say the JFrame is 800x600, and the height of each row is 50, after I reach the 13th line, I want to add in a vertical scrolling bar. But now I can't seem to add the components correctly as I wished, I have also tried other layouts and apparently not working out.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
public class Testing extends JFrame implements ActionListener
{
public static int x =0;
JPanel panel;
public Testing()
{
super("Add component on JFrame at runtime");
setLayout(new BorderLayout());
panel=new JPanel();
panel.setPreferredSize(new Dimension(800,600));
panel.setAutoscrolls(true);
panel.setLayout(new GridLayout(0,2,0,20));
add(panel,BorderLayout.CENTER);
JButton button=new JButton("CLICK HERE");
add(button,BorderLayout.SOUTH);
button.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent evt)
{
JLabel jlbl1 = new JLabel("Row"+x);
JTextField jtf =new JTextField(10);
jtf.setMaximumSize(new Dimension(400,50));
jlbl1.setMaximumSize(new Dimension(400,50));
panel.add(jlbl1);
panel.add(jtf);
panel.revalidate();
x++;
validate();
}
public static void main(String[]args)
{
Testing test=new Testing();
}
}
Edit: Thanks and Props to MadProgrammer for showing guidelines, this is what I wanted, just in case someone else face the same problem as I did:
Thanks to MadProgrammer and Andrew Thompson for showing guidelines. After some tweaks, this is what I wanted.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TableExample {
public static void main(String[] args) {
new TableExample();
}
public TableExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public GridBagConstraints c = new GridBagConstraints();
private JPanel fieldsPanel;
private int row;
public TestPane() {
c.gridx =0;
c.gridy =0;
c.fill = GridBagConstraints.NONE;
setLayout(new BorderLayout());
fieldsPanel = new JPanel(new GridBagLayout());
add(new JScrollPane(fieldsPanel));
JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fieldsPanel.add(new JLabel("Row " + (++row)),c);
c.gridx++;
fieldsPanel.add(new JTextField(10),c);
fieldsPanel.revalidate();
c.gridy++;
c.gridx--;
}
});
add(btn, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Use a JTable instead and/or
Use a JScrollPane and allow it to take care of it for you...
Update with JTable example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TableExample {
public static void main(String[] args) {
new TableExample();
}
public TableExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private DefaultTableModel model;
public TestPane() {
setLayout(new BorderLayout());
model = new DefaultTableModel(
new Object[]{"Row", "Value"},
0);
JTable table = new JTable(model);
add(new JScrollPane(table));
JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int count = model.getRowCount();
model.addRow(new Object[]{count + 1, ""});
}
});
add(btn, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Updated with JScrollPane example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TableExample {
public static void main(String[] args) {
new TableExample();
}
public TableExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel fieldsPanel;
private int row;
public TestPane() {
setLayout(new BorderLayout());
fieldsPanel = new JPanel(new GridLayout(0, 2));
add(new JScrollPane(fieldsPanel));
JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fieldsPanel.add(new JLabel("Row " + (++row)));
fieldsPanel.add(new JTextField(10));
fieldsPanel.revalidate();
}
});
add(btn, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Updated with GridBagLayout example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TableExample {
public static void main(String[] args) {
new TableExample();
}
public TableExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel fieldsPanel;
private JPanel filler;
private int row;
public TestPane() {
setLayout(new BorderLayout());
filler = new JPanel();
fieldsPanel = new JPanel(new GridBagLayout());
add(new JScrollPane(fieldsPanel));
JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fieldsPanel.remove(filler);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 0;
gbc.gridy = row;
gbc.fill = GridBagConstraints.HORIZONTAL;
fieldsPanel.add(new JLabel("Row " + (++row)), gbc);
gbc.gridx++;
gbc.weightx = 1;
fieldsPanel.add(new JTextField(10), gbc);
gbc.gridy++;
gbc.weighty = 1;
fieldsPanel.add(filler, gbc);
fieldsPanel.revalidate();
}
});
add(btn, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}

Incorrect JPanel position in GridBagLayout

im using GridBag to display some JPanels with images inside a JScrollPane.
When there are 3 or more images the GridBagConstraints work ok but when i have 1 or 2, they get aligned to the center of the JScrollPane instead of being in their position in the top (like in a gallery)
Here is my code:
JPanel jPanel1 = new JPanel();
GridBagLayout layout = new GridBagLayout();
jPanel1.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
JPanel photo = new JPanel();
Dimension d = new Dimension(100,100);
photo.setPreferredSize(d);
gbc.insets = new Insets(0,3,3,3);
gbc.gridx = i;
gbc.gridy = j;
jPanel1.add(photo, gbc);
jScrollPane1.setViewportView(jPanel1);
I have omitted the part where i assign an image to the photo Jpanel.
I want the JPanels to stay static in their places and do not align if there is free space.
If im not being clear i can upload a few snaps.
Thanks!
GridBagLayout layouts its components out around the center of the container, this is it's (and sometimes annoying) default functionality.
You could try adding an empty "filler" component (say a JLabel) with the GridBagConstraints of weightx=1 and weighty=1 at a position right of and below the other components in the container. This will force them to the top/left corner of the container...
Updated...
Centered/default...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GridBagLayoutTest {
public static void main(String[] args) {
new GridBagLayoutTest();
}
public GridBagLayoutTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
JLabel picture = new JLabel();
try {
picture.setIcon(new ImageIcon(ImageIO.read(new File("/path/to/your/picture"))));
} catch (IOException ex) {
ex.printStackTrace();
picture.setText("Bad picture");
}
add(picture, gbc);
}
}
}
Aligned...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GridBagLayoutTest {
public static void main(String[] args) {
new GridBagLayoutTest();
}
public GridBagLayoutTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
JLabel picture = new JLabel();
try {
picture.setIcon(new ImageIcon(ImageIO.read(new File("/path/to/your/picture"))));
} catch (IOException ex) {
ex.printStackTrace();
picture.setText("Bad picture");
}
add(picture, gbc);
JLabel filler = new JLabel();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
add(filler, gbc);
}
}
}

How to make the component to respect column and row Weights?

public class Tester {
public static class Frame extends JFrame {
public Frame() {
// Layout
GridBagLayout layout=new GridBagLayout();
layout.columnWeights=new double[] { 0.5, 0.5 };
layout.rowWeights=new double[] { 1 };
// Frame
setLayout(layout);
setSize(500,500);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Constraints
GridBagConstraints c=new GridBagConstraints();
c.fill=GridBagConstraints.BOTH;
// Panel 1
JPanel p1=new JPanel();
p1.setBackground(Color.green);
c.gridx=0;
c.gridy=0;
add(p1,c);
// Panel 2
JLabel l1=new JLabel("TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST" +
"TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST");
l1.setBackground(Color.yellow);
c.gridx=1;
c.gridy=0;
add(l1,c);
}
}
public static void main(String[] args) {
new Frame().setVisible(true);
}
}
In this case l1 takes whole space, I want it to take half, as this one says:
layout.columnWeights=new double[] { 0.5, 0.5 };
I put c.fill=GridBagConstraints.BOTH; because I want: if the frame get resized, i want also the component to be resized, but to take maximum 50% space.
You could add a "filler" component to the "empty" side...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout24 {
public static void main(String[] args) {
new TestLayout24();
}
public TestLayout24() {
EventQueue.invokeLater(
new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 0.5f;
gbc.weighty = 0.1f;
gbc.fill = GridBagConstraints.BOTH;
JPanel left = new JPanel();
left.setBackground(Color.RED);
JPanel right = new JPanel();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(left, gbc);
frame.add(right, gbc);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Or
You could use GridLayout instead...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout24 {
public static void main(String[] args) {
new TestLayout24();
}
public TestLayout24() {
EventQueue.invokeLater(
new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JPanel left = new JPanel();
left.setBackground(Color.RED);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 2));
frame.add(left);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I figure it out, setting this for the Label, it makes your life much easier!!!!
l1.setMinimumSize(new Dimension(0,0));
l1.setPreferredSize(new Dimension(0, 0));
Thanks for help...

Categories