我正在尝试使用Java创建一个Calculator应用程序。现在,我正在创建包含所有按钮和Panel的窗口,以显示单击的数字。 不知何故,我添加到框架的面板不会显示。任何人都可以帮助我。我在做什么错误?
package com.wells.eda;
import java.awt.*;
public class Calc {
public static void main(String[] args) {
Calculator c = new Calculator();
try{
Frame fm= c.NewFrame("Calculator",330,310);
c.NewButton(fm, "1",10,110);
c.NewButton(fm, "2",90,110);
c.NewButton(fm, "3",170,110);
c.NewButton(fm, "4",10,160);
c.NewButton(fm, "5",90,160);
c.NewButton(fm, "6",170,160);
c.NewButton(fm, "7",10,210);
c.NewButton(fm, "8",90,210);
c.NewButton(fm, "9",170,210);
c.NewButton(fm, "00",10,260);
c.NewButton(fm, "0",90,260);
c.NewButton(fm, "Reserved",170,260);
c.NewButton(fm, "+",250,110);
c.NewButton(fm, "-",250,160);
c.NewButton(fm, "*",250,210);
c.NewButton(fm, "/",250,260);
c.NewPanel(fm);
//Thread.sleep(3000);
//fm.dispose();
}
catch(Exception e)
{
System.out.println("Exception happened");
}
}
}
class Calculator{
public Frame NewFrame(String name,int length, int width)
{
Frame fm = new Frame(name);
fm.setLayout(null);
fm.setResizable(false);
fm.setSize(length,width);
fm.setVisible(true);
return(fm);
}
public void NewButton(Frame fm,String number,int xcordinate,int ycordinate) throws Exception
{
Button b = new Button (number);
b.setBounds(xcordinate,ycordinate,70,40);
//b.setVisible(true);
fm.add(b);
}
public void NewPanel(Frame fm)
{
Panel p= new Panel(null);
fm.add(p);
//p.setSize(100, 100);
p.setBounds(10,10,250,100);
p.setName("Panel");
p.setVisible(true);
}
}
答案 0 :(得分:1)
您的面板未显示,因为它是空的,并且您没有设置可以使其可见的特定布局。
例如:fm.setLayout(null); ==> fm.setLayout(new BorderLayout());
public void NewPanel(Frame fm)
{
Panel p= new Panel(null);
fm.add(p);
//p.setSize(100, 100);
p.setBounds(10,10,250,100);
p.setName("Panel");
p.setVisible(true);
}
试试这个:
public void NewPanel(Frame fm)
{
Panel p= new Panel(null);
fm.add(p);
//p.setSize(100, 100);
p.setBounds(10,10,250,100);
p.setName("Panel");
p.add(new JLabel("Test"));
p.setVisible(true);
}
您将看到您的Panel围绕创建的JLabel