日期:2014-05-20 浏览次数:20807 次
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; public class AddButton extends JFrame implements ActionListener{ private JPanel jp; private ArrayList<String> lst=null; private JButton addBtn; public AddButton(){ lst=new ArrayList<String>(); lst.add("按钮1"); lst.add("按钮2"); jp=new JPanel(new GridLayout(lst.size(),1)); for(int i=0;i<lst.size();i++){ JButton jb=new JButton(lst.get(i)); jp.add(jb); } addBtn=new JButton("添加一个按钮"); addBtn.setActionCommand("add"); addBtn.addActionListener(this); this.add(jp); this.add(addBtn,BorderLayout.SOUTH); this.setSize(400, 300); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.setVisible(true); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub AddButton ab=new AddButton(); } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub if(arg0.getActionCommand().equals("add")){ System.out.println("add"); lst.add("按钮3"); //JButton jb=new JButton(lst.get(2)); //如何添加到jp中去?? //jp.add(jb); jp.removeAll(); jp.setLayout(new GridLayout(lst.size(), 1)); for (int i = 0; i < lst.size(); i++) { jp.add(new JButton(lst.get(i))); } this.repaint(); jp.validate(); //期望的效果是网格布局的jp能变成new JPanel(new GridLayout(3,1))的效果 } } }