I’m trying to create a custom timer that will record cumulative time passage separated by days. I have a custom JPanel that does all of the timer work for me. I would like to have a GUI interace with this JPanel represented 7 times. However, when I add more than one custom JPanel to either a JPanel or a JFrame, they don’t show up. I’ve tried setting the layout and setting them to everything I can think of, but nothing works.
This is the basic setup of the Panel:
public class TimerPane extends JPanel{
private static JButton button = new JButton("Start");
private static JLabel label = new JLabel("Time elapsed:");
private static JLabel tLabel = new JLabel("0:0:0");
private static JLabel title = new JLabel("Timer");
public TimerPane(){
button.addActionListener(new ButtonListener());
this.add(title);
this.add(label);
this.add(tLabel);
this.add(button);
this.setOpaque(false);
this.setPreferredSize(new Dimension(100,100));
this.setMaximumSize(new Dimension(100,100));
}
}
This is my latest attempt at getting the JPanel to display multiple times (just twice here):
public static void main(String[] args){
JFrame frame = new JFrame("Timer");
JPanel panel = new JPanel();
frame.setPreferredSize(new Dimension(700,110));
panel.setLayout(new BorderLayout());
panel.add(new TimerPane(), BorderLayout.EAST);
panel.add(new TimerPane(), BorderLayout.WEST);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
The GUI that executes after this is 700×110 of which only 100×100 on the far left is used for exactly one of my TimerPane panels. I have also tried GridLayout on the same code, but then only the TimerPane in the second “spot” shows up. Any suggestions?
First of all, please remove the
staticfrom the member variables:button,label,tLabelandtitle. Otherwise, having themstatic, it means they are shared by all theTimerPaneinstances.You will see 2 timer panels now.
Next, you can change the
BorderLayoutto aFlowLayoutfor instance and add several instances ofTimerPane.