使用数据库创建jcomponents [英] create jcomponents using database

查看:39
本文介绍了使用数据库创建jcomponents的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用数据库动态创建 jcomponents.当我打开任何 jframe 或 jpanel 组件(如 jlabel、jtextfields、jcombobox 等)时,应该通过读取数据库行来创建.我对如何从数据库值(即在字符串中)引用 jcomponent 的对象感到困惑.这是我的数据库表

 尝试{con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","pass");stat = con.createStatement();ResultSet rs = stat.executeQuery("select * from design");而(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();关闭();}捕获(异常 e){System.out.println(e);}

这是演示表.我知道这行不通,因为我无法与对象和数据库进行通信.我想在 jframe 上打印 jcomponents.我将编写 for 循环以多次打印它们.请帮帮我.

解决方案

首先看看这个@AndrewThompson 的明智建议:

<块引用>

Java GUI 可能必须在许多平台上工作,在不同的平台上屏幕分辨率使用不同的PLAF.因此,他们不是有利于元件的准确放置.组织组件对于健壮的 GUI,请改用布局管理器或组合它们,以及布局填充和空白边框.

有一些有用的主题可以帮助您理解此处的含义:

  • 在后台线程中执行数据库调用(耗时的任务)并在 事件调度线程.

    说到这里,你可能会有这样的想法:

    公共类演示{私人 JPanel 内容;私人 JFrame 框架;私有无效 createAndShowGUI() {content = new JPanel(new GridBagLayout());SwingWorkerworker = new SwingWorker() {@覆盖受保护的 Void doInBackground() {尝试{Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","password");语句 stat = con.createStatement();ResultSet rs = stat.executeQuery("select * from TableName");而(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");数据数据=新数据(组件类型,列,行,宽,高,weightx, weighty, 文本);发布(数据);}rs.close();stat.close();关闭();} 捕获(异常 e){System.out.println(e);}返回空;}@覆盖受保护的无效进程(列表<数据>块){for(数据数据:块){JComponent 组件 = null;if(data.getComponentType().equalsIgnoreCase("JTextField")) {组件 = 新 JTextField(data.getText());}if(data.getComponentType().equalsIgnoreCase("JComboBox")) {组件 = 新 JComboBox();}if(data.getComponentType().equalsIgnoreCase("JLabel")) {组件 = 新 JLabel(data.getText());}如果(组件!= null){GridBagConstraints 约束 = 新的 GridBagConstraints();约束.gridx = data.getColumn();约束.gridy = data.getRow();约束.gridwidth = data.getWidth();约束.gridheight = data.getHeight();约束.weightx = data.getWeightX();约束.weighty = data.getWeightY();约束.anchor = GridBagConstraints.WEST;约束.fill = GridBagConstraints.BOTH;Constraints.insets = new Insets(8,8,8,8);内容.添加(组件,约束);}}}@覆盖受保护的无效完成(){frame = new JFrame("Demo");frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);frame.getContentPane().add(content);框架.pack();frame.setLocationRelativeTo(null);frame.setVisible(true);}};worker.execute();}公共静态无效主(字符串 [] args){SwingUtilities.invokeLater(new Runnable() {@覆盖公共无效运行(){新演示().createAndShowGUI();}});}}

    你会看到这样的:

    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

        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.

    解决方案

    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:

    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:

    这篇关于使用数据库创建jcomponents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