为什么我的按钮没有出现在我的JPanel上 - Java

时间:2010-12-06 22:18:43

标签: java swing

或许我的JPanel根本没有出现。

我试图在屏幕底部有一个JPanel,它有几个按钮。有人能把我搞砸吗?

public class MyAWTMenu extends java.awt.Frame// implements ActionListener 
{
public void init() { 
setBackground( Color.white );
JPanel bottom = new JPanel();
    bottom.setBackground(Color.BLACK);
    JButton b1 = new JButton("test");
 b1.setVisible(true);
    bottom.add(b1);
    bottom.setVisible(true);
    add(bottom,BorderLayout.CENTER);
}
public static void main( String args [] ) {

    MyAWTMenu objAppFrame = new MyAWTMenu();

    objAppFrame.addWindowListener(      //Register an anonymous class as a listener.
         new WindowAdapter() {
            public void windowClosing( WindowEvent e ) 
            {  
               System.exit( 0 );
            }
         }
    );
    objAppFrame.init();
    objAppFrame.setSize( 760, 378);
    objAppFrame.setVisible( true );                    

  }

2 个答案:

答案 0 :(得分:3)

我最好按如下方式重写:

public class FooFrame extends JFrame {

    public FooFrame() {

        // your code, copy/pasted
        setBackground(Color.white);
        JPanel bottom = new JPanel();
        bottom.setBackground(Color.BLACK);
        JButton b1 = new JButton("test");
        bottom.add(b1);
        add(bottom, BorderLayout.CENTER);

        // set size & pack
        Dimension size = new Dimension(400, 400);
        setPreferredSize(size);
        setMinimumSize(size);
        pack();
        setLocationRelativeTo(null);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FooFrame().setVisible(true);
            }
        });
    }
}

答案 1 :(得分:1)

add(bottom,BorderLayout.SOUTH);

中的

init()

这是我正在运行的代码。它对我来说似乎很好。我确实添加了对pack();

的调用

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JPanel;

public class MyAWTMenu extends java.awt.Frame// implements ActionListener
{

    public void init() {
        setBackground(Color.white);
        JPanel bottom = new JPanel();
        bottom.setBackground(Color.BLACK);
        JButton b1 = new JButton("test");
        bottom.add(b1);
        bottom.setVisible(true);
        add(bottom, BorderLayout.SOUTH);
        pack();
    }

    public static void main(String args[]) {

        MyAWTMenu objAppFrame = new MyAWTMenu();

        objAppFrame.addWindowListener( //Register an anonymous class as a listener.
                new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        objAppFrame.init();
        objAppFrame.setSize(760, 378);
        objAppFrame.setVisible(true);

    }
}