[英]Custom JPanel objects overlap when added to JFrame
我正在嘗試創建一個自定義計時器,該計時器將記錄以天為單位的累積時間流逝。 我有一個自定義的JPanel,可以為我完成所有計時器工作。 我想用這個JPanel進行7次GUI交互。 但是,當我向一個JPanel或JFrame中添加多個自定義JPanel時,它們不會顯示。 我嘗試設置布局並將其設置為我能想到的所有內容,但沒有任何效果。
這是面板的基本設置:
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));
}
}
這是我最近一次嘗試使JPanel顯示多次(這里只是兩次)的嘗試:
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);
}
此后執行的GUI為700x110,其中最左邊的100x100僅用於我的TimerPane面板之一。 我也在相同的代碼上嘗試了GridLayout,但隨后僅在第二個“位置”中顯示了TimerPane。 有什么建議么?
首先,請從成員變量中刪除static
變量: button
, label
, tLabel
和title
。 否則,將它們設置為static
,意味着它們被所有TimerPane
實例共享。 您現在將看到2個計時器面板。
接下來,您可以將BorderLayout
更改為FlowLayout
,並添加幾個TimerPane
實例。
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(new TimerPane());
panel.add(new TimerPane());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.