在同一帧中使用2个面板

时间:2013-05-11 02:05:21

标签: java swing jbutton layout-manager

我想在同一帧中使用2个面板。但按钮不起作用?我怎么做?我想在一个面板上放几个按钮,其他面板会做一些其他的东西。

public class TestingPage extends JFrame {

    JFrame frame=new JFrame();
    JPanel panel01;
    JPanel panel02;
    JButton bttn1;


    /**
     * @param args
     */
    public TestingPage(){
        super("Test");
        setBounds(700,700,650,500);
        setVisible(true);
        setLayout(new BorderLayout());
        Container cont=frame.getContentPane();

        panel01=new JPanel();
        panel02=new JPanel();
        cont.add(panel01,BorderLayout.EAST);
        cont.add(panel02,BorderLayout.WEST);

    //setLayout(new BorderLayout());

    bttn1=new JButton("Button");
    bttn1.setBounds(77, 75, 100,26);
    add(bttn1);

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
      Runnable guiCreator= new Runnable(){
      @Override
      public void run  (){
          TestingPage page=new TestingPage();  
      }
     };
    javax.swing.SwingUtilities.invokeLater(guiCreator); 
    }
}

1 个答案:

答案 0 :(得分:3)

你有三个问题......

  • 您不是将按钮添加到任何面板,而是添加到框架本身
  • 在创建完UI之前,您正在调用setVisible。这是众所周知的常见问题。如果您需要在设置可见后向框架添加内容,则需要调用revalidate以确保更新布局
  • 您的课程已延伸JFrame,但您创建了另一个JFrame并使用其内容窗格添加您的组件,但让TestingPage可见......

enter image description here

import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestingPage extends JFrame {

//    JFrame frame = new JFrame();
    JPanel panel01;
    JPanel panel02;
    JButton bttn1;

    public TestingPage() {
        super("Test");
        setBounds(700, 700, 650, 500);
        setLayout(new BorderLayout());
        Container cont = getContentPane();

        panel01 = new JPanel();
        panel02 = new JPanel();
        cont.add(panel01, BorderLayout.EAST);
        cont.add(panel02, BorderLayout.WEST);

        //setLayout(new BorderLayout());

        bttn1 = new JButton("Button");
        panel01.add(bttn1);
        setVisible(true);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Runnable guiCreator = new Runnable() {
            @Override
            public void run() {
                TestingPage page = new TestingPage();
            }
        };
        javax.swing.SwingUtilities.invokeLater(guiCreator);
    }
}