Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- /**
- * "Code early, Code often."
- */
- public class SimpleFrame extends JFrame {
- int frameCount = 1;
- public SimpleFrame(){
- super("SimpleFrame");
- final JPanel centerPanel = new JPanel();//this panel will hold the new components we create.
- final JPanel topPanel = new JPanel();
- final String[] choices = new String[]{"Label", "Button", "Frame"};
- final JComboBox comboBox = new JComboBox(choices);
- final JButton addComponentButton = new JButton("Add");
- addComponentButton.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e) {
- //When the button addComponentButton is pressed, this code will execute.
- final Object selectedItem = comboBox.getSelectedItem(); // See what's selected in the combobox.
- if(null != selectedItem){
- if("Label".equals(selectedItem)){
- centerPanel.add(new JLabel("This is a label"));
- }else if("Button".equals(selectedItem)){
- centerPanel.add(new JButton("This is a Button"));
- }else if("Frame".equals(selectedItem)){
- JFrame newFrame = new JFrame("This is Frame#"+(frameCount));
- frameCount++;
- newFrame.setLocation(frameCount*20, frameCount*20);
- newFrame.setSize(new Dimension(100,100));
- newFrame.setVisible(true);
- }else{
- JOptionPane.showMessageDialog(null, "Button was pressed, but nothing was selected!");
- }
- topPanel.revalidate();
- }
- }
- });
- //add our combobox and button to the top panel
- topPanel.add(comboBox);
- topPanel.add(addComponentButton);
- //now we'll add our two panels to the frame's content pane, and we're done.
- getContentPane().setLayout(new BorderLayout());
- getContentPane().add(topPanel, BorderLayout.NORTH);
- getContentPane().add(centerPanel, BorderLayout.CENTER);
- }
- public static void main(String[] args) {
- SimpleFrame sf = new SimpleFrame();
- sf.setSize(new Dimension(800,600));
- sf.setVisible(true);
- sf.addWindowListener(new WindowAdapter() {
- @Override
- public void windowClosed(WindowEvent e) {
- System.exit(1);
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement