Hi, I'm new in Java programming... I'd like to set a Component exactly in center of panel... it should be both horizontally and vertically... I've looked for it and I've found nothing... can you give me any advice please? Thnx
Printable View
Hi, I'm new in Java programming... I'd like to set a Component exactly in center of panel... it should be both horizontally and vertically... I've looked for it and I've found nothing... can you give me any advice please? Thnx
Code:MyPanel.add( component, BorderLayout.CENTER );
Or if you want the component centered, but you don't want it to expand out to fill the container (as BorderLayout will try to do), you can use a GridBagLayout and just add the component (if it's the only thing being added to that container).
e.g.,
Code:JLabel centerLabel = new JLabel("Centered");
centerLabel.setBorder(new LineBorder(Color.black));
JPanel panel = new JPanel(new GridBagLayout());
panel.add(centerLabel);
Or if you want to see this in a small program:
Code:import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class CenterComponent {
private static void createAndShowUI() {
JLabel centerLabel = new JLabel("Centered");
centerLabel.setBorder(new LineBorder(Color.black));
JPanel panel = new JPanel(new GridBagLayout());
panel.setPreferredSize(new Dimension(500, 500));
panel.add(centerLabel);
JFrame frame = new JFrame("CenterComponent");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Thank you... this one I've never tried... I've tried only basic layout managers (BorderLayout, BoxLayout, FlowLayout and GridLayout)... I'll learn GridBagLayout too, it could be useful ;-)... thnx