Page 1 of 2 12 LastLast
Results 1 to 20 of 34
  1. #1
    bmist is offline Member
    Join Date
    May 2010
    Posts
    1
    Rep Power
    0

    Default How to keep a string through out diffrent methods

    Ok well im writing ths app for school and i just cant seem to find out how to keep the "String ele;" constant thought the method take a look at the attachment, if you click hydrogen it will set the string ele to hyrdrogen but then once you click atomic number its null, so how would i keep the string ele through out the progam once you selected it?
    Attached Files Attached Files

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Hello and welcome to the forum!

    I hope your question gets answered soon, but if not, you may wish to post the relevant code itself in the forum with code tags. I've often found that if I take the effort to make my question as easy as possible to answer, I get helpful answers quicker. You'll likely find that this works for you too.

    Again, welcome and look forward to seeing you around!

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Looking at your code, I see that you have quite a bit of redundancy and a very very long "god" class, both of which could be vastly improved by refactoring this class and creating appropriate subclasses. This will make debugging much easier, and will make it much easier for other's to be able to understand your code much quicker (much less code to read).

    For instance, consider creating a non-GUI class called perhaps ElementInfo that holds all the important information pertaining to an actual element such as its name, atomic number, charge, etc... and then creating an ArrayList of these objects and using these objects to help you create your GUI. This will cut down on over 80% of your code.

    Also, use variable names that make sense, that are "self-commenting". If you look at your code a month from now, you may be hard-pressed to quickly figure out what JButton "b21" does.

    Next of all, the sub-windows would be better off being JDialogs not JFrames since these are in fact behaving as dialogs.

    Finally, you again may wish to post your pertinent code here and indicate which lines are causing your your current problem.

    Again, much luck!

  4. #4
    buffalo is offline Member
    Join Date
    May 2010
    Posts
    19
    Rep Power
    0

    Default

    The answer to your question is fundamental. Some of your methods redefine ele. Your code defines ele at the top as a class variable, that would normally make it available throughout all of the methods. However the method "ActionPerformed" redefines it in many places by statements like:
    String ele = "Hydrogen";
    Replace such statements with:
    ele=new String("Hydrogen");

    BTW, your coding style is fine. I wouldn't worry about what other people say, rather your style will change with experience to suit you.

  5. #5
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by buffalo View Post
    The answer to your question is fundamental. Some of your methods redefine ele. Your code defines ele at the top as a class variable, that would normally make it available throughout all of the methods. However the method "ActionPerformed" redefines it in many places by statements like:
    String ele = "Hydrogen";
    Replace such statements with:
    ele=new String("Hydrogen");
    Why would he want to call new String(...) ever? This prevents String re-use via the String pool and should be frowned upon.


    BTW, your coding style is fine. I wouldn't worry about what other people say, rather your style will change with experience to suit you.
    Hm, it seems like good advice to me to avoid huge and unmanageable classes and methods, but you're entitled to your opinion.

    Regardless, it appears that the OP has disappeared and is no longer interested in this thread.

  6. #6
    buffalo is offline Member
    Join Date
    May 2010
    Posts
    19
    Rep Power
    0

    Default

    Reply to Curmudgeon:
    Why would he want to call new String(...) ever? This prevents String re-use via the String pool and should be frowned upon.
    new String() is called to assign a value to a String variable, which is what the originator intended to do. How else would one assign a new value to a String variable?

    it seems like good advice to me to avoid huge and unmanageable classes and methods
    Huge classes are not necessarily unmanageable, especially if they are constructed in an orderly manner. Breaking the functionality into many classes doesn't doesn't help manageabilty if so doing doesn't improve its orderlyness. People like Fubarable like to preach style but don't help in supplying an answer to a question.

  7. #7
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by buffalo View Post
    Reply to Curmudgeon: new String() is called to assign a value to a String variable, which is what the originator intended to do. How else would one assign a new value to a String variable?
    It's almost always better to simply assign a String constant:
    Java Code:
    ele = "Hydrogen";
    this way the JVm can re-use a String from the String pool if desired. there are few times that I know of where it's desirable to use new String(). One is when you want to change a byte array into a String.

    Huge classes are not necessarily unmanageable, especially if they are constructed in an orderly manner. Breaking the functionality into many classes doesn't doesn't help manageabilty if so doing doesn't improve its orderlyness. People like Fubarable like to preach style but don't help in supplying an answer to a question.
    But if the class is huge, it's often hard to even see where the problem is.

  8. #8
    buffalo is offline Member
    Join Date
    May 2010
    Posts
    19
    Rep Power
    0

    Default

    Reply to Curmudgeon:
    It's almost always better to simply assign a String constant:
    I now see your point. I always thought that ele="Hydrogen"; was shorthand for ele=new String("Hydrogen"); But now, from what you say, that's not so. Rather literal strings are stored in a pool and can be used many times without allocating additional memory - right?

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by buffalo View Post
    Huge classes are not necessarily unmanageable, especially if they are constructed in an orderly manner. Breaking the functionality into many classes doesn't doesn't help manageabilty if so doing doesn't improve its orderlyness. People like Fubarable like to preach style but don't help in supplying an answer to a question.
    I admit, I like to preach style, and while my style is far from perfect, I think that changing class structure will benefit the OP's program and ability to upgrade, debug, and understand his code. For instance, which code is easier for you to understand?

    The OP's program:
    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    
    public class Elements extends JPanel implements ActionListener {
       public JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14,
                b15, b16, b17, b18, b19, b20, b21, b22, b23, b24;
    
       public JPanel aj = new JPanel();
    
       String ele;
       String atmcnum;
       String elect;
       String sym;
       String atmcmas;
    
       public Elements() {
          b1 = new JButton("Hydrogen");
          b1.setVerticalTextPosition(AbstractButton.CENTER);
          b1.setHorizontalTextPosition(AbstractButton.LEADING);
          b1.setEnabled(true);
          b1.addActionListener(this);
          b1.setActionCommand("1");
    
          b2 = new JButton("Helium");
          b2.setVerticalTextPosition(AbstractButton.CENTER);
          b2.setHorizontalTextPosition(AbstractButton.LEADING);
          b2.setEnabled(true);
          b2.addActionListener(this);
          b2.setActionCommand("2");
    
          b3 = new JButton("Lithium");
          b3.setVerticalTextPosition(AbstractButton.CENTER);
          b3.setHorizontalTextPosition(AbstractButton.LEADING);
          b3.setEnabled(true);
          b3.addActionListener(this);
          b3.setActionCommand("3");
    
          b4 = new JButton("Berillium");
          b4.setVerticalTextPosition(AbstractButton.CENTER);
          b4.setHorizontalTextPosition(AbstractButton.LEADING);
          b4.setEnabled(true);
          b4.addActionListener(this);
          b4.setActionCommand("4");
    
          b5 = new JButton("Boron");
          b5.setVerticalTextPosition(AbstractButton.CENTER);
          b5.setHorizontalTextPosition(AbstractButton.LEADING);
          b5.setEnabled(true);
          b5.addActionListener(this);
          b5.setActionCommand("5");
    
          b6 = new JButton("Carbon");
          b6.setVerticalTextPosition(AbstractButton.CENTER);
          b6.setHorizontalTextPosition(AbstractButton.LEADING);
          b6.setEnabled(true);
          b6.addActionListener(this);
          b6.setActionCommand("6");
    
          b7 = new JButton("Nitrogen");
          b7.setVerticalTextPosition(AbstractButton.CENTER);
          b7.setHorizontalTextPosition(AbstractButton.LEADING);
          b7.setEnabled(true);
          b7.addActionListener(this);
          b7.setActionCommand("7");
    
          b8 = new JButton("Oxygen");
          b8.setVerticalTextPosition(AbstractButton.CENTER);
          b8.setHorizontalTextPosition(AbstractButton.LEADING);
          b8.setEnabled(true);
          b8.addActionListener(this);
          b8.setActionCommand("8");
    
          b9 = new JButton("Fluorine");
          b9.setVerticalTextPosition(AbstractButton.CENTER);
          b9.setHorizontalTextPosition(AbstractButton.LEADING);
          b9.setEnabled(true);
          b9.addActionListener(this);
          b9.setActionCommand("9");
    
          b10 = new JButton("Neon");
          b10.setVerticalTextPosition(AbstractButton.CENTER);
          b10.setHorizontalTextPosition(AbstractButton.LEADING);
          b10.setEnabled(true);
          b10.addActionListener(this);
          b10.setActionCommand("10");
    
          b11 = new JButton("Sodium");
          b11.setVerticalTextPosition(AbstractButton.CENTER);
          b11.setHorizontalTextPosition(AbstractButton.LEADING);
          b11.setEnabled(true);
          b11.addActionListener(this);
          b11.setActionCommand("11");
    
          b12 = new JButton("Magnesium");
          b12.setVerticalTextPosition(AbstractButton.CENTER);
          b12.setHorizontalTextPosition(AbstractButton.LEADING);
          b12.setEnabled(true);
          b12.addActionListener(this);
          b12.setActionCommand("12");
    
          b13 = new JButton("Aluminium");
          b13.setVerticalTextPosition(AbstractButton.CENTER);
          b13.setHorizontalTextPosition(AbstractButton.LEADING);
          b13.setEnabled(true);
          b13.addActionListener(this);
          b13.setActionCommand("13");
    
          b14 = new JButton("Silicon");
          b14.setVerticalTextPosition(AbstractButton.CENTER);
          b14.setHorizontalTextPosition(AbstractButton.LEADING);
          b14.setEnabled(true);
          b14.addActionListener(this);
          b14.setActionCommand("14");
    
          b15 = new JButton("Phosphorous");
          b15.setVerticalTextPosition(AbstractButton.CENTER);
          b15.setHorizontalTextPosition(AbstractButton.LEADING);
          b15.setEnabled(true);
          b15.addActionListener(this);
          b15.setActionCommand("15");
    
          b16 = new JButton("Sulphur");
          b16.setVerticalTextPosition(AbstractButton.CENTER);
          b16.setHorizontalTextPosition(AbstractButton.LEADING);
          b16.setEnabled(true);
          b16.addActionListener(this);
          b16.setActionCommand("16");
    
          b17 = new JButton("Chlorine");
          b17.setVerticalTextPosition(AbstractButton.CENTER);
          b17.setHorizontalTextPosition(AbstractButton.LEADING);
          b17.setEnabled(true);
          b17.addActionListener(this);
          b17.setActionCommand("17");
    
          b18 = new JButton("Argon");
          b18.setVerticalTextPosition(AbstractButton.CENTER);
          b18.setHorizontalTextPosition(AbstractButton.LEADING);
          b18.setEnabled(true);
          b18.addActionListener(this);
          b18.setActionCommand("18");
    
          b19 = new JButton("Potassium");
          b19.setVerticalTextPosition(AbstractButton.CENTER);
          b19.setHorizontalTextPosition(AbstractButton.LEADING);
          b19.setEnabled(true);
          b19.addActionListener(this);
          b19.setActionCommand("19");
    
          b20 = new JButton("Calcuim");
          b20.setVerticalTextPosition(AbstractButton.CENTER);
          b20.setHorizontalTextPosition(AbstractButton.LEADING);
          b20.setEnabled(true);
          b20.addActionListener(this);
          b20.setActionCommand("20");
    
          b21 = new JButton("Atomic Mass");
          b21.setVerticalTextPosition(AbstractButton.CENTER);
          b21.setHorizontalTextPosition(AbstractButton.LEADING);
          b21.setEnabled(true);
          b21.addActionListener(this);
          b21.setActionCommand("21");
    
          b22 = new JButton("Electronegativity");
          b22.setVerticalTextPosition(AbstractButton.CENTER);
          b22.setHorizontalTextPosition(AbstractButton.LEADING);
          b22.setEnabled(true);
          b22.addActionListener(this);
          b22.setActionCommand("22");
    
          b23 = new JButton("Symbol");
          b23.setVerticalTextPosition(AbstractButton.CENTER);
          b23.setHorizontalTextPosition(AbstractButton.LEADING);
          b23.setEnabled(true);
          b23.addActionListener(this);
          b23.setActionCommand("23");
    
          b24 = new JButton("Atomic Number");
          b24.setVerticalTextPosition(AbstractButton.CENTER);
          b24.setHorizontalTextPosition(AbstractButton.LEADING);
          b24.setEnabled(true);
          b24.addActionListener(this);
          b24.setActionCommand("24");
    
          add(b1);
          add(b2);
          add(b3);
          add(b4);
          add(b5);
          add(b6);
          add(b7);
          add(b8);
          add(b9);
          add(b10);
          add(b11);
          add(b12);
          add(b13);
          add(b14);
          add(b15);
          add(b16);
          add(b17);
          add(b18);
          add(b19);
          add(b20);
    
       }//buttons for each element
    
       public void actionPerformed(ActionEvent e) {
          if ("1".equals(e.getActionCommand())) {
             String ele = "Hydrogen";//setting element as the string ele
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Hydrogen");//naming the fram
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);//adding buttons into content panel
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Hydrogen:");//new frames for specific info
          }
    
          else if ("2".equals(e.getActionCommand())) {
             String ele = "Helium";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Helium");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Helium:");
          }
    
          else if ("3".equals(e.getActionCommand())) {
             String ele = "Lithium";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Lithium");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Lithium:");
          }
    
          else if ("4".equals(e.getActionCommand())) {
             String ele = "Berillium";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Berillium");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Berillium:");
          }
    
          else if ("5".equals(e.getActionCommand())) {
             String ele = "Boron";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Boron");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Boron:");
          }
    
          else if ("6".equals(e.getActionCommand())) {
             String ele = "Carbon";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Carbon");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Carbon:");
          }
    
          else if ("7".equals(e.getActionCommand())) {
             String ele = "Nitrogen";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Nitrogen");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Nitrogen:");
          }
    
          else if ("8".equals(e.getActionCommand())) {
             String ele = "Oxygen";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Oxygen");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Oxygen:");
          }
    
          else if ("9".equals(e.getActionCommand())) {
             String ele = "Fluorine";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Fluorine");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Fluorine:");
          }
    
          else if ("10".equals(e.getActionCommand())) {
             String ele = "Neon";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Neon");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Neon:");
          }
    
          else if ("11".equals(e.getActionCommand())) {
             String ele = "Sodium";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Sodium");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Sodium:");
          }
    
          else if ("12".equals(e.getActionCommand())) {
             String ele = "Magnesium";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Magnesium");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Magnesium:");
          }
    
          else if ("13".equals(e.getActionCommand())) {
             String ele = "Aluminium";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Aluminium");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Aluminium:");
          }
    
          else if ("14".equals(e.getActionCommand())) {
             String ele = "Silicon";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Silicon");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Silicon:");
          }
    
          else if ("15".equals(e.getActionCommand())) {
             String ele = "Phosphorous";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Phosphorous");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Phosphorous:");
          }
    
          else if ("16".equals(e.getActionCommand())) {
             String ele = "Sulphur";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Sulphur");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Sulphur:");
          }
    
          else if ("17".equals(e.getActionCommand())) {
             String ele = "Chlorine";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Chlorine");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Chlorine:");
          }
    
          else if ("18".equals(e.getActionCommand())) {
             String ele = "Argon";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Argon");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Argon:");
          }
    
          else if ("19".equals(e.getActionCommand())) {
             String ele = "Potassium";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Potassium");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Potassium:");
          }
    
          else if ("20".equals(e.getActionCommand())) {
             String ele = "Calcium";
             System.out.println("Element:" + ele);
    
             JFrame a = new JFrame("Calcium");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Calcium:");
    
          }
    
          else if ("21".equals(e.getActionCommand())) {
    
             JFrame a = new JFrame("Calcium");
             a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             aj = new JPanel();
    
             a.add(aj);
             aj.add(b21);
             aj.add(b22);
             aj.add(b23);
             aj.add(b24);
    
             a.pack();
             a.setSize(400, 200);
             a.setLocation(400, 0);
             a.setVisible(true);
             a.setTitle("Choose what you want to know about Calcium:");
    
          }
    
       }//what happens after button is pushed
    
       public static void Elementsshow() {
    
          //Create and set up the window.
          JFrame ele = new JFrame("Elements table");
          ele.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
          //Create and set up the content pane.
          Elements newContentPane = new Elements();
          newContentPane.setOpaque(true); //content panes must be opaque
          ele.setContentPane(newContentPane);
    
          //Display the window.
          ele.pack();
          ele.setSize(400, 200);
          ele.setVisible(true);
       }
    
       public static void main(String[] args) {
    
          //creating and showing this application's GUI.
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                Elementsshow();
             }
          });
       }
    
    }

    And one that breaks the code down into separate classes:
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.swing.*;
    
    public class Elements2 {
       public static final Element[] ELEMENTS = {
          new Element("Hydrogen", "H", 1, 1.01), 
          new Element("Helium", "He", 2, 4.00), 
          new Element("Lithium", "Li", 3, 6.94),
          new Element("Beryllium", "Be", 4, 9.01),
          new Element("Boron", "B", 5, 10.81),
          new Element("Carbon", "C", 6, 12.01),
          new Element("Nitrogen", "N", 7, 14.01),
          new Element("Oxygen", "O", 8, 16.00),
          new Element("Fluorine", "F", 9, 19.00),
          new Element("Neon", "Ne", 10, 20.18),
          new Element("Sodium", "Na", 11, 22.99),
          new Element("Magnesium", "Mg", 12, 24.31),
          new Element("Aluminum", "Al", 13, 26.99),
          new Element("Silicon", "Si", 14, 28.09),
          new Element("Phosphorus", "P", 15, 30.97),
          new Element("Sulfur", "S", 16, 32.06)
       };
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("The Elements");
          frame.getContentPane().add(new ElementsGui(ELEMENTS).getMainPanel());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    
    class ElementsGui {
       private JPanel mainPanel = new JPanel();
       private Map<String, Element> elementMap = new HashMap<String, Element>();
       private ElementPanel elementPanel = new ElementPanel();
       
       public ElementsGui(Element[] elements) {
          ButtonListener btnListener = new ButtonListener();
          int gap = 10;
          mainPanel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
          mainPanel.setLayout(new BorderLayout(gap, gap));
          JPanel buttonPanel = new JPanel(new GridLayout(0, 4, gap, gap));
          buttonPanel.setLayout(new GridLayout(0, 4, gap, gap));
          for (Element element : elements) {
             elementMap.put(element.getName(), element);
             JButton btn = new JButton(element.getName());
             btn.addActionListener(btnListener);
             buttonPanel.add(btn);
          }
          
          mainPanel.add(buttonPanel, BorderLayout.NORTH);
          mainPanel.add(elementPanel.getPanel(), BorderLayout.SOUTH);
       }
       
       public JPanel getMainPanel() {
          return mainPanel;
       }
       
       private class ButtonListener implements ActionListener {
          public void actionPerformed(ActionEvent e) {
             Element element = elementMap.get(e.getActionCommand());
             elementPanel.setElement(element);
          }
       }
    }
    
    class ElementPanel {
       enum FieldName {
          NAME("Name"), SYMBOL("Symbol"), 
          ATOMIC_NUMBER("Atomic Number"), 
          ATOMIC_MASS("Atomic Mass");
          
          private String text;
          private FieldName(String text) {
             this.text = text;
          }
          public String getText() {
             return text;
          }
          public String toString() {
             return text;
          }
       }
       private static final int FIELD_SIZE = 15;
       private JPanel panel = new JPanel();
       private Map<FieldName, JTextField> fieldMap = new HashMap<FieldName, JTextField>();
       
       public ElementPanel() {
          panel.setLayout(new GridBagLayout());
          GridBagConstraints gbc = new GridBagConstraints();
          for (FieldName fieldName : FieldName.values()) {
             JLabel label = new JLabel(fieldName.getText());
             JTextField field = new JTextField(FIELD_SIZE);
             field.setEditable(false);
             fieldMap.put(fieldName, field);
             
             gbc.gridx = 0;
             gbc.gridy = GridBagConstraints.RELATIVE;
             gbc.gridwidth = 1;
             gbc.gridheight = 1;
             gbc.weightx = 1.0;
             gbc.weighty = 1.0;
             gbc.fill = GridBagConstraints.BOTH;
             gbc.anchor = GridBagConstraints.WEST;
             gbc.insets = new Insets(5, 5, 5, 20);
             panel.add(label, gbc);
             
             gbc.gridx = 1;
             gbc.anchor = GridBagConstraints.EAST;
             gbc.fill = GridBagConstraints.HORIZONTAL;
             gbc.insets = new Insets(5, 5, 5, 5);
             panel.add(field, gbc);
          }
       }
       
       public void setElement(Element element) {
          fieldMap.get(FieldName.NAME).setText(element.getName());
          fieldMap.get(FieldName.SYMBOL).setText(element.getSymbol());
          fieldMap.get(FieldName.ATOMIC_NUMBER).setText(String.valueOf(element.getAtomicNumber()));
          fieldMap.get(FieldName.ATOMIC_MASS).setText(String.valueOf(element.getAtomicMass()));
       }
       
       public JPanel getPanel() {
          return panel;
       }
    }
    
    class Element {
       private String name;
       private String symbol;
       private int atomicNumber;
       private double atomicMass;
       
       public Element(String name, String symbol, int atomicNumber,
                double atomicMass) {
          this.name = name;
          this.symbol = symbol;
          this.atomicNumber = atomicNumber;
          this.atomicMass = atomicMass;
       }
       public String getName() {
          return name;
       }
       public String getSymbol() {
          return symbol;
       }
       public int getAtomicNumber() {
          return atomicNumber;
       }
       public double getAtomicMass() {
          return atomicMass;
       }
       
       @Override
       public String toString() {
          return name + ", " + symbol + ", " + atomicNumber + ", " + atomicMass;
       }
       
    }
    Last edited by Fubarable; 05-25-2010 at 05:22 AM.

  10. #10
    buffalo is offline Member
    Join Date
    May 2010
    Posts
    19
    Rep Power
    0

    Default

    reply to Fubarable: you certainly did an admirable job in reformulating the code, which does reduce the repetition and shortens it to about 1/4. However, reduction of repetition could also be acheived with arrays and loops in the methods of a single class.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by buffalo View Post
    reply to Fubarable: you certainly did an admirable job in reformulating the code, which does reduce the repetition and shortens it to about 1/4. However, reduction of repetition could also be acheived with arrays and loops in the methods of a single class.
    The proof's in the code. Have at it, and let the best code win! :)

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Edit: Other advantages to subclassing: say I decide to add more Elements -- I simply add more to the array in the main class.

    Say I want to change the top JPanel from holding JButtons to instead hold a single JComboBox -- I have to only change one class:
    Java Code:
    class ElementsGui2 {
       private JPanel mainPanel = new JPanel();
       private ElementPanel elementPanel = new ElementPanel();
       
       public ElementsGui2(Element[] elements) {
          final JComboBox combo = new JComboBox(elements);
          combo.setSelectedIndex(-1);
          combo.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                Element element = (Element)combo.getSelectedItem();
                elementPanel.setElement(element);
             }
          });
          
          JPanel comboPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
          comboPanel.add(combo);
    
          int gap = 10;
          mainPanel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
          mainPanel.setLayout(new BorderLayout(gap, gap));
          mainPanel.add(comboPanel, BorderLayout.NORTH);
          mainPanel.add(elementPanel.getPanel(), BorderLayout.CENTER);
       }
       
       public JPanel getMainPanel() {
          return mainPanel;
       }
    
    }
    Since everything is self-contained, changing this class really doesn't affect the others.

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,751
    Rep Power
    19

    Default

    Quote Originally Posted by buffalo View Post
    reply to Fubarable: you certainly did an admirable job in reformulating the code, which does reduce the repetition and shortens it to about 1/4. However, reduction of repetition could also be acheived with arrays and loops in the methods of a single class.
    But you would still be mixing data, display, and logic into one class. And that is poor design.

    There's no zealotry involved, it is simply a fact born of long experience in system desgn by large numbers of developers. Hefty classes like the OPs are almost always a big flashing sign saying "Warning! Warning!". (With or without wavy robot arms).

  14. #14
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by Tolls View Post
    But you would still be mixing data, display, and logic into one class. And that is poor design.
    There's no zealotry involved, ....
    Someone say "Amen!" :)

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,751
    Rep Power
    19

    Default

    Well, yes...it could be summed up at "Burn the heretic!"

    Where's my flaming brand gone?

  16. #16
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by Tolls View Post
    Well, yes...it could be summed up at "Burn the heretic!"
    Where's my flaming brand gone?
    That's so last century. Us modern zealots much prefer defenestration.

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,751
    Rep Power
    19

    Default

    Well, defenestration is a good 400 years old...

    Besides, with a good burning you can turn it into a barbecue.

  18. #18
    buffalo is offline Member
    Join Date
    May 2010
    Posts
    19
    Rep Power
    0

    Default

    Reply to Tolls and Curmudgeon:
    But you would still be mixing data, display, and logic into one class. And that is poor design.
    There's no zealotry involved, ....
    In all seriouness, why is mixing bad design? After all, isn't the concept of a class that of a struct (data) plus function (logic)?

  19. #19
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,751
    Rep Power
    19

    Default

    When it comes to maintenance, especially in systems where the data comes from a db (which is quite a lot of systems), data and logic in the same class tends to cause problems, especially when you have it wired to Hibernate or somesuch.

    It simply tends to be easier to maintain things if the logic is either an extension of a data class (which is what is used whee I am at the moment), or is in a pass through class prior to insertion in the db (which was where I was at late last year). Models tend to require less refactoring than logic, so it allows you to have a fixed model you can point at and go "done", while still working on the logic side of things.

    Now, for display it's even more important because the logic has a tendency to get completely lost when it's incorporated in action listeners scattered throughout an app...and it also means it is not an easy job to detach the logic (in my view the app itself) side of things from the display, making it a pain if you decide to move from Swing to Web app.

    So, essentially, it boils down to allowing you to have a business logic lump (along with associated model) that can then be attached to any front end, and any backend.

    ETA: Oh, and debugging...:)

  20. #20
    buffalo is offline Member
    Join Date
    May 2010
    Posts
    19
    Rep Power
    0

    Default

    Reply to Toll: You make some good points about separating logic, data and I/O to simplify maintenance. I see these points as arguments against object-oriented programing, since objects are intended to encapsulate logic, data and I/O. However, Java is a prime example of an OO language. So I think that your points would be better accomodated with a procedural language, e.g. C, using specific subroutines (or macros) to do logic and I/O and perhaps struts (or arrays) for data.

Page 1 of 2 12 LastLast

Similar Threads

  1. java method to select from diffrent table
    By waboke in forum New To Java
    Replies: 2
    Last Post: 04-24-2010, 01:58 PM
  2. Add diffrent components in jtable
    By anilkumar_vist in forum Advanced Java
    Replies: 1
    Last Post: 11-23-2009, 05:03 AM
  3. log4j - multiple logs with diffrent contents
    By ld09 in forum Java Applets
    Replies: 0
    Last Post: 10-08-2009, 11:36 AM
  4. diffrent page redirection in struts.
    By rakesh_n_mehta in forum Web Frameworks
    Replies: 0
    Last Post: 12-11-2008, 06:34 AM
  5. Problems implementing Java string methods
    By everlast88az in forum New To Java
    Replies: 8
    Last Post: 11-06-2008, 04:17 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •