gpt4 book ai didi

java - JFrame 组件未出现

转载 作者:行者123 更新时间:2023-12-01 23:17:46 26 4
gpt4 key购买 nike

我对 Java 很陌生,我正在尝试制作一个简单的时间计算器。

为什么 add() 方法只抛出我最后添加的内容?当我运行该程序时,它只显示“天”而不是文本框和年份标签。

import javax.swing.*;

public class TimeCalculator extends JFrame

{

public static void main(String[] args)
{
JOptionPaneMultiInput window = new JOptionPaneMultiInput();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300,500);
window.setVisible(true);
}

public TimeCalculator()
{
super("Time Calculator");

JTextField yearsField = new JTextField(5);
JTextField daysField = new JTextField(5);
JTextField hoursField = new JTextField(5);
JTextField minutesField = new JTextField(5);
JTextField secondsField = new JTextField(5);

JLabel yearsLabel = new JLabel();
JLabel daysLabel = new JLabel();
JLabel hoursLabel = new JLabel();
JLabel minutesLabel = new JLabel();
JLabel secondsLabel = new JLabel();

JCheckBox yearsCheckbox = new JCheckBox();
JCheckBox daysCheckbox = new JCheckBox();
JCheckBox hoursCheckbox = new JCheckBox();
JCheckBox minutesCheckbox = new JCheckBox();
JCheckBox secondsCheckbox = new JCheckBox();

JLabel yearsCLabel = new JLabel();
JLabel daysCLabel = new JLabel();
JLabel hoursCLabel = new JLabel();
JLabel minutesCLabel = new JLabel();
JLabel secondsCLabel = new JLabel();

JButton convertButton = new JButton();

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

yearsLabel.setText("Years");
daysLabel.setText("Days");
hoursLabel.setText("Hours");
minutesLabel.setText("Minutes");
secondsLabel.setText("Seconds");

yearsCLabel.setText("Yr");
daysCLabel.setText("D");
hoursCLabel.setText("Hr");
minutesCLabel.setText("Min");
secondsCLabel.setText("Sec");

convertButton.setText("Convert");
convertButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
//doConvert(evt); this will be added later once i figure everything out
}
});


add(yearsField);
add(yearsLabel);
add(daysField);
add(daysLabel);
}
}

最佳答案

main() 中提到的

JOptionPaneMultiInput 不是发布的源代码的一部分。考虑发布SSCCE

答案:

When I run the program it only shows "Days" instead of the textboxes and the years label.

问题中出现的

TimeCalculator 扩展了 JFrame。默认情况下,JFrame 使用BorderLayout 布局。当使用 BorderLayout 时,不带约束参数的 add() 方法会导致 BorderLayout.CENTER 约束添加组件。因此,您将对象添加到 BorderLayout 的中心。每个后续的 add() 都会替换先前添加的组件。最后,只剩下daysLabel

参见How to Use BorderLayout更多细节。另请参阅A Visual Guide to Layout Managers对于其他布局管理器,因为框架中有许多控件,如果没有额外的嵌套面板,很难对其进行布局。

关于java - JFrame 组件未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20960622/

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