0

I have a very annoying problem. I am working with JAVA GUI and I am not that well equipped with Layout Managers however i know the basics. I have a code that supposedly should put a label component into its parent panel but it is not working as i tried BorderLayout.CENTER on adding. Can somebody help me guys. Here is the short code where I had the problem.

JPanel namePanel = new JPanel();    
            namePanel.setLayout(new BorderLayout());
            namePanel.setPreferredSize(new Dimension(420,45));
            namePanel.setBackground(Color.DARK_GRAY);
            namePanel.setBorder(border);
        JLabel nameLabel = new JLabel(taskName.get(i));
            nameLabel.setFont(new Font("Century Gothic", Font.BOLD, 18));
            nameLabel.setForeground(Color.WHITE);
            namePanel.add(nameLabel, BorderLayout.CENTER); 

Image: enter image description here

BoJack Horseman
  • 159
  • 5
  • 15
  • 1
    Possible duplicate of [Centering a JLabel in a JPanel](http://stackoverflow.com/questions/9829319/centering-a-jlabel-in-a-jpanel) – RubioRic May 05 '16 at 08:37
  • But i have no other componets inserted in the parent Panel sir – BoJack Horseman May 05 '16 at 08:40
  • 1
    Thank you for the link sir. Found an answer. I just changed my Layout into GridBagLayout instead of using Borderlayout. – BoJack Horseman May 05 '16 at 08:42
  • 1
    Change the `horizontalAlignment` of the label to be centered for [example](http://stackoverflow.com/questions/16957329/borderlayout-center-doesnt-center/16957552#16957552) and don't mess with the preferred size – MadProgrammer May 05 '16 at 08:46
  • @adrianquevada You're welcome. :-) – RubioRic May 05 '16 at 08:48
  • 1
    "i have no other componets inserted in the parent Panel sir" So you don't need to create a panel to set label align center. Just use nameLabel.setHorizontalAlignment(SwingConstants.CENTER); and add this label on parent of namePanel. – ziLk May 05 '16 at 09:29
  • @zilk Thank you. I think your suggestion is a better solution – BoJack Horseman May 05 '16 at 09:47

0 Answers0