Search in sources :

Example 1 with DefaultTableModel

use of com.codename1.ui.table.DefaultTableModel in project CodenameOne by codenameone.

the class Table method getPropertyValue.

/**
 * {@inheritDoc}
 */
public Object getPropertyValue(String name) {
    if (name.equals("data")) {
        String[][] result = new String[((DefaultTableModel) model).data.size()][];
        for (int iter = 0; iter < result.length; iter++) {
            Object[] o = ((DefaultTableModel) model).data.get(iter);
            String[] arr = new String[o.length];
            result[iter] = arr;
            for (int ai = 0; ai < arr.length; ai++) {
                Object current = o[ai];
                if (current instanceof String) {
                    arr[ai] = (String) current;
                } else {
                    if (current != null) {
                        arr[iter] = current.toString();
                    }
                }
            }
        }
        return result;
    }
    if (name.equals("header")) {
        return ((DefaultTableModel) model).columnNames;
    }
    return null;
}
Also used : Constraint(com.codename1.ui.validation.Constraint)

Example 2 with DefaultTableModel

use of com.codename1.ui.table.DefaultTableModel in project CodenameOne by codenameone.

the class SQLExplorerSample method start.

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Toolbar.setGlobalToolbar(true);
    Style s = UIManager.getInstance().getComponentStyle("TitleCommand");
    FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_QUERY_BUILDER, s);
    Form hi = new Form("SQL Explorer", new BorderLayout());
    hi.getToolbar().addCommandToRightBar("", icon, (e) -> {
        TextArea query = new TextArea(3, 80);
        Command ok = new Command("Execute");
        Command cancel = new Command("Cancel");
        if (Dialog.show("Query", query, ok, cancel) == ok) {
            Database db = null;
            Cursor cur = null;
            try {
                db = Display.getInstance().openOrCreate("MyDB.db");
                if (query.getText().startsWith("select")) {
                    cur = db.executeQuery(query.getText());
                    int columns = cur.getColumnCount();
                    hi.removeAll();
                    if (columns > 0) {
                        boolean next = cur.next();
                        if (next) {
                            ArrayList<String[]> data = new ArrayList<>();
                            String[] columnNames = new String[columns];
                            for (int iter = 0; iter < columns; iter++) {
                                columnNames[iter] = cur.getColumnName(iter);
                            }
                            while (next) {
                                Row currentRow = cur.getRow();
                                String[] currentRowArray = new String[columns];
                                for (int iter = 0; iter < columns; iter++) {
                                    currentRowArray[iter] = currentRow.getString(iter);
                                }
                                data.add(currentRowArray);
                                next = cur.next();
                            }
                            Object[][] arr = new Object[data.size()][];
                            data.toArray(arr);
                            hi.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
                        } else {
                            hi.add(BorderLayout.CENTER, "Query returned no results");
                        }
                    } else {
                        hi.add(BorderLayout.CENTER, "Query returned no results");
                    }
                } else {
                    db.execute(query.getText());
                    hi.add(BorderLayout.CENTER, "Query completed successfully");
                }
                hi.revalidate();
            } catch (IOException err) {
                Log.e(err);
                hi.removeAll();
                hi.add(BorderLayout.CENTER, "Error: " + err);
                hi.revalidate();
            } finally {
                Util.cleanup(db);
                Util.cleanup(cur);
            }
        }
    });
    hi.show();
}
Also used : Table(com.codename1.ui.table.Table) Form(com.codename1.ui.Form) TextArea(com.codename1.ui.TextArea) DefaultTableModel(com.codename1.ui.table.DefaultTableModel) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Cursor(com.codename1.db.Cursor) BorderLayout(com.codename1.ui.layouts.BorderLayout) Command(com.codename1.ui.Command) Database(com.codename1.db.Database) Style(com.codename1.ui.plaf.Style) Row(com.codename1.db.Row) FontImage(com.codename1.ui.FontImage)

Example 3 with DefaultTableModel

use of com.codename1.ui.table.DefaultTableModel in project CodenameOne by codenameone.

the class JavaSEPort method createSkinsMenu.

