添加JTextField后空白JPanel

时间:2013-11-20 01:02:52

标签: java swing jpanel jtextfield

为我的简单掷骰子模拟程序添加GUI。

制作了一个新的JPanel,并使用默认文本值为其添加了一些JTextField。我得到没有错误,代码运行,但我得到的只是一个空白窗口,里面没有任何内容。

以下是代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class CrapsGUI extends JFrame
{
   JPanel jp = new JPanel();
   JLabel jl = new JLabel();
   JTextField die1 = new JTextField("Die 1",30);
   JTextField die2 = new JTextField("Die 2",30);
   JTextField sum = new JTextField("Sum",30);
   JTextField point = new JTextField("Point",30);
   JTextField status = new JTextField("Status",30);

   public CrapsGUI()
   {
      setTitle("Craps Simulator 2013");
      setVisible(true);
      setSize(400, 200);
      setDefaultCloseOperation(EXIT_ON_CLOSE);

      jp.add(die1);
      jp.add(die2);
      jp.add(sum);
      jp.add(point);
      jp.add(status);
   }

   public static void main(String[] args)
   {
      Craps craps = new Craps();

      CrapsGUI crapsGUI = new CrapsGUI();
   }
}

提前致谢!

3 个答案:

答案 0 :(得分:1)

您尚未添加包含可见组件的JPanel

add(jp);

答案 1 :(得分:0)

有三件事情浮现在脑海中

  1. 确保从Event Dispatching Thread的上下文中启动UI。有关详细信息,请参阅Initial Threads
  2. 仅在完成创建UI后调用setVisible
  3. 如果您向框架中添加了某些内容,也会有所帮助。尝试使用add(jp)

答案 2 :(得分:0)

try this one:

public static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("Sample Frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // first text box
    JPanel textbox1Panel = new JPanel();
    textbox1Panel.setLayout(new BoxLayout(textbox1Panel, 0));
    textbox1Panel.setOpaque(true);
    textbox1Panel.setBackground(new Color(100, 0, 131));
    textbox1Panel.setPreferredSize(new Dimension(300, 300));
    textbox1Panel.add(die1);
    textbox1Panel.add(die2);
    textbox1Panel.add(sum);
    textbox1Panel.add(point);

    // Set the menu bar and add the label to the content pane.

    frame.getContentPane().add(textbox1Panel, BorderLayout.SOUTH);

    // Display the window.
    frame.pack();
    frame.setVisible(true);
}