gpt4 book ai didi

java - 添加到 JFrame 时自定义 JPanel 对象重叠

转载 作者:行者123 更新时间:2023-11-30 11:41:09 25 4
gpt4 key购买 nike

我正在尝试创建一个自定义计时器,它将记录以天为单位的累积时间流逝。我有一个自定义 JPanel,它可以为我完成所有计时器工作。我想有一个 GUI 界面与这个 JPanel 代表 7 次。但是,当我向 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:buttonlabeltLabel标题。否则,让它们为 static,这意味着它们由所有 TimerPane 实例共享。您现在将看到 2 个计时器面板。

接下来,您可以将 BorderLayout 更改为 FlowLayout 并添加多个 TimerPane 实例。

panel.setLayout(new FlowLayout(FlowLayout.LEFT));

panel.add(new TimerPane());
panel.add(new TimerPane());

关于java - 添加到 JFrame 时自定义 JPanel 对象重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12375973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com