除按钮外,我的GUI中没有显示任何内容?

时间:2016-03-23 18:21:44

标签: java

我正在尝试制作一个如下所示的GUI:

JLabel和JTextField并排在顶部, 中心的JLabel阵列, 两个按钮并排在底部

但是,只显示底部的按钮,BorderLayout的中心和北部区域完全空白。我已经环顾了类似的问题,但大多数似乎是他们忘了将组件添加到面板中,对我来说情况并非如此。有人可以帮帮我吗?

  import javax.swing.JFrame;
  public class Driver11
  {
  public static void main(String[] args)
  {
     JFrame frame = new JFrame("Unit4, Lab11: Decimal to Binary");
     frame.setLocation(100, 50);
     frame.setSize(400, 150);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.getContentPane().add(new Panel11());
     frame.setVisible(true);
  }
}

 public class Panel11 extends JPanel
 {
  private JTextField box;
  private JLabel label;
  private Display11 display;
  private JButton button2;
   public Panel11()
  {
     setLayout(new BorderLayout());

     JPanel panel = new JPanel(); 
     panel.setLayout(new GridLayout(1, 2));   
     add(panel, BorderLayout.NORTH); 

     label = new JLabel("Enter an integer from 0 to 255: ");
     label.setFont(new Font("Serif", Font.BOLD, 5)); 
     label.setHorizontalAlignment(SwingConstants.LEFT); 
     panel.add(label, BorderLayout.WEST); 

     box = new JTextField("", 5); 
     box.setHorizontalAlignment(SwingConstants.RIGHT);
     panel.add(box, BorderLayout.EAST); 

     display = new Display11();
     add(display, BorderLayout.CENTER); 

     JPanel south = new JPanel();
     south.setLayout(new FlowLayout());
     add(south, BorderLayout.SOUTH);
     JButton button1 = new JButton("Convert");
     button1.addActionListener(new Listener1());
     south.add(button1);
     button2 = new JButton("Step");
     button2.addActionListener(new Listener2());
     south.add(button2);
     button2.setEnabled(false);
     label = new JLabel("");
     south.add(label);
  }

1 个答案:

答案 0 :(得分:0)

要根据布局正确放置:BorderLayout仅适用于全局面板 - 其他内容具有不同的布局(当您制作它们时),因此不应随意使用NORTH / WEST / EAST。仅适用于适用的地方。

 public Panel11()
{
 setLayout(new BorderLayout());

 JPanel panel = new JPanel(); 
 panel.setLayout(new GridLayout(1, 2));   
 add(panel, BorderLayout.NORTH); 

 label = new JLabel("Enter an integer from 0 to 255: ");
 label.setFont(new Font("Serif", Font.BOLD, 5)); 
 label.setHorizontalAlignment(SwingConstants.LEFT); 
 panel.add(label);

 box = new JTextField("", 5); 
 box.setHorizontalAlignment(SwingConstants.RIGHT);
 panel.add(box); 

 display = new Display11();
 add(display, BorderLayout.CENTER); 

 JPanel south = new JPanel();
 south.setLayout(new FlowLayout());
 JButton button1 = new JButton("Convert");
 button1.addActionListener(new Listener1());
 south.add(button1);
 button2 = new JButton("Step");
 button2.addActionListener(new Listener2());
 south.add(button2);
 button2.setEnabled(false);
 label = new JLabel("");
 south.add(label);
 add(south, BorderLayout.SOUTH);
}