如何在java中将jpanel添加到jpanel

时间:2016-05-19 12:20:48

标签: java eclipse jpanel

当我向现有的jpanel添加jpanel时出现问题!

我希望jlist位于中心位置,jbuttom位于南方位置!

我可以看到jlist,但jbuttom不会显示!

我正在使用Eclipse 3.0版本。

这是我的代码:

package classes;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class JPanelDecorator extends JPanel implements ActionListener
{
    private static final long serialVersionUID = 1L;
    private JList<String> list = null;
    private JButton Change=null;

    public JPanelDecorator()
    {
        super();
        setLayout(new BorderLayout());       
        setSize(450 ,400);
        String animals_list[] = new String[AquaPanel.swims.size()];
        LinkedList<Swimmable> ir = new LinkedList<Swimmable>(AquaPanel.swims);
        for(int i=0;i<ir.size();i++)
        {
            animals_list[i]=(i+1+". "+ir.get(i).toString());
        }

        list = new JList<String>(animals_list );
        list.setFont(new Font("Tahoma",Font.BOLD,15));
        list.setSize(450, 300);
        add(list,BorderLayout.CENTER);

        Change = new JButton("Change Color");
        Change.addActionListener(this);
        add(Change,BorderLayout.CENTER);
        repaint();
    }
    @Override
    public void actionPerformed(ActionEvent e) {


    }

}

请帮忙!

1 个答案:

答案 0 :(得分:1)

你有一个微妙的错误。在JPanelDecorator的构造函数中,您有:

public JPanelDecorator()
{
    //....
    add(list,BorderLayout.CENTER);
    //...
    add(Change,BorderLayout.CENTER); // center again...
    //...
}

但你需要的是:

public JPanelDecorator()
{
    //....
    add(list,BorderLayout.CENTER);
    //...
    add(Change,BorderLayout.SOUTH); // south
    //...
}