我正在尝试使用 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();}
}
它仍然无法正常工作:(