1

I want to create jcomponents dynamically using database. when I open any jframe or jpanel components like jlabel, jtextfields, jcombobox, etc should be created by reading database rows. I am confused in how to give reference from database value i.e. in the String to the jcomponent's object. this is my database table

enter image description here

    try{
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","pass");
        stat = con.createStatement();
        ResultSet rs = stat.executeQuery("select * from design");
        while(rs.next()){
            jTextField1 = new JTextField();
            jTextField1.setSize(rs.getInt("height"),rs.getInt("width"));
            jTextField1.setLocation(rs.getInt("x"), rs.getInt("y"));
        }
        rs.close();
        stat.close();
        con.close();
    }
    catch(Exception e){
        System.out.println(e);
    }

this is demo table. I know this will not work because I can't communicate with objects and database. I want to print jcomponents on jframe. I will write for loop to print them multiple times. please help me.

Ashish Kudale
  • 1,230
  • 1
  • 27
  • 51
  • 1
    What did you try so far? Do you have the DB connection part solved at least? Any code to show? – dic19 Feb 23 '14 at 16:21
  • I am also trying please don't close this question. am using normal Resultset for ex: `jtextfield a = new jtextfiled();` and `a.setSize(rs.getInt(height),rs.getInt(width));` – Ashish Kudale Feb 24 '14 at 08:49
  • Please vote to reopen since this question has been edited after be closed. – dic19 Mar 05 '14 at 18:45

1 Answers1

2

First of all see this @AndrewThompson's wise advice:

Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space.

There are some helpful topics to understand what it means here:

You'll see the use of methods like setLocation(), setBounds() or setSize() is highly discouraged. However I've seen this approach before applied to allow customizing forms. But instead of specific (x,y) coordinates and fixed (width,height) you can store constraints for GridBagLayout. Let's say you have a table like this:

enter image description here

I'd start first with a class to wrap data from the DB:

public class Data {
    private String componentType, text;
    private int column, row, width, height, weightX, weightY;

    public Data(String componentType, int column, int row, int width, int height
                ,int weightX, int weightY, String text) {

        this.componentType = componentType;
        this.column = column;
        this.row = row;
        this.width = width;
        this.height = height;
        this.weightX = weightX;
        this.weightY = weightY;
        this.text = text;
   }

   // getters and setters here
}

As database calls are time consuming task you have to consider use a SwingWorker to do the database call (time consuming task) in a background thread and create/update your GUI in the Event Dispatch Thread.

Having said this you may have something like this:

public class Demo {

    private JPanel content;
    private JFrame frame;

    private void createAndShowGUI() {        
        content = new JPanel(new GridBagLayout());

        SwingWorker<Void, Data> worker = new SwingWorker<Void, Data>() {
            @Override
            protected Void doInBackground() {                    
                try{
                   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","password");
                   Statement stat = con.createStatement();
                   ResultSet rs = stat.executeQuery("select * from TableName");
                   while(rs.next()){
                      String componentType = rs.getString("component");
                      int column = rs.getInt("x");
                      int row = rs.getInt("y");
                      int width = rs.getInt("width");
                      int height = rs.getInt("height");
                      int weightx = rs.getInt("weightx");
                      int weighty = rs.getInt("weighty");
                      String text = rs.getString("text");
                      Data data = new Data(componentType, column, row, width, height
                                          ,weightx, weighty, text);
                      publish(data);
                  }
                  rs.close();
                  stat.close();
                  con.close();
              } catch(Exception e) {
                  System.out.println(e);
              }

                return null;
            }

            @Override
            protected void process(List<Data> chunks) {
                for(Data data : chunks) {

                    JComponent component = null;
                    if(data.getComponentType().equalsIgnoreCase("JTextField")) {
                        component = new JTextField(data.getText());
                    }

                    if(data.getComponentType().equalsIgnoreCase("JComboBox")) {
                        component = new JComboBox();
                    }

                    if(data.getComponentType().equalsIgnoreCase("JLabel")) {
                        component = new JLabel(data.getText());
                    }

                    if(component != null) {
                        GridBagConstraints constraints = new GridBagConstraints();
                        constraints.gridx = data.getColumn();
                        constraints.gridy = data.getRow();
                        constraints.gridwidth = data.getWidth();
                        constraints.gridheight = data.getHeight();
                        constraints.weightx = data.getWeightX();
                        constraints.weighty = data.getWeightY();

                        constraints.anchor = GridBagConstraints.WEST;
                        constraints.fill = GridBagConstraints.BOTH;
                        constraints.insets = new Insets(8,8,8,8);
                        content.add(component, constraints);
                    }

                }
            }

            @Override
            protected void done() {
                frame = new JFrame("Demo");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.getContentPane().add(content);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        };

        worker.execute();
    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Demo().createAndShowGUI();
            }
        });
    }
}

And you'll see something like this:

enter image description here

Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69
  • what is publish(Data); – Ashish Kudale Feb 25 '14 at 18:05
  • `publish()` is a SwingWorker class' method. It puts an object on a queue that will be processed when `process()` method is invoked. You need to read about SwingWorker class and how does it synchronizes the background thread and the Event Dispatch Thread. It's about concurrency in Swing. @Ashish – dic19 Feb 25 '14 at 19:28
  • what is weightx and weighty in table. why we are using it. – Ashish Kudale Feb 27 '14 at 09:39
  • 1
    @Ashish it's well explained here: [How to Use GridBagLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html). The whole point of this approach is avoid fixed components position and size because of the Andrew's comment I've quoted. But if you store GridBagLayout constraints then the layout manager will handle this matter (as it should be). Please let me know if I'm clear enough. – dic19 Feb 27 '14 at 10:07
  • Unable to solve `type List does not take parameters.` and `cannot find symbol` in ` method equalsIgnoreCase(String)` – Ashish Kudale Feb 27 '14 at 17:36
  • please reopen this question. Can I use `getName();` & `setName();` to set components id. as we define id in c#. – Ashish Kudale Mar 04 '14 at 16:45
  • Hi there! I've voted to reopen but you might consider ask a new question since it spent a while and probably this question might not have too much attention. There are both [getName()](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#getName%28%29) and [setName()](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#setName%28java.lang.String%29) methods inherited from `java.awt.Component` class so you can use them I guess (don't know if they are exactly the same in C#, look at the javadocs). @Ashish – dic19 Mar 05 '14 at 18:44