没有组件出现在JFrame GUI上

时间:2015-09-24 22:24:00

标签: java swing jframe jpanel

我对Swing和GUI相当新,到目前为止,只会出现窗口,但没有任何组件可见。我该怎么办?可见性有问题还是容器有问题?

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

public class PhoneCaller 
{
  JButton button1;
  JButton button2;
  JButton button3;
  JButton button4;
  JButton button5;
  JButton button6;
  JButton button7;
  JButton button8;
  JButton button9;
  JButton buttonDash;
  JButton button0;
  JButton dialButton;

  String phoneNum = "";

  public static void main (String[] args)
   {
    new PhoneCaller();
    }

  public PhoneCaller()
  {
    JFrame myFrame = new JFrame();
    myFrame.setTitle("Dialer");
    myFrame.setSize(200, 250);
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    JPanel myPanel = new JPanel(new BorderLayout(10,10));
    myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));
    myFrame.add(myPanel);


    JPanel myPanel2 = new JPanel();
    myPanel2.setLayout(new FlowLayout());
    JLabel lab = new JLabel("Enter the number to dial");
    myPanel2.add(lab);

    JPanel myPanel3 = new JPanel();
    myPanel3.setLayout(new GridLayout(4,3,5,5));
    button1 = new JButton ("1");
    myPanel3.add(button1);
    button2 = new JButton ("2");
    myPanel3.add(button2);
    button3 = new JButton ("3");
    myPanel3.add(button3);
    button4 = new JButton ("4");
    button5 = new JButton ("5");
    button6 = new JButton ("6");
    button7 = new JButton ("7");
    button8 = new JButton ("8");
    button9 = new JButton ("9");
    button0 = new JButton ("0");
    buttonDash = new JButton ("-");

    myPanel3.add(button4);
    myPanel3.add(button5);
    myPanel3.add(button6);
    myPanel3.add(button7);
    myPanel3.add(button8);
    myPanel3.add(button9);
    myPanel3.add(button0);
    myPanel3.add(buttonDash);

    myFrame.setVisible(true);
  }
}

2 个答案:

答案 0 :(得分:2)

我想您忘记在myPanel2内添加myPanel3myPanel

myPanel.add(myPanel2);
myPanel.add(myPanel3);

答案 1 :(得分:0)

您忘记将myPanel2myPanel3添加到您的JFrame,将以下代码段添加到代码的末尾

myFrame.add(myPanel2);
myFrame.add(myPanel3);