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();
}
}
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'
JFrame
, just use an instance of one. JButton timerLabel
is a confusing name, it should be JButton timerButton
this.setTitle("Timer Test");
could be written super("Timer Test");
or if using a standard (not extended) frame .. JFrame frame = new JFrame("Timer Test");
this.setSize(150,150);
That size is just a guess. It would better be this.pack();
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.public static void main(String[] args) { new TimerTest(); }
Swing & AWT based GUIs should be created & updated on the EDT.