Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package arrayofobjects;
  6.  
  7. import java.awt.Container;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10. import java.util.ArrayList;
  11. import javax.swing.JButton;
  12. import javax.swing.JFrame;
  13. import javax.swing.JOptionPane;
  14. import javax.swing.JTextArea;
  15.  
  16. /**
  17. *
  18. * @author jwporter3
  19. */
  20. public class MainArrayList extends JFrame {
  21. static final int MAX_NAMES = 5;
  22.  
  23. JTextArea namesArea; // where a list of names is displayed
  24. JButton newNameButton; // button to create a new AName object
  25. ArrayList alNames; // collection of AName objects
  26.  
  27. public MainArrayList() {
  28. createUserInterface();
  29. alNames = new ArrayList();
  30. }
  31.  
  32. private void createUserInterface() {
  33. // get content pane and set layout to null
  34. Container contentPane = getContentPane();
  35. contentPane.setLayout(null);
  36.  
  37. newNameButton = new JButton("New Name");
  38. newNameButton.setBounds(10, 10, 100, 20);
  39. contentPane.add(newNameButton);
  40. newNameButton.addActionListener(
  41. new ActionListener() // anonymous inner class
  42. {
  43. // event handler called when viewJButton is pressed
  44.  
  45. public void actionPerformed(ActionEvent event) {
  46. newNameAction();
  47. }
  48. } // end anonymous inner class
  49. ); // end call to addActionListener
  50.  
  51. namesArea = new JTextArea();
  52. namesArea.setBounds(10, 50, 200, 200);
  53. contentPane.add(namesArea);
  54.  
  55. setTitle("Name App"); // set title bar string
  56. setSize(250, 300); // set window size
  57. setVisible(true); // display window
  58. }
  59.  
  60. private void newNameAction() {
  61. String name = JOptionPane.showInputDialog("Please input a name");
  62. AName newName = new AName(name);
  63. alNames.add(newName);
  64.  
  65. // pull names from ArrayList into a fixed array for easy iteration
  66. AName[] newNames = new AName[alNames.size()];
  67. alNames.toArray(newNames);
  68.  
  69. // clear text area
  70. namesArea.setText("");
  71.  
  72. // display all the AName names in the text area
  73. for (AName an : newNames) {
  74. namesArea.append(an.getName() + "\n");
  75. }
  76. }
  77.  
  78. /**
  79. * @param args the command line arguments
  80. */
  81. public static void main(String[] args) {
  82. MainArrayList mainClass = new MainArrayList();
  83. mainClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement