Created
May 20, 2012 10:33
-
-
Save bxshi/2757610 to your computer and use it in GitHub Desktop.
Create Jpanel and buttons at run time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.BorderLayout; | |
import java.awt.FlowLayout; | |
import java.awt.Panel; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import java.util.ArrayList; | |
import java.util.List; | |
import javax.swing.JButton; | |
import javax.swing.JFrame; | |
import javax.swing.JPanel; | |
import javax.swing.JTextField; | |
public class JavaApplication7 extends JFrame | |
{ | |
JPanel panel; | |
List<JPanel> components = new ArrayList<JPanel>(); | |
public JavaApplication7() | |
{ | |
setLayout(new BorderLayout()); | |
panel=new JPanel(); | |
panel.setLayout(new FlowLayout()); | |
add(panel,BorderLayout.CENTER); | |
JPanel answer = new JPanel(); | |
JButton jbminus = new JButton("-"); | |
jbminus.setEnabled(false); | |
JButton jbplus = new JButton("+"); | |
JTextField jtext = new JTextField("test"); | |
answer.add(jbminus); | |
answer.add(jbplus); | |
answer.add(jtext); | |
panel.add(answer); | |
components.add(answer); | |
jbplus.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent ae) { | |
JPanel answer = new JPanel(); | |
JButton jbminus = new JButton("-"); | |
//JButton jbminus = new JButton(ICon); | |
JButton jbplus = new JButton("+"); | |
JTextField jtext = new JTextField("test"); | |
answer.add(jbminus); | |
answer.add(jbplus); | |
answer.add(jtext); | |
jbminus.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent ae) { | |
if (components.contains(((JButton)ae.getSource()).getParent()) == true) | |
{// in list | |
components.remove(((JButton)ae.getSource()).getParent()); | |
((JButton)ae.getSource()).getParent().getParent().remove(((JButton)ae.getSource()).getParent()); | |
panel.revalidate(); | |
panel.validate(); | |
panel.repaint(); | |
} | |
} | |
}); | |
jbplus.addActionListener(this); | |
components.add(answer); | |
panel.removeAll(); | |
for(int i=0;i<components.size();i++){ | |
panel.add(components.get(i)); | |
} | |
panel.revalidate(); | |
panel.validate(); | |
panel.repaint(); | |
} | |
}); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setSize(500,500); | |
setVisible(true); | |
} | |
public static void main(String[]args) | |
{ | |
JavaApplication7 acojfar=new JavaApplication7(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment