javaswingjframelayout-managerborder-layout

How do I put a class instance at north of border layout?


I wrote a simple Timer class, and I want to set the frame layout to Border layout and put timer at north. I'm new to layouts, can anyone help me with how to do this?

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

public class TimerTest extends JFrame{
    JButton timerLabel = null;
    public TimerTest()
    {
        this.setTitle("Timer Test");
        Container c = this.getContentPane();
        c.setLayout(new FlowLayout());
        timerLabel = new JButton("0");
        timerLabel.setEnabled(false);
        c.add(timerLabel);
        this.setSize(150,150);
        this.setVisible(true);
        int k = 100;
        while(true)
        {

            timerLabel.setText(k+" seconds left");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            k--;
        }
    }

    public static void main(String[] args) {
        new TimerTest();
    }
}

Solution

  • Container c = this.getContentPane(); // has border layout by DEFAULT
    c.setLayout(new FlowLayout()); // but now it has flow layout!
    // ..
    c.add(timerLabel);
    

    So change that to:

    Container c = this.getContentPane(); // has border layout by DEFAULT
    // ..
    c.add(timerLabel, BorderLayout.PAGE_START); // PAGE_START is AKA 'NORTH'
    

    Other tips:

    1. Don't extend JFrame, just use an instance of one.
    2. JButton timerLabel is a confusing name, it should be JButton timerButton
    3. this.setTitle("Timer Test"); could be written super("Timer Test"); or if using a standard (not extended) frame .. JFrame frame = new JFrame("Timer Test");
    4. this.setSize(150,150); That size is just a guess. It would better be this.pack();
    5. while(true) .. Thread.sleep(1000); Don't block the EDT (Event Dispatch Thread). The GUI will 'freeze' when that happens. See Concurrency in Swing for details and the fix.
    6. public static void main(String[] args) { new TimerTest(); } Swing & AWT based GUIs should be created & updated on the EDT.