gpt4 book ai didi

java - 无法在 JFrame 中显示面板

转载 作者:行者123 更新时间:2023-12-01 18:48:09 25 4
gpt4 key购买 nike

我正在尝试使用 Java 设计一个计算器外壳(非功能计算器),但由于某种原因我无法让程序显示我的按钮。我在这里做错了什么?

import java.awt.*;    
import javax.swing.*;
import java.awt.color.*;

public class Calculator extends JFrame {

public Calculator() {
JPanel P1 = new JPanel();
P1.setLayout(new GridLayout(4, 4));
//Panel Buttons
for (int i = 1; i <= 9; i++) {
P1.add(new JButton("" + i));
}
P1.add(new JButton("" + 0));
P1.add(new JButton("."));
P1.add(new JButton("*"));
P1.add(new JButton("/"));
P1.add(new JButton("+"));
P1.add(new JButton("-"));
P1.add(new JButton("="));
P1.setBackground(Color.cyan);
P1.setForeground(new Color(100, 1, 1));
//Content panel
JPanel P2 = new JPanel();
P2.setLayout(new BorderLayout());
P2.add(new JTextField("Hello world"), BorderLayout.NORTH);
P2.add(P1, BorderLayout.CENTER);
}


public static void main(String[] args) {
Calculator frame = new Calculator();
frame.setTitle("Simple Calculator");
frame.setSize(250, 250);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

}

好的,这就是我现在所拥有的......

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JFrame
{
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
Calculator()
{
super("Wk 3 Calculator"); setBounds(100,100,300,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
con.add(p1);
con.add(p2);
p1.setLayout(new GridLayout(4, 4));
//Panel Buttons
for (int i =1; i <=9; i++){
p1.add(new JButton ("" + i));
}
p1.add(new JButton (""+0));
p1.add(new JButton ("."));
p1.add(new JButton ("*"));
p1.add(new JButton ("/"));
p1.add(new JButton ("+"));
p1.add(new JButton ("-"));
p1.add(new JButton ("="));
//Content panel
p2.setLayout(new BorderLayout());
p2.add (new JTextField("Hello world"),BorderLayout.NORTH);
p2.add(p1, BorderLayout.CENTER);
//Frame specs
Calculator frame = new Calculator();
frame.setSize(250,250);
frame.setTitle("Simple Calculator");
frame.add(p1, BorderLayout.NORTH);
frame.add(p2, BorderLayout.SOUTH);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){new Calculator();}
}

它仍然无法工作:(

最佳答案

您没有向框架添加任何内容...

尝试一些类似的事情

add(P1, BorderLayout.NORTH);
add(P2, BorderLayout.SOUTH);

对于初学者...

您可能想看看

关于java - 无法在 JFrame 中显示面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16828606/

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