private JMenu createSkinsMenu(final JFrame frm, final JMenu menu) throws MalformedURLException {
    JMenu m;
    if (menu == null) {
        m = new JMenu("Skins");
        m.setDoubleBuffered(true);
    } else {
        m = menu;
        m.removeAll();
    }
    final JMenu skinMenu = m;
    Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
    String skinNames = pref.get("skins", DEFAULT_SKINS);
    if (skinNames != null) {
        if (skinNames.length() < DEFAULT_SKINS.length()) {
            skinNames = DEFAULT_SKINS;
        }
        ButtonGroup skinGroup = new ButtonGroup();
        StringTokenizer tkn = new StringTokenizer(skinNames, ";");
        while (tkn.hasMoreTokens()) {
            final String current = tkn.nextToken();
            String name = current;
            if (current.contains(":")) {
                try {
                    URL u = new URL(current);
                    File f = new File(u.getFile());
                    if (!f.exists()) {
                        continue;
                    }
                    name = f.getName();
                } catch (Exception e) {
                    continue;
                }
            } else {
                // remove the old builtin skins from the menu
                if (current.startsWith("/") && !current.equals(DEFAULT_SKIN)) {
                    continue;
                }
            }
            String d = System.getProperty("dskin");
            JRadioButtonMenuItem i = new JRadioButtonMenuItem(name, name.equals(pref.get("skin", d)));
            i.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    if (netMonitor != null) {
                        netMonitor.dispose();
                        netMonitor = null;
                    }
                    if (perfMonitor != null) {
                        perfMonitor.dispose();
                        perfMonitor = null;
                    }
                    Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                    pref.putBoolean("desktopSkin", false);
                    String mainClass = System.getProperty("MainClass");
                    if (mainClass != null) {
                        pref.put("skin", current);
                        frm.dispose();
                        System.setProperty("reload.simulator", "true");
                    } else {
                        loadSkinFile(current, frm);
                        refreshSkin(frm);
                    }
                }
            });
            skinGroup.add(i);
            skinMenu.add(i);
        }
    }
    JMenuItem dSkin = new JMenuItem("Desktop.skin");
    dSkin.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            if (netMonitor != null) {
                netMonitor.dispose();
                netMonitor = null;
            }
            if (perfMonitor != null) {
                perfMonitor.dispose();
                perfMonitor = null;
            }
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("desktopSkin", true);
            pref.putBoolean("uwpDesktopSkin", false);
            String mainClass = System.getProperty("MainClass");
            if (mainClass != null) {
                deinitializeSync();
                frm.dispose();
                System.setProperty("reload.simulator", "true");
            }
        }
    });
    JMenuItem uwpSkin = new JMenuItem("UWP Desktop.skin");
    uwpSkin.setToolTipText("Windows 10 Desktop Skin");
    uwpSkin.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            if (netMonitor != null) {
                netMonitor.dispose();
                netMonitor = null;
            }
            if (perfMonitor != null) {
                perfMonitor.dispose();
                perfMonitor = null;
            }
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("desktopSkin", true);
            pref.putBoolean("uwpDesktopSkin", true);
            String mainClass = System.getProperty("MainClass");
            if (mainClass != null) {
                deinitializeSync();
                frm.dispose();
                System.setProperty("reload.simulator", "true");
            }
        }
    });
    skinMenu.addSeparator();
    skinMenu.add(dSkin);
    skinMenu.add(uwpSkin);
    skinMenu.addSeparator();
    JMenuItem more = new JMenuItem("More...");
    skinMenu.add(more);
    more.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final JDialog pleaseWait = new JDialog(frm, false);
            pleaseWait.setLocationRelativeTo(frm);
            pleaseWait.setTitle("Message");
            pleaseWait.setLayout(new BorderLayout());
            pleaseWait.add(new JLabel("  Please Wait...  "), BorderLayout.CENTER);
            pleaseWait.pack();
            pleaseWait.setVisible(true);
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    final JDialog d = new JDialog(frm, true);
                    d.setLocationRelativeTo(frm);
                    d.setTitle("Skins");
                    d.getContentPane().setLayout(new BorderLayout());
                    String userDir = System.getProperty("user.home");
                    final File skinDir = new File(userDir + "/.codenameone/");
                    if (!skinDir.exists()) {
                        skinDir.mkdir();
                    }
                    Vector data = new Vector();
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    final Document[] doc = new Document[1];
                    try {
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                        InputStream is = openSkinsURL();
                        doc[0] = db.parse(is);
                        NodeList skins = doc[0].getElementsByTagName("Skin");
                        for (int i = 0; i < skins.getLength(); i++) {
                            Node skin = skins.item(i);
                            NamedNodeMap attr = skin.getAttributes();
                            String url = attr.getNamedItem("url").getNodeValue();
                            int ver = 0;
                            Node n = attr.getNamedItem("version");
                            if (n != null) {
                                ver = Integer.parseInt(n.getNodeValue());
                            }
                            boolean exists = new File(skinDir.getAbsolutePath() + url).exists();
                            if (!(exists) || Integer.parseInt(pref.get(url, "0")) < ver) {
                                Vector row = new Vector();
                                row.add(new Boolean(false));
                                row.add(new ImageIcon(new URL(defaultCodenameOneComProtocol + "://www.codenameone.com/OTA" + attr.getNamedItem("icon").getNodeValue())));
                                row.add(attr.getNamedItem("name").getNodeValue());
                                if (exists) {
                                    row.add("Update");
                                } else {
                                    row.add("New");
                                }
                                data.add(row);
                            }
                        }
                    } catch (Exception ex) {
                        Logger.getLogger(JavaSEPort.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (data.size() == 0) {
                        pleaseWait.setVisible(false);
                        JOptionPane.showMessageDialog(frm, "No New Skins to Install");
                        return;
                    }
                    Vector cols = new Vector();
                    cols.add("Install");
                    cols.add("Icon");
                    cols.add("Name");
                    cols.add("");
                    final DefaultTableModel tableModel = new DefaultTableModel(data, cols) {

                        @Override
                        public boolean isCellEditable(int row, int column) {
                            return column == 0;
                        }
                    };
                    JTable skinsTable = new JTable(tableModel) {

                        @Override
                        public Class<?> getColumnClass(int column) {
                            if (column == 0) {
                                return Boolean.class;
                            }
                            if (column == 1) {
                                return Icon.class;
                            }
                            return super.getColumnClass(column);
                        }
                    };
                    skinsTable.setRowHeight(112);
                    skinsTable.getTableHeader().setReorderingAllowed(false);
                    final JTextField filter = new JTextField();
                    final TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(((DefaultTableModel) skinsTable.getModel()));
                    filter.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {

                        private void updateFilter() {
                            try {
                                RowFilter rf = RowFilter.regexFilter("(?i)" + filter.getText(), 2);
                                sorter.setRowFilter(rf);
                            } catch (java.util.regex.PatternSyntaxException e) {
                                return;
                            }
                        }

                        @Override
                        public void insertUpdate(javax.swing.event.DocumentEvent e) {
                            updateFilter();
                        }

                        @Override
                        public void removeUpdate(DocumentEvent e) {
                            updateFilter();
                        }

                        @Override
                        public void changedUpdate(DocumentEvent e) {
                            updateFilter();
                        }
                    });
                    skinsTable.setRowSorter(sorter);
                    d.getContentPane().add(filter, BorderLayout.NORTH);
                    d.getContentPane().add(new JScrollPane(skinsTable), BorderLayout.CENTER);
                    JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
                    JButton download = new JButton("Download");
                    download.addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            final Vector toDowload = new Vector();
                            NodeList skins = doc[0].getElementsByTagName("Skin");
                            for (int i = 0; i < tableModel.getRowCount(); i++) {
                                if (((Boolean) tableModel.getValueAt(i, 0)).booleanValue()) {
                                    Node skin;
                                    for (int j = 0; j < skins.getLength(); j++) {
                                        skin = skins.item(j);
                                        NamedNodeMap attr = skin.getAttributes();
                                        if (attr.getNamedItem("name").getNodeValue().equals(tableModel.getValueAt(i, 2))) {
                                            String url = attr.getNamedItem("url").getNodeValue();
                                            String[] data = new String[2];
                                            data[0] = defaultCodenameOneComProtocol + "://www.codenameone.com/OTA" + url;
                                            data[1] = attr.getNamedItem("version").getNodeValue();
                                            toDowload.add(data);
                                            break;
                                        }
                                    }
                                }
                            }
                            if (toDowload.size() > 0) {
                                final JDialog downloadMessage = new JDialog(d, true);
                                downloadMessage.setTitle("Downloading");
                                downloadMessage.setLayout(new FlowLayout());
                                downloadMessage.setLocationRelativeTo(d);
                                final JLabel details = new JLabel("<br><br>Details");
                                downloadMessage.add(details);
                                final JLabel progress = new JLabel("Progress<br><br>");
                                downloadMessage.add(progress);
                                new Thread() {

                                    @Override
                                    public void run() {
                                        for (Iterator it = toDowload.iterator(); it.hasNext(); ) {
                                            String[] data = (String[]) it.next();
                                            String url = data[0];
                                            details.setText(url.substring(url.lastIndexOf("/")));
                                            details.repaint();
                                            progress.setText("");
                                            progress.repaint();
                                            try {
                                                File skin = downloadSkin(skinDir, url, data[1], progress);
                                                if (skin.exists()) {
                                                    addSkinName(skin.toURI().toString());
                                                }
                                            } catch (Exception e) {
                                            }
                                        }
                                        downloadMessage.setVisible(false);
                                        d.setVisible(false);
                                        try {
                                            createSkinsMenu(frm, skinMenu);
                                        } catch (MalformedURLException ex) {
                                            Logger.getLogger(JavaSEPort.class.getName()).log(Level.SEVERE, null, ex);
                                        }
                                    }
                                }.start();
                                downloadMessage.pack();
                                downloadMessage.setSize(200, 70);
                                downloadMessage.setVisible(true);
                            } else {
                                JOptionPane.showMessageDialog(d, "Choose a Skin to Download");
                            }
                        }
                    });
                    p.add(download);
                    d.getContentPane().add(p, BorderLayout.SOUTH);
                    d.pack();
                    pleaseWait.dispose();
                    d.setVisible(true);
                }
            });
        }
    });
    skinMenu.addSeparator();
    JMenuItem addSkin = new JMenuItem("Add New...");
    skinMenu.add(addSkin);
    addSkin.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            FileDialog picker = new FileDialog(frm, "Add Skin");
            picker.setMode(FileDialog.LOAD);
            picker.setFilenameFilter(new FilenameFilter() {

                public boolean accept(File file, String string) {
                    return string.endsWith(".skin");
                }
            });
            picker.setModal(true);
            picker.setVisible(true);
            String file = picker.getFile();
            if (file != null) {
                if (netMonitor != null) {
                    netMonitor.dispose();
                    netMonitor = null;
                }
                if (perfMonitor != null) {
                    perfMonitor.dispose();
                    perfMonitor = null;
                }
                String mainClass = System.getProperty("MainClass");
                if (mainClass != null) {
                    Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                    pref.put("skin", picker.getDirectory() + File.separator + file);
                    deinitializeSync();
                    frm.dispose();
                    System.setProperty("reload.simulator", "true");
                } else {
                    loadSkinFile(picker.getDirectory() + File.separator + file, frm);
                    refreshSkin(frm);
                }
            }
        }
    });
    skinMenu.addSeparator();
    JMenuItem reset = new JMenuItem("Reset Skins");
    skinMenu.add(reset);
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            if (JOptionPane.showConfirmDialog(frm, "Are you sure you want to reset skins to default?", "Clean Storage", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
                Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                pref.put("skins", DEFAULT_SKINS);
                String userDir = System.getProperty("user.home");
                final File skinDir = new File(userDir + "/.codenameone/");
                if (skinDir.exists()) {
                    File[] childs = skinDir.listFiles();
                    for (int i = 0; i < childs.length; i++) {
                        File child = childs[i];
                        if (child.getName().endsWith(".skin")) {
                            child.delete();
                        }
                    }
                }
                if (netMonitor != null) {
                    netMonitor.dispose();
                    netMonitor = null;
                }
                if (perfMonitor != null) {
                    perfMonitor.dispose();
                    perfMonitor = null;
                }
                String mainClass = System.getProperty("MainClass");
                if (mainClass != null) {
                    pref.put("skin", DEFAULT_SKIN);
                    deinitializeSync();
                    frm.dispose();
                    System.setProperty("reload.simulator", "true");
                } else {
                    loadSkinFile(DEFAULT_SKIN, frm);
                    refreshSkin(frm);
                }
            }
        }
    });
    return skinMenu;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Node(org.w3c.dom.Node) AttributedString(java.text.AttributedString) Document(org.w3c.dom.Document) Vector(java.util.Vector) NodeList(org.w3c.dom.NodeList) java.util(java.util) DefaultTableModel(javax.swing.table.DefaultTableModel) FilenameFilter(java.io.FilenameFilter) PathIterator(java.awt.geom.PathIterator) Preferences(java.util.prefs.Preferences) java.awt.event(java.awt.event) javax.swing.event(javax.swing.event) TableRowSorter(javax.swing.table.TableRowSorter) NamedNodeMap(org.w3c.dom.NamedNodeMap) BufferedInputStream(com.codename1.io.BufferedInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) AudioInputStream(javax.sound.sampled.AudioInputStream) ZipInputStream(java.util.zip.ZipInputStream) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) LineUnavailableException(javax.sound.sampled.LineUnavailableException) Point(java.awt.Point) StringTokenizer(java.util.StringTokenizer) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileDialog(java.awt.FileDialog)

Aggregations

Cursor (com.codename1.db.Cursor)1 Database (com.codename1.db.Database)1 Row (com.codename1.db.Row)1 BufferedInputStream (com.codename1.io.BufferedInputStream)1 Command (com.codename1.ui.Command)1 FontImage (com.codename1.ui.FontImage)1 Form (com.codename1.ui.Form)1 TextArea (com.codename1.ui.TextArea)1 BorderLayout (com.codename1.ui.layouts.BorderLayout)1 Style (com.codename1.ui.plaf.Style)1 DefaultTableModel (com.codename1.ui.table.DefaultTableModel)1 Table (com.codename1.ui.table.Table)1 Constraint (com.codename1.ui.validation.Constraint)1 FileDialog (java.awt.FileDialog)1 FontFormatException (java.awt.FontFormatException)1 Point (java.awt.Point)1 java.awt.event (java.awt.event)1 PathIterator (java.awt.geom.PathIterator)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 EOFException (java.io.EOFException)1