网格布局--计算器

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

public class Calculator {
 public static void main(String[] args) {
  JFrame frame = new CalculatorFrame();
  frame.show();
 }
}

class CalculatorFrame extends JFrame
{
 public CalculatorFrame()
 {
  setTitle("Calculator");
  setSize(200,200);
  Container contentPane = getContentPane();
  contentPane.add(new CalculatorPanel());
 }
}

class CalculatorPanel extends JPanel
{
 public CalculatorPanel()
 {
  setLayout(new BorderLayout());
  JPanel p = new JPanel();
  p.setLayout(new GridLayout(4,4));
  String buttons = "789/456*123-0.=+";
  
  for(int i = 0; i < buttons.length(); i++)
  {
   addButton(p, buttons.substring(i, i+1));
  }
  add(p, "Center");
 }
 
 public void addButton(Container c, String s)
 {
  JButton b = new JButton(s);
  c.add(b);
 }
 
}

你可能感兴趣的:(Java)