因为你使用的是BorderLayout,在BorderLayout被使用的情况下,调用rootFrame.getContentPane().add时,如果没有指定安放的位置,则会默认把空间放在中央并伸展至四周,所以你可以指定排放的位置,如NORTH, SOUTH, CENTER, EAST, WEST等,也可以改用别的Layout,如FlowLayout。

解决方案 »

  1.   

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class SwingSample implements ActionListener
    {
            private JFrame rootFrame=null;
            private JButton exitButton=null;
            private JButton clickMeButton=null;
            private JLabel rootLabel=null;
            private JLabel  clickNumsLabel=null;
            private int m_iClickNum=0;
            private String m_strLabelPrefix="一共点击了:";
            private String m_strLabelPostfix="次";
            private Hashtable     componentTable;
            public SwingSample()
            {
                    componentTable=new Hashtable(10);
                    rootFrame=new JFrame();
                    rootLabel=new JLabel();
                    rootFrame.getContentPane().setLayout(new FlowLayout());///////////////在这里
                    rootFrame.setDefaultLookAndFeelDecorated(true);
                    //添加“退出”按纽
                    exitButton=new JButton("退出");
                    exitButton.setMnemonic(KeyEvent.VK_Q);
                    exitButton.addActionListener(this);
                    //
                    clickMeButton =new JButton("点击");
                    clickMeButton.setMnemonic(KeyEvent.VK_C);
                    clickMeButton.addActionListener(this);
                    //
                    clickNumsLabel=new JLabel(m_strLabelPrefix +m_iClickNum+m_strLabelPostfix);                //                rootFrame.getContentPane().add(exitButton);
                    rootFrame.getContentPane().add(clickMeButton);
                    rootFrame.getContentPane().add(clickNumsLabel);
                    rootFrame.pack();
                    rootFrame.setVisible(true);                componentTable.put("RootFrame",rootFrame);
                    componentTable.put("ExitButton",exitButton);
            }
            //
            //
            //
            private JFrame getRootFrame()
            {
                    return rootFrame;
            }        //
            public static void main(String[] args)
            {
                    SwingSample theApp=new SwingSample();
            }
            //
            public void actionPerformed(ActionEvent e)
            {
                    if(e.getSource()==exitButton)
                    {
                            System.exit(0);
                    }
                    else
                    if(e.getSource()==clickMeButton)
                    {
                            m_iClickNum+=1;
                            clickNumsLabel.setText(m_strLabelPrefix+m_iClickNum+m_strLabelPostfix);
                    }
            }
    }