-1

The following Java program attempts to read data from a database, but instead of creating the multiple buttons I expect to be the result of the while() loop, I only get one button whose title is the first database entry. Can anyone help me determine why?

 // Submit button's action handler

btnSubmit.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) 
            JFrame2 f2 = new JFrame2();
            f2.setVisible(true);
            try {
                String query = "select name from decipline";
                pst = conn.prepareStatement(query);
                rs = pst.executeQuery();
                while(rs.next()) {  
                    String str = rs.getString("name");
                    JButton btn = new JButton(str);
                    System.out.println(str);
                    btn.addActionListener(this);
                    btn.setBounds(154, 112, 89, 23);
                    f2.getContentPane().add(btn);               
                }
            } catch(Exception E) {
                E.printStackTrace();
            } 
        }
    });
clearlight
  • 12,255
  • 11
  • 57
  • 75
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) **`while(rs.next()) { .. btn.setBounds(154, 112, 89, 23);` No matter how many times it loops, all the buttons are created in the same location at the same size, so only one will appear.** 3) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, .. – Andrew Thompson Dec 30 '16 at 06:03
  • .. or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 4) Rather than creating multiple buttons, I would recommend creating multiple rows in a `JList` or a `JTable` (each of which already exists and is on-screen). 5) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Dec 30 '16 at 06:05
  • @Andrew Use comments to ask for more information or suggest improvements. Avoid answering questions in comments. – Mordechai Dec 30 '16 at 06:14
  • actually i want to create hierarchy of tabs for exp. if i clicked one tab it will take data from database and create relevant tabs ...what you recommend for this please help me out.. – Ashish Sharma Dec 30 '16 at 06:16
  • I don't know the layout use in JFrame2 but I would guess it is set to null (please confirm this) since you used the bounds property. Use a Layout... this is cleaner, easier, elegant, ... And just do your test with a simple loop to add 2 or 3 buttons instead of doind your test with the DB. – AxelH Dec 30 '16 at 06:16
  • 3
    @MouseEvent I don't give questions serious consideration until there is an MCVE nor answer based on a hunch. If you want to form an answer from any comment I made, go for it. The bottom line is that the OP's entire approach is less than optimal, and if they change the approach the current problem will probably disappear. See also [Is “Don't do it” a valid answer?](http://meta.stackexchange.com/questions/8891/is-dont-do-it-a-valid-answer) – Andrew Thompson Dec 30 '16 at 06:17
  • Tried to clarify question and example. – clearlight Jan 01 '17 at 20:06
  • Improve the title – clearlight Jan 01 '17 at 20:11
  • I would pay more attention to syntax. Looks much better with one space around `=` and after `;` in for loops. Also better to consistently name variables for what they do or are, for example `str `could be called `name`, instead, and why not name `f2` as `frame2`? And is "decipline" a misspelling of "discipline"? – clearlight Jan 01 '17 at 20:14

2 Answers2

0

You really want to avoid the use of null layouts and setBounds as much as possible. Check out all of the different layout managers available. Based on your example I would recommend GridLayout. Also, instead of buttons in a JFrame for a submission-type example you may want to create a ButtonGroup of JRadioButtons inside a JOptionPane.

try {
    List<String> names = new ArrayList<String>();
    PreparedStatement ps = conn.prepareStatement("SELECT name FROM discipline");
    ResultSet rs = ps.executeQuery();
    while(rs.next()) {
        names.add(rs.getString("name"));
    }

    JPanel menu = new JPanel(new GridLayout(1, names.size())); // One column, as many rows as names.
    List<JRadioButton> buttons = new ArrayList<JRadioButton>();
    ButtonGroup bg = new ButtonGroup();
    for(String name : names) {
        JRadioButton radio = new JRadioButton(name);
        bg.add(radio);
        buttons.add(radio);
        menu.add(radio);
    }

    int code = JOptionPane.showConfirmDialog(null, menu, "Choose a name.", JOptionPane.OK_CANCEL_OPTION);
    if(code == JOptionPane.OK_OPTION) {
        JRadioButton selected = null;
        for(JRadioButton btn : buttons) {
            if(btn.isSelected()) {
                selected = btn;
            }
        }
        if(selected != null) {
            String name = selected.getText();
            // Do submission with chosen name.
        } else {
            // You didn't choose a name!
        }
    } else {
        // Canceled option.
    }
} catch (Exception e) {
    e.printStackTrace();
}
Matthew Wright
  • 1,485
  • 1
  • 14
  • 38
-1

Below is what I suggest you.

    btnSubmit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) 
                    //frame.dispose();
                    JFrame2 f2=new JFrame2();
                    f2.setVisible(true);
                    f2.setLayout(null);
                try{
                    int x=154, width=89;
                    String query = "select name from decipline";
                    pst=conn.prepareStatement(query);
                    rs=pst.executeQuery();
                    //int i=0;
                while(rs.next())
                {   
                     String str= rs.getString("name");
                     JButton btn =new JButton(str);
                     System.out.println(str);
                     btn.addActionListener(new ActionListner(){
                          @Override
                    public void actionPerformed(ActionEvent e) {
                     .......
                       }
                     });
                     btn.setBounds(x, 112, width, 23);
                     x=x+width+1;
                     f2.getContentPane().add(btn);

                  }
                }
                catch(Exception E){
                    E.printStackTrace();
                } 
            }
        });
Kuldeep Dubey
  • 1,097
  • 2
  • 11
  • 33
  • Thanks @Kuldeep ..and also i want to ask that how can i add seperate actionListener for each button? – Ashish Sharma Dec 30 '16 at 07:07
  • `btn.setBounds(x, 112, width, 23);` Please stop suggesting things until you work out why that is such a poor idea. – Andrew Thompson Dec 30 '16 at 07:18
  • *"..please suggest me what would be the good idea."* I already did in comments that you apparently ignored, 2 hours ago. You can lead a horse to water, but you can't make it drink. The down votes on the question & answer were to warn unsuspecting newbies away from them. – Andrew Thompson Dec 30 '16 at 08:55