2015-12-23 2 views
1

Я пытаюсь добиться чего-то like thisОдин столбец 3 строки в центре JPanel

enter image description here

Проблема здесь, что я не знаю, как к центру «один столбец» разного объекты. Уже пробовали с GridLayout и BorderLayout, но не могли бы центрировать эти элементы.

Если есть кто-то, кто мог бы помочь, я был бы благодарен.

+0

у вас есть какой-то код? Я бы серьезно подумал о границе. Север, Ют и центр. Это должно делать свое дело. –

ответ

1

Вы можете дать BoxLayout попытку - см. Например: A Visual Guide to Layout Managers. Более подробную информацию о том, как использовать этот менеджер макетов, можно найти здесь: How to Use BoxLayout.

При добавлении компонента к панели с компоновкой коробки, вы можете установить выравнивание так:

component.setAlignmentX(Component.CENTER_ALIGNMENT); 

Полный пример:

import java.awt.*; 
import javax.swing.*; 
import javax.swing.border.*; 

public class BoxLayoutExample { 
    public static void main(String[] arguments) { 
     SwingUtilities.invokeLater(() -> new BoxLayoutExample().createAndShowGui()); 
    } 

    private void createAndShowGui() { 
     JFrame frame = new JFrame("Stack Overflow"); 
     frame.setBounds(100, 100, 800, 600); 
     frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

     JPanel panel = new JPanel(); 
     panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); 
     panel.setBorder(new EmptyBorder(28, 28, 28, 28)); 

     JLabel label = new JLabel("Some longer text here......"); 
     panel.add(label); 
     label.setAlignmentX(Component.CENTER_ALIGNMENT); 

     panel.add(Box.createRigidArea(new Dimension(0, 42))); 

     String text = "image (can be done with \"new ImageIcon(\"image path\")\")"; 
     JLabel image = new JLabel(text); 
     panel.add(image); 
     image.setAlignmentX(Component.CENTER_ALIGNMENT); 

     panel.add(Box.createRigidArea(new Dimension(0, 42))); 

     JButton button = new JButton("a button"); 
     panel.add(button); 
     button.setAlignmentX(Component.CENTER_ALIGNMENT); 

     frame.getContentPane().add(panel); 
     frame.setVisible(true); 
    } 
}