日期:2014-05-20  浏览次数:20572 次

求高手赐教,我的java程序到底哪里出错了!?
import java.awt.*;


public class frame extends Frame
{
public frame()
{
super("娱乐版计算机--潘深练");
TextField txt = new TextField();
GridBagConstraints gridBag = new GridBagConstraints(); // 实例化一个约束对象
  gridBag.fill = GridBagConstraints.HORIZONTAL; // 以水平填充方式布局
gridBag.weightx = 100; // 行自适应缩放
gridBag.weighty = 0; // 列高不变
addToBag(txt,gridBag,0,0,1,1);
gridBag.weightx = 100; // 行自适应缩放
gridBag.weighty = 100; // 列自适应缩放

Panel operate = new Panel();
operate.setLayout(new GridLayout(6,3,15,15));
operate.add(new Button("Clear"));
operate.add(new Button("+"));
operate.add(new Button("0"));
operate.add(new Button("1"));
operate.add(new Button("2"));
operate.add(new Button("3"));
operate.add(new Button("-"));
operate.add(new Button("*"));
operate.add(new Button("."));
operate.add(new Button("4"));
operate.add(new Button("5"));
operate.add(new Button("6"));
  operate.add(new Button("/"));
  operate.add(new Button("%"));
  operate.add(new Button("="));
  operate.add(new Button("7"));
  operate.add(new Button("8"));
  operate.add(new Button("9"));
  add(operate);

pack();
setVisible(true);
}


/***********************将一个部件按指定大小加入到 GridBagLayout 布局的指定位置***********************/
void addToBag(Component c ,GridBagConstraints gbc , int x , int y ,int h , int w)
{
gbc.gridx = x;
gbc.gridy = y;
gbc.gridheight = h;
gbc.gridwidth = w;
add(c,gbc); // 按指定约束加入部件
}






/**********************************************主程序**********************************************/
  public static void main(String args[])
  {
  new frame();
  }
}

------解决方案--------------------
一堆警告,可以加个try和catch块检查一下,我把代码修改过后,能运行,只是一个界面
改动的有三点:1,class frame extends JFrame
2, public static void main(String[] args)
{
frame f = new frame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
这就是为什么类frame要继承JFrame的原因
3.void addToBag(Component c ,GridBagConstraints gbc , int x , int y ,int h , int w)
{
gbc.gridx = x;
gbc.gridy = y;
gbc.gridheight = h;
gbc.gridwidth = w;

Panel o = new Panel();
o.add(c,gbc); // 按指定约束加入部件
}
addToBag函数不能只写个add(c,gbc),必须要有对象添加

源码:
[code=Java][/code]
import java.awt.*;

import javax.swing.JFrame;


public class frame extends JFrame
{
public frame()
{
super("娱乐版计算机--潘深练");
TextField txt = new TextField();
GridBagConstraints gridBag = new GridBagConstraints(); // 实例化一个约束对象
gridBag.fill = GridBagConstraints.HORIZONTAL; // 以水平填充方式布局
gridBag.weightx = 100; // 行自适应缩放
gridBag.weighty = 0; // 列高不变
addToBag(txt,gridBag,0,0,1,1);
gridBag.weightx = 100; // 行自适应缩放
gridBag.weighty = 100; // 列自适应缩放

Panel operate = new Panel();
operate.setLayout(new GridLayout(6,3,15,15));
operate.add(new Button("Clear"));
operate.add(new Button("+"));
operate.add(new Button("0"));
operate.add(new Button("1"));
operate.add(new Button("2"));
operate.add(new Button("3"));