Search in sources :

Example 1 with ButtonGroup

use of com.codename1.ui.ButtonGroup in project CodenameOne by codenameone.

the class InstantUI method createEditUI.

/**
 * Creates editing UI for the given business object
 * @param bo the business object
 * @param autoCommit true if the bindings used should be auto-committed
 * @return a UI container that can be used to edit the business object
 */
public Container createEditUI(PropertyBusinessObject bo, boolean autoCommit) {
    Container cnt;
    if (Display.getInstance().isTablet()) {
        TableLayout tl = new TableLayout(1, 2);
        tl.setGrowHorizontally(true);
        cnt = new Container(tl);
    } else {
        cnt = new Container(BoxLayout.y());
    }
    UiBinding uib = new UiBinding();
    ArrayList<UiBinding.Binding> allBindings = new ArrayList<UiBinding.Binding>();
    for (PropertyBase b : bo.getPropertyIndex()) {
        if (isExcludedProperty(b)) {
            continue;
        }
        Class cls = (Class) b.getClientProperty("cn1$cmpCls");
        if (cls != null) {
            try {
                Component cmp = (Component) cls.newInstance();
                cmp.setName(b.getName());
                cnt.add(b.getLabel()).add(cmp);
                allBindings.add(uib.bind(b, cmp));
            } catch (Exception err) {
                Log.e(err);
                throw new RuntimeException("Custom property instant UI failed for " + b.getName() + " " + err);
            }
            continue;
        }
        String[] multiLabels = (String[]) b.getClientProperty("cn1$multiChceLbl");
        if (multiLabels != null) {
            // multi choice component
            final Object[] multiValues = (Object[]) b.getClientProperty("cn1$multiChceVal");
            if (multiLabels.length < 5) {
                // toggle buttons
                ButtonGroup bg = new ButtonGroup();
                RadioButton[] rbs = new RadioButton[multiLabels.length];
                cnt.add(b.getLabel());
                Container radioBox = new Container(new GridLayout(multiLabels.length));
                for (int iter = 0; iter < multiLabels.length; iter++) {
                    rbs[iter] = RadioButton.createToggle(multiLabels[iter], bg);
                    radioBox.add(rbs[iter]);
                }
                cnt.add(radioBox);
                allBindings.add(uib.bindGroup(b, multiValues, rbs));
            } else {
                Picker stringPicker = new Picker();
                stringPicker.setStrings(multiLabels);
                Map<Object, Object> m1 = new HashMap<Object, Object>();
                Map<Object, Object> m2 = new HashMap<Object, Object>();
                for (int iter = 0; iter < multiLabels.length; iter++) {
                    m1.put(multiLabels[iter], multiValues[iter]);
                    m2.put(multiValues[iter], multiLabels[iter]);
                }
                cnt.add(b.getLabel()).add(stringPicker);
                allBindings.add(uib.bind(b, stringPicker, new UiBinding.PickerAdapter<Object>(new UiBinding.MappingConverter(m1), new UiBinding.MappingConverter(m2))));
            }
            continue;
        }
        Class t = b.getGenericType();
        if (t != null) {
            if (t == Boolean.class) {
                CheckBox cb = new CheckBox();
                uib.bind(b, cb);
                cnt.add(b.getLabel()).add(cb);
                continue;
            }
            if (t == Date.class) {
                Picker dp = new Picker();
                dp.setType(Display.PICKER_TYPE_DATE);
                uib.bind(b, dp);
                cnt.add(b.getLabel()).add(dp);
                continue;
            }
        }
        TextField tf = new TextField();
        tf.setConstraint(getTextFieldConstraint(b));
        uib.bind(b, tf);
        cnt.add(b.getLabel()).add(tf);
    }
    cnt.putClientProperty("cn1$iui-binding", uib.createGroupBinding(allBindings));
    return cnt;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Container(com.codename1.ui.Container) GridLayout(com.codename1.ui.layouts.GridLayout) Picker(com.codename1.ui.spinner.Picker) TextField(com.codename1.ui.TextField) Component(com.codename1.ui.Component) TableLayout(com.codename1.ui.table.TableLayout) RadioButton(com.codename1.ui.RadioButton) ButtonGroup(com.codename1.ui.ButtonGroup) CheckBox(com.codename1.ui.CheckBox)

Example 2 with ButtonGroup

use of com.codename1.ui.ButtonGroup in project CodenameOne by codenameone.

the class ResourceEditorApp method main.

/**
 * Main method launching the application.
 */
public static void main(String[] args) throws Exception {
    JavaSEPortWithSVGSupport.blockMonitors();
    JavaSEPortWithSVGSupport.setDesignMode(true);
    JavaSEPortWithSVGSupport.setShowEDTWarnings(false);
    JavaSEPortWithSVGSupport.setShowEDTViolationStacks(false);
    // creates a deadlock between FX, Swing and CN1. Horrible horrible deadlock...
    JavaSEPortWithSVGSupport.blockNativeBrowser = true;
    if (args.length > 0) {
        if (args[0].equalsIgnoreCase("-buildVersion")) {
            Properties p = new Properties();
            try {
                p.load(ResourceEditorApp.class.getResourceAsStream("/version.properties"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            System.out.println(p.getProperty("build", "1"));
            System.exit(0);
            return;
        }
        if (args[0].equalsIgnoreCase("-style")) {
            java.awt.Container cnt = new java.awt.Container();
            com.codename1.ui.Display.init(cnt);
            final String uiid = args[2];
            String themeName = args[3];
            boolean isXMLEnabled = Preferences.userNodeForPackage(ResourceEditorView.class).getBoolean("XMLFileMode", true);
            EditableResources.setXMLEnabled(isXMLEnabled);
            EditableResources res = new EditableResources();
            File resourceFile = new File(args[1]);
            res.openFileWithXMLSupport(resourceFile);
            Hashtable themeHash = res.getTheme(themeName);
            final AddThemeEntry entry = new AddThemeEntry(false, res, null, new Hashtable(themeHash), "", themeName);
            entry.setKeyValues(uiid, "");
            entry.setPreferredSize(new Dimension(1000, 600));
            JPanel wrapper = new JPanel(new BorderLayout());
            wrapper.add(entry, BorderLayout.CENTER);
            JPanel bottom = new JPanel();
            ButtonGroup gr = new ButtonGroup();
            JRadioButton unsel = new JRadioButton("Unselected", true);
            gr.add(unsel);
            unsel.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    entry.setPrefix("");
                    entry.setKeyValues(uiid, "");
                    entry.revalidate();
                }
            });
            bottom.add(unsel);
            JRadioButton sel = new JRadioButton("Selected");
            gr.add(sel);
            sel.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    entry.setPrefix("sel#");
                    entry.setKeyValues(uiid, "sel#");
                    entry.revalidate();
                }
            });
            bottom.add(sel);
            JRadioButton press = new JRadioButton("Pressed");
            gr.add(press);
            press.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    entry.setPrefix("press#");
                    entry.setKeyValues(uiid, "press#");
                    entry.revalidate();
                }
            });
            bottom.add(press);
            JRadioButton dis = new JRadioButton("Disabled");
            gr.add(dis);
            dis.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    entry.setPrefix("dis#");
                    entry.setKeyValues(uiid, "dis#");
                    entry.revalidate();
                }
            });
            bottom.add(dis);
            wrapper.add(bottom, BorderLayout.SOUTH);
            if (ModifiableJOptionPane.showConfirmDialog(null, wrapper, "Edit") == JOptionPane.OK_OPTION) {
                Hashtable tmp = new Hashtable(themeHash);
                entry.updateThemeHashtable(tmp);
                res.setTheme(themeName, tmp);
            }
            try (FileOutputStream fos = new FileOutputStream(resourceFile)) {
                res.save(fos);
            }
            res.saveXML(resourceFile);
            System.exit(0);
            return;
        }
        if (args[0].equalsIgnoreCase("-img")) {
            java.awt.Container cnt = new java.awt.Container();
            com.codename1.ui.Display.init(cnt);
            String imageName;
            String fileName;
            if (args.length == 3) {
                imageName = args[2];
                fileName = args[2];
            } else {
                if (args.length == 4) {
                    imageName = args[3];
                    fileName = args[2];
                } else {
                    System.out.println("The img command works as: -img path_to_resourceFile.res pathToImageFile [image name]");
                    System.exit(1);
                    return;
                }
            }
            File imageFile = new File(fileName);
            if (!imageFile.exists()) {
                System.out.println("File not found: " + imageFile.getAbsolutePath());
                System.exit(1);
                return;
            }
            com.codename1.ui.Image img = ImageRGBEditor.createImageStatic(imageFile);
            boolean isXMLEnabled = Preferences.userNodeForPackage(ResourceEditorView.class).getBoolean("XMLFileMode", true);
            EditableResources.setXMLEnabled(isXMLEnabled);
            EditableResources res = new EditableResources();
            File resourceFile = new File(args[1]);
            res.openFileWithXMLSupport(resourceFile);
            res.setImage(imageName, img);
            try (FileOutputStream fos = new FileOutputStream(resourceFile)) {
                res.save(fos);
            }
            res.saveXML(resourceFile);
            System.exit(0);
            return;
        }
        if (args[0].equalsIgnoreCase("-mimg")) {
            java.awt.Container cnt = new java.awt.Container();
            com.codename1.ui.Display.init(cnt);
            String fileName;
            if (args.length == 4) {
                fileName = args[3];
            } else {
                System.out.println("The mimg command works as: -img path_to_resourceFile.res dpi pathToImageFile");
                System.out.println("dpi can be one of:  high, veryhigh, hd, 560, 2hd, 4k");
                System.exit(1);
                return;
            }
            String dpi = args[2];
            int dpiInt = -1;
            switch(dpi.toLowerCase()) {
                case "high":
                    dpiInt = 3;
                    break;
                case "veryhigh":
                    dpiInt = 4;
                    break;
                case "hd":
                    dpiInt = 5;
                    break;
                case "560":
                    dpiInt = 6;
                    break;
                case "2hd":
                    dpiInt = 7;
                    break;
                case "4k":
                    dpiInt = 8;
                    break;
                default:
                    System.out.println("dpi can be one of:  high, veryhigh, hd, 560, 2hd, 4k");
                    System.exit(1);
                    return;
            }
            File imageFile = new File(fileName);
            if (!imageFile.exists()) {
                System.out.println("File not found: " + imageFile.getAbsolutePath());
                System.exit(1);
                return;
            }
            boolean isXMLEnabled = Preferences.userNodeForPackage(ResourceEditorView.class).getBoolean("XMLFileMode", true);
            EditableResources.setXMLEnabled(isXMLEnabled);
            EditableResources res = new EditableResources();
            File resourceFile = new File(args[1]);
            res.openFileWithXMLSupport(resourceFile);
            AddAndScaleMultiImage.generateImpl(new File[] { imageFile }, res, dpiInt);
            try (FileOutputStream fos = new FileOutputStream(resourceFile)) {
                res.save(fos);
            }
            res.saveXML(resourceFile);
            System.exit(0);
            return;
        }
        if (args[0].equalsIgnoreCase("gen")) {
            java.awt.Container cnt = new java.awt.Container();
            com.codename1.ui.Display.init(cnt);
            File output = new File(args[1]);
            generateResourceFile(output, args[2], args[3]);
            System.exit(0);
            return;
        }
        if (args[0].equalsIgnoreCase("mig")) {
            java.awt.Container cnt = new java.awt.Container();
            com.codename1.ui.Display.init(cnt);
            File projectDir = new File(args[1]);
            EditableResources.setXMLEnabled(true);
            EditableResources res = new EditableResources();
            res.openFileWithXMLSupport(new File(args[2]));
            migrateGuiBuilder(projectDir, res, args[3]);
            System.exit(0);
            return;
        }
        if (args[0].equalsIgnoreCase("-regen")) {
            java.awt.Container cnt = new java.awt.Container();
            com.codename1.ui.Display.init(cnt);
            File output = new File(args[1]);
            EditableResources.setXMLEnabled(true);
            EditableResources res = new EditableResources();
            res.openFileWithXMLSupport(output);
            FileOutputStream fos = new FileOutputStream(output);
            res.save(fos);
            fos.close();
            generate(res, output);
            System.exit(0);
            return;
        }
    }
    JavaSEPortWithSVGSupport.setDefaultInitTarget(new JPanel());
    Display.init(null);
    launch(ResourceEditorApp.class, args);
}
Also used : JPanel(javax.swing.JPanel) JRadioButton(javax.swing.JRadioButton) ActionEvent(java.awt.event.ActionEvent) Properties(java.util.Properties) Container(com.codename1.ui.Container) BorderLayout(java.awt.BorderLayout) EditableResources(com.codename1.ui.util.EditableResources) UIBuilderOverride(com.codename1.ui.util.UIBuilderOverride) Hashtable(java.util.Hashtable) IOException(java.io.IOException) Dimension(java.awt.Dimension) ActionListener(java.awt.event.ActionListener) ButtonGroup(javax.swing.ButtonGroup) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 3 with ButtonGroup

use of com.codename1.ui.ButtonGroup in project CodenameOne by codenameone.

the class JavaSEPort method installMenu.

private void installMenu(final JFrame frm, boolean desktopSkin) throws IOException {
    JMenuBar bar = new JMenuBar();
    frm.setJMenuBar(bar);
    JMenu simulatorMenu = new JMenu("Simulate");
    simulatorMenu.setDoubleBuffered(true);
    simulatorMenu.addMenuListener(new MenuListener() {

        @Override
        public void menuSelected(MenuEvent e) {
            menuDisplayed = true;
        }

        @Override
        public void menuCanceled(MenuEvent e) {
            menuDisplayed = false;
        }

        @Override
        public void menuDeselected(MenuEvent e) {
            menuDisplayed = false;
        }
    });
    JMenuItem rotate = new JMenuItem("Rotate");
    rotate.setEnabled(!desktopSkin);
    simulatorMenu.add(rotate);
    final JCheckBoxMenuItem zoomMenu = new JCheckBoxMenuItem("Zoom", scrollableSkin);
    simulatorMenu.add(zoomMenu);
    JMenu debugEdtMenu = new JMenu("Debug EDT");
    simulatorMenu.add(debugEdtMenu);
    zoomMenu.setEnabled(!desktopSkin);
    JRadioButtonMenuItem debugEdtNone = new JRadioButtonMenuItem("None");
    JRadioButtonMenuItem debugEdtLight = new JRadioButtonMenuItem("Light");
    JRadioButtonMenuItem debugEdtFull = new JRadioButtonMenuItem("Full");
    debugEdtMenu.add(debugEdtNone);
    debugEdtMenu.add(debugEdtLight);
    debugEdtMenu.add(debugEdtFull);
    ButtonGroup bg = new ButtonGroup();
    bg.add(debugEdtNone);
    bg.add(debugEdtLight);
    bg.add(debugEdtFull);
    final Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
    int debugEdtSelection = pref.getInt("debugEDTMode", 0);
    switch(debugEdtSelection) {
        case 0:
            debugEdtNone.setSelected(true);
            setShowEDTWarnings(false);
            setShowEDTViolationStacks(false);
            break;
        case 2:
            debugEdtFull.setSelected(true);
            setShowEDTWarnings(true);
            setShowEDTViolationStacks(true);
            break;
        default:
            debugEdtLight.setSelected(true);
            setShowEDTWarnings(true);
            setShowEDTViolationStacks(false);
            break;
    }
    debugEdtNone.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            setShowEDTWarnings(false);
            setShowEDTViolationStacks(false);
            pref.putInt("debugEDTMode", 0);
        }
    });
    debugEdtFull.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            setShowEDTWarnings(true);
            setShowEDTViolationStacks(true);
            pref.putInt("debugEDTMode", 2);
        }
    });
    debugEdtLight.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            setShowEDTWarnings(true);
            setShowEDTViolationStacks(false);
            pref.putInt("debugEDTMode", 1);
        }
    });
    JMenuItem screenshot = new JMenuItem("Screenshot");
    simulatorMenu.add(screenshot);
    KeyStroke f2 = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
    screenshot.setAccelerator(f2);
    screenshot.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            final float zoom = zoomLevel;
            zoomLevel = 1;
            final Form frm = Display.getInstance().getCurrent();
            BufferedImage headerImageTmp;
            if (isPortrait()) {
                headerImageTmp = header;
            } else {
                headerImageTmp = headerLandscape;
            }
            if (!includeHeaderInScreenshot) {
                headerImageTmp = null;
            }
            int headerHeightTmp = 0;
            if (headerImageTmp != null) {
                headerHeightTmp = headerImageTmp.getHeight();
            }
            final int headerHeight = headerHeightTmp;
            final BufferedImage headerImage = headerImageTmp;
            // gr.translate(0, statusBarHeight);
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    final com.codename1.ui.Image img = com.codename1.ui.Image.createImage(frm.getWidth(), frm.getHeight());
                    com.codename1.ui.Graphics gr = img.getGraphics();
                    takingScreenshot = true;
                    screenshotActualZoomLevel = zoom;
                    try {
                        frm.paint(gr);
                    } finally {
                        takingScreenshot = false;
                    }
                    final int imageWidth = img.getWidth();
                    final int imageHeight = img.getHeight();
                    final int[] imageRGB = img.getRGB();
                    SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            BufferedImage bi = new BufferedImage(frm.getWidth(), frm.getHeight() + headerHeight, BufferedImage.TYPE_INT_ARGB);
                            bi.setRGB(0, headerHeight, imageWidth, imageHeight, imageRGB, 0, imageWidth);
                            if (headerImage != null) {
                                Graphics2D g2d = bi.createGraphics();
                                g2d.drawImage(headerImage, 0, 0, null);
                                g2d.dispose();
                            }
                            OutputStream out = null;
                            try {
                                out = new FileOutputStream(findScreenshotFile());
                                ImageIO.write(bi, "png", out);
                                out.close();
                            } catch (Throwable ex) {
                                ex.printStackTrace();
                                System.exit(1);
                            } finally {
                                zoomLevel = zoom;
                                try {
                                    out.close();
                                } catch (Throwable ex) {
                                }
                                frm.repaint();
                                canvas.repaint();
                            }
                        }
                    });
                }
            });
        }
    });
    JMenuItem screenshotWithSkin = new JMenuItem("Screenshot With Skin");
    simulatorMenu.add(screenshotWithSkin);
    screenshotWithSkin.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final float zoom = zoomLevel;
            zoomLevel = 1;
            final Form frm = Display.getInstance().getCurrent();
            BufferedImage headerImageTmp;
            if (isPortrait()) {
                headerImageTmp = header;
            } else {
                headerImageTmp = headerLandscape;
            }
            if (!includeHeaderInScreenshot) {
                headerImageTmp = null;
            }
            int headerHeightTmp = 0;
            if (headerImageTmp != null) {
                headerHeightTmp = headerImageTmp.getHeight();
            }
            final int headerHeight = headerHeightTmp;
            final BufferedImage headerImage = headerImageTmp;
            // gr.translate(0, statusBarHeight);
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    final com.codename1.ui.Image img = com.codename1.ui.Image.createImage(frm.getWidth(), frm.getHeight());
                    com.codename1.ui.Graphics gr = img.getGraphics();
                    takingScreenshot = true;
                    screenshotActualZoomLevel = zoom;
                    try {
                        frm.paint(gr);
                    } finally {
                        takingScreenshot = false;
                    }
                    final int imageWidth = img.getWidth();
                    final int imageHeight = img.getHeight();
                    final int[] imageRGB = img.getRGB();
                    SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            BufferedImage bi = new BufferedImage(frm.getWidth(), frm.getHeight() + headerHeight, BufferedImage.TYPE_INT_ARGB);
                            bi.setRGB(0, headerHeight, imageWidth, imageHeight, imageRGB, 0, imageWidth);
                            BufferedImage skin = getSkin();
                            BufferedImage newSkin = new BufferedImage(skin.getWidth(), skin.getHeight(), BufferedImage.TYPE_INT_ARGB);
                            Graphics2D g2d = newSkin.createGraphics();
                            g2d.drawImage(bi, getScreenCoordinates().x, getScreenCoordinates().y, null);
                            if (headerImage != null) {
                                g2d.drawImage(headerImage, getScreenCoordinates().x, getScreenCoordinates().y, null);
                            }
                            g2d.drawImage(skin, 0, 0, null);
                            g2d.dispose();
                            OutputStream out = null;
                            try {
                                out = new FileOutputStream(findScreenshotFile());
                                ImageIO.write(newSkin, "png", out);
                                out.close();
                            } catch (Throwable ex) {
                                ex.printStackTrace();
                                System.exit(1);
                            } finally {
                                zoomLevel = zoom;
                                try {
                                    out.close();
                                } catch (Throwable ex) {
                                }
                                frm.repaint();
                                canvas.repaint();
                            }
                        }
                    });
                }
            });
        }
    });
    includeHeaderInScreenshot = pref.getBoolean("includeHeaderScreenshot", true);
    final JCheckBoxMenuItem includeHeaderMenu = new JCheckBoxMenuItem("Screenshot StatusBar");
    includeHeaderMenu.setToolTipText("Include status bar area in Screenshots");
    includeHeaderMenu.setSelected(includeHeaderInScreenshot);
    simulatorMenu.add(includeHeaderMenu);
    includeHeaderMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            includeHeaderInScreenshot = includeHeaderMenu.isSelected();
            pref.putBoolean("includeHeaderScreenshot", includeHeaderInScreenshot);
        }
    });
    JMenu networkDebug = new JMenu("Network");
    simulatorMenu.add(networkDebug);
    JMenuItem networkMonitor = new JMenuItem("Network Monitor");
    networkMonitor.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (netMonitor == null) {
                showNetworkMonitor();
                Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                pref.putBoolean("NetworkMonitor", true);
            }
        }
    });
    networkDebug.add(networkMonitor);
    JMenuItem proxy = new JMenuItem("Proxy Settings");
    proxy.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            final JDialog proxy;
            if (window != null) {
                proxy = new JDialog(window);
            } else {
                proxy = new JDialog();
            }
            final Preferences pref = Preferences.userNodeForPackage(Component.class);
            int proxySel = pref.getInt("proxySel", 2);
            String proxySelHttp = pref.get("proxySel-http", "");
            String proxySelPort = pref.get("proxySel-port", "");
            JPanel panel = new JPanel();
            panel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            JPanel proxyUrl = new JPanel();
            proxyUrl.setLayout(new FlowLayout(FlowLayout.LEFT));
            proxyUrl.add(new JLabel("Http Proxy:"));
            final JTextField http = new JTextField(proxySelHttp);
            http.setColumns(20);
            proxyUrl.add(http);
            proxyUrl.add(new JLabel("Port:"));
            final JTextField port = new JTextField(proxySelPort);
            port.setColumns(4);
            proxyUrl.add(port);
            final JRadioButton noproxy = new JRadioButton("No Proxy");
            JPanel rbPanel = new JPanel();
            rbPanel.setLayout(new java.awt.GridLayout(1, 0));
            rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            rbPanel.add(noproxy);
            Dimension d = rbPanel.getPreferredSize();
            d.width = proxyUrl.getPreferredSize().width;
            rbPanel.setMinimumSize(d);
            // noproxy.setPreferredSize(d);
            panel.add(rbPanel);
            final JRadioButton systemProxy = new JRadioButton("Use System Proxy");
            rbPanel = new JPanel();
            rbPanel.setLayout(new java.awt.GridLayout(1, 0));
            rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            rbPanel.add(systemProxy);
            d = rbPanel.getPreferredSize();
            d.width = proxyUrl.getPreferredSize().width;
            rbPanel.setPreferredSize(d);
            panel.add(rbPanel);
            final JRadioButton manual = new JRadioButton("Manual Proxy Settings:");
            rbPanel = new JPanel();
            rbPanel.setLayout(new java.awt.GridLayout(1, 0));
            rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            rbPanel.add(manual);
            d = rbPanel.getPreferredSize();
            d.width = proxyUrl.getPreferredSize().width;
            rbPanel.setPreferredSize(d);
            panel.add(rbPanel);
            rbPanel = new JPanel();
            rbPanel.setLayout(new java.awt.GridLayout(1, 0));
            rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            rbPanel.add(proxyUrl);
            panel.add(rbPanel);
            ButtonGroup group = new ButtonGroup();
            group.add(noproxy);
            group.add(systemProxy);
            group.add(manual);
            noproxy.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    http.setEnabled(false);
                    port.setEnabled(false);
                }
            });
            systemProxy.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    http.setEnabled(false);
                    port.setEnabled(false);
                }
            });
            manual.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    http.setEnabled(true);
                    port.setEnabled(true);
                }
            });
            switch(proxySel) {
                case 1:
                    noproxy.setSelected(true);
                    http.setEnabled(false);
                    port.setEnabled(false);
                    break;
                case 2:
                    systemProxy.setSelected(true);
                    http.setEnabled(false);
                    port.setEnabled(false);
                    break;
                case 3:
                    manual.setSelected(true);
                    break;
            }
            JPanel closePanel = new JPanel();
            JButton close = new JButton("Ok");
            close.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    if (noproxy.isSelected()) {
                        pref.putInt("proxySel", 1);
                    } else if (systemProxy.isSelected()) {
                        pref.putInt("proxySel", 2);
                    } else if (manual.isSelected()) {
                        pref.putInt("proxySel", 3);
                        pref.put("proxySel-http", http.getText());
                        pref.put("proxySel-port", port.getText());
                    }
                    proxy.dispose();
                    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);
                        deinitializeSync();
                        frm.dispose();
                        System.setProperty("reload.simulator", "true");
                    } else {
                        refreshSkin(frm);
                    }
                }
            });
            closePanel.add(close);
            panel.add(closePanel);
            proxy.add(panel);
            proxy.pack();
            if (window != null) {
                proxy.setLocationRelativeTo(window);
            }
            proxy.setResizable(false);
            proxy.setVisible(true);
        }
    });
    networkDebug.add(proxy);
    networkDebug.addSeparator();
    JRadioButtonMenuItem regularConnection = new JRadioButtonMenuItem("Regular Connection");
    regularConnection.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            slowConnectionMode = false;
            disconnectedMode = false;
            pref.putInt("connectionStatus", 0);
        }
    });
    networkDebug.add(regularConnection);
    JRadioButtonMenuItem slowConnection = new JRadioButtonMenuItem("Slow Connection");
    slowConnection.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            slowConnectionMode = true;
            disconnectedMode = false;
            pref.putInt("connectionStatus", 1);
        }
    });
    networkDebug.add(slowConnection);
    JRadioButtonMenuItem disconnected = new JRadioButtonMenuItem("Disconnected");
    disconnected.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            slowConnectionMode = false;
            disconnectedMode = true;
            pref.putInt("connectionStatus", 2);
        }
    });
    networkDebug.add(disconnected);
    ButtonGroup connectionGroup = new ButtonGroup();
    connectionGroup.add(regularConnection);
    connectionGroup.add(slowConnection);
    connectionGroup.add(disconnected);
    switch(pref.getInt("connectionStatus", 0)) {
        case 0:
            regularConnection.setSelected(true);
            break;
        case 1:
            slowConnection.setSelected(true);
            slowConnectionMode = true;
            break;
        case 2:
            disconnected.setSelected(true);
            disconnectedMode = true;
            break;
    }
    JMenuItem componentTreeInspector = new JMenuItem("Component Inspector");
    componentTreeInspector.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            new ComponentTreeInspector();
        }
    });
    JMenuItem locactionSim = new JMenuItem("Location Simulation");
    locactionSim.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (!fxExists) {
                System.err.println("This simulation requires jdk 7");
                return;
            }
            if (locSimulation == null) {
                locSimulation = new LocationSimulation();
            } else {
                locSimulation.setVisible(true);
            }
        }
    });
    simulatorMenu.add(locactionSim);
    JMenuItem pushSim = new JMenuItem("Push Simulation");
    pushSim.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (pushSimulation == null) {
                pushSimulation = new PushSimulator();
            }
            pref.putBoolean("PushSimulator", true);
            pushSimulation.setVisible(true);
        }
    });
    simulatorMenu.add(pushSim);
    simulatorMenu.add(componentTreeInspector);
    JMenuItem testRecorderMenu = new JMenuItem("Test Recorder");
    testRecorderMenu.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (testRecorder == null) {
                showTestRecorder();
            }
        }
    });
    simulatorMenu.add(testRecorderMenu);
    manualPurchaseSupported = pref.getBoolean("manualPurchaseSupported", true);
    managedPurchaseSupported = pref.getBoolean("managedPurchaseSupported", true);
    subscriptionSupported = pref.getBoolean("subscriptionSupported", true);
    refundSupported = pref.getBoolean("refundSupported", true);
    JMenu purchaseMenu = new JMenu("In App Purchase");
    simulatorMenu.add(purchaseMenu);
    final JCheckBoxMenuItem manualPurchaseSupportedMenu = new JCheckBoxMenuItem("Manual Purchase");
    manualPurchaseSupportedMenu.setSelected(manualPurchaseSupported);
    final JCheckBoxMenuItem managedPurchaseSupportedMenu = new JCheckBoxMenuItem("Managed Purchase");
    managedPurchaseSupportedMenu.setSelected(managedPurchaseSupported);
    final JCheckBoxMenuItem subscriptionSupportedMenu = new JCheckBoxMenuItem("Subscription");
    subscriptionSupportedMenu.setSelected(subscriptionSupported);
    final JCheckBoxMenuItem refundSupportedMenu = new JCheckBoxMenuItem("Refunds");
    refundSupportedMenu.setSelected(refundSupported);
    manualPurchaseSupportedMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            manualPurchaseSupported = manualPurchaseSupportedMenu.isSelected();
            pref.putBoolean("manualPurchaseSupported", manualPurchaseSupported);
        }
    });
    managedPurchaseSupportedMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            managedPurchaseSupported = managedPurchaseSupportedMenu.isSelected();
            pref.putBoolean("managedPurchaseSupported", managedPurchaseSupported);
        }
    });
    subscriptionSupportedMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            subscriptionSupported = subscriptionSupportedMenu.isSelected();
            pref.putBoolean("subscriptionSupported", subscriptionSupported);
        }
    });
    refundSupportedMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            refundSupported = refundSupportedMenu.isSelected();
            pref.putBoolean("refundSupported", refundSupported);
        }
    });
    purchaseMenu.add(manualPurchaseSupportedMenu);
    purchaseMenu.add(managedPurchaseSupportedMenu);
    purchaseMenu.add(subscriptionSupportedMenu);
    purchaseMenu.add(refundSupportedMenu);
    JMenuItem performanceMonitor = new JMenuItem("Performance Monitor");
    performanceMonitor.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (perfMonitor == null) {
                showPerformanceMonitor();
                Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                pref.putBoolean("PerformanceMonitor", true);
            }
        }
    });
    simulatorMenu.add(performanceMonitor);
    JMenuItem clean = new JMenuItem("Clean Storage");
    clean.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            File home = new File(System.getProperty("user.home") + File.separator + appHomeDir);
            if (!home.exists()) {
                return;
            }
            if (JOptionPane.showConfirmDialog(frm, "Are you sure you want to Clean all Storage under " + home.getAbsolutePath() + " ?", "Clean Storage", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
                File[] files = home.listFiles();
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];
                    file.delete();
                }
            }
        }
    });
    simulatorMenu.add(clean);
    JMenu skinMenu = createSkinsMenu(frm, null);
    skinMenu.addMenuListener(new MenuListener() {

        @Override
        public void menuSelected(MenuEvent e) {
            menuDisplayed = true;
        }

        @Override
        public void menuCanceled(MenuEvent e) {
            menuDisplayed = false;
        }

        @Override
        public void menuDeselected(MenuEvent e) {
            menuDisplayed = false;
        }
    });
    final JCheckBoxMenuItem touchFlag = new JCheckBoxMenuItem("Touch", touchDevice);
    simulatorMenu.add(touchFlag);
    final JCheckBoxMenuItem nativeInputFlag = new JCheckBoxMenuItem("Native Input", useNativeInput);
    simulatorMenu.add(nativeInputFlag);
    final JCheckBoxMenuItem simulateAndroidVKBFlag = new JCheckBoxMenuItem("Simulate Android VKB", simulateAndroidKeyboard);
    // simulatorMenu.add(simulateAndroidVKBFlag);
    final JCheckBoxMenuItem scrollFlag = new JCheckBoxMenuItem("Scrollable", scrollableSkin);
    simulatorMenu.add(scrollFlag);
    scrollFlag.setEnabled(!desktopSkin);
    final JCheckBoxMenuItem slowMotionFlag = new JCheckBoxMenuItem("Slow Motion", false);
    simulatorMenu.add(slowMotionFlag);
    slowMotionFlag.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Motion.setSlowMotion(slowMotionFlag.isSelected());
        }
    });
    final JCheckBoxMenuItem permFlag = new JCheckBoxMenuItem("Android 6 Permissions", android6PermissionsFlag);
    simulatorMenu.add(permFlag);
    permFlag.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            android6PermissionsFlag = !android6PermissionsFlag;
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("Android6Permissions", android6PermissionsFlag);
        }
    });
    pause = new JMenuItem("Pause App");
    simulatorMenu.add(pause);
    pause.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (pause.getText().startsWith("Pause")) {
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        Executor.stopApp();
                        minimized = true;
                    }
                });
                canvas.setEnabled(false);
                pause.setText("Resume App");
            } else {
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        Executor.startApp();
                        minimized = false;
                    }
                });
                canvas.setEnabled(true);
                pause.setText("Pause App");
            }
        }
    });
    final JCheckBoxMenuItem alwaysOnTopFlag = new JCheckBoxMenuItem("Always on Top", alwaysOnTop);
    simulatorMenu.add(alwaysOnTopFlag);
    simulatorMenu.addSeparator();
    JMenuItem exit = new JMenuItem("Exit");
    simulatorMenu.add(exit);
    JMenu helpMenu = new JMenu("Help");
    helpMenu.setDoubleBuffered(true);
    helpMenu.addMenuListener(new MenuListener() {

        @Override
        public void menuSelected(MenuEvent e) {
            menuDisplayed = true;
        }

        @Override
        public void menuCanceled(MenuEvent e) {
            menuDisplayed = false;
        }

        @Override
        public void menuDeselected(MenuEvent e) {
            menuDisplayed = false;
        }
    });
    JMenuItem javadocs = new JMenuItem("Javadocs");
    javadocs.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI("https://www.codenameone.com/javadoc/"));
            } catch (Exception ex) {
            }
        }
    });
    helpMenu.add(javadocs);
    JMenuItem how = new JMenuItem("How Do I?...");
    how.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI("https://www.codenameone.com/how-do-i.html"));
            } catch (Exception ex) {
            }
        }
    });
    helpMenu.add(how);
    JMenuItem forum = new JMenuItem("Community Forum");
    forum.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI("https://www.codenameone.com/discussion-forum.html"));
            } catch (Exception ex) {
            }
        }
    });
    helpMenu.add(forum);
    JMenuItem bserver = new JMenuItem("Build Server");
    bserver.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI("https://www.codenameone.com/build-server.html"));
            } catch (Exception ex) {
            }
        }
    });
    helpMenu.addSeparator();
    helpMenu.add(bserver);
    helpMenu.addSeparator();
    JMenuItem about = new JMenuItem("About");
    about.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            final JDialog about;
            if (window != null) {
                about = new JDialog(window);
            } else {
                about = new JDialog();
            }
            JPanel panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            JPanel imagePanel = new JPanel();
            JLabel image = new JLabel(new javax.swing.ImageIcon(getClass().getResource("/CodenameOne_Small.png")));
            image.setHorizontalAlignment(SwingConstants.CENTER);
            imagePanel.add(image);
            panel.add(imagePanel);
            JPanel linkPanel = new JPanel();
            JButton link = new JButton();
            link.setText("<HTML>For more information, please <br>visit <FONT color=\"#000099\"><U>www.codenameone.com</U></FONT></HTML>");
            link.setHorizontalAlignment(SwingConstants.LEFT);
            link.setBorderPainted(false);
            link.setOpaque(false);
            link.setBackground(Color.WHITE);
            link.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    try {
                        Desktop.getDesktop().browse(new URI("https://www.codenameone.com"));
                    } catch (Exception ex) {
                    }
                }
            });
            linkPanel.add(link);
            panel.add(linkPanel);
            JPanel closePanel = new JPanel();
            JButton close = new JButton("close");
            close.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    about.dispose();
                }
            });
            closePanel.add(close);
            panel.add(closePanel);
            about.add(panel);
            about.pack();
            if (window != null) {
                about.setLocationRelativeTo(window);
            }
            about.setVisible(true);
        }
    });
    helpMenu.add(about);
    if (showMenu) {
        bar.add(simulatorMenu);
        bar.add(skinMenu);
        bar.add(helpMenu);
    }
    rotate.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            portrait = !portrait;
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("Portrait", portrait);
            float w1 = ((float) canvas.getWidth()) / ((float) getSkin().getWidth() / (float) retinaScale);
            float h1 = ((float) canvas.getHeight()) / ((float) getSkin().getHeight() / (float) retinaScale);
            zoomLevel = Math.min(h1, w1);
            Container parent = canvas.getParent();
            parent.remove(canvas);
            canvas.setForcedSize(new java.awt.Dimension((int) (getSkin().getWidth() / retinaScale), (int) (getSkin().getHeight() / retinaScale)));
            parent.add(BorderLayout.CENTER, canvas);
            frm.pack();
            zoomLevel = 1;
            JavaSEPort.this.sizeChanged(getScreenCoordinates().width, getScreenCoordinates().height);
        }
    });
    alwaysOnTopFlag.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent ie) {
            alwaysOnTop = !alwaysOnTop;
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("AlwaysOnTop", alwaysOnTop);
            window.setAlwaysOnTop(alwaysOnTop);
        }
    });
    simulateAndroidVKBFlag.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent ie) {
            simulateAndroidKeyboard = !simulateAndroidKeyboard;
        }
    });
    ItemListener zoomListener = new ItemListener() {

        public void itemStateChanged(ItemEvent ie) {
            scrollableSkin = !scrollableSkin;
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("Scrollable", scrollableSkin);
            if (scrollableSkin) {
                frm.add(java.awt.BorderLayout.SOUTH, hSelector);
                frm.add(java.awt.BorderLayout.EAST, vSelector);
            } else {
                frm.remove(hSelector);
                frm.remove(vSelector);
            }
            Container parent = canvas.getParent();
            parent.remove(canvas);
            canvas.setForcedSize(new java.awt.Dimension((int) (getSkin().getWidth() / retinaScale), (int) (getSkin().getHeight() / retinaScale)));
            parent.add(BorderLayout.CENTER, canvas);
            canvas.x = 0;
            canvas.y = 0;
            zoomLevel = 1;
            frm.invalidate();
            frm.pack();
            Display.getInstance().getCurrent().repaint();
            frm.repaint();
        }
    };
    zoomMenu.addItemListener(zoomListener);
    scrollFlag.addItemListener(zoomListener);
    exit.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            exitApplication();
        }
    });
}
Also used : ActionEvent(java.awt.event.ActionEvent) BufferedOutputStream(com.codename1.io.BufferedOutputStream) Graphics(com.codename1.ui.Graphics) Dimension(java.awt.Dimension) ActionListener(java.awt.event.ActionListener) ItemEvent(java.awt.event.ItemEvent) Form(com.codename1.ui.Form) MenuListener(javax.swing.event.MenuListener) URI(java.net.URI) BufferedImage(java.awt.image.BufferedImage) Preferences(java.util.prefs.Preferences) BrowserComponent(com.codename1.ui.BrowserComponent) Component(com.codename1.ui.Component) JTextComponent(javax.swing.text.JTextComponent) PeerComponent(com.codename1.ui.PeerComponent) MenuEvent(javax.swing.event.MenuEvent) Image(com.codename1.ui.Image) Dimension(java.awt.Dimension) Point(java.awt.Point) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) Graphics2D(java.awt.Graphics2D) ItemListener(java.awt.event.ItemListener) java.awt(java.awt)

Example 4 with ButtonGroup

use of com.codename1.ui.ButtonGroup 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("/iphone3gs.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);
                        deinitializeSync();
                        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);
            String mainClass = System.getProperty("MainClass");
            if (mainClass != null) {
                deinitializeSync();
                frm.dispose();
                System.setProperty("reload.simulator", "true");
            }
        }
    });
    skinMenu.addSeparator();
    skinMenu.add(dSkin);
    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.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);
                    d.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.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", "/iphone3gs.skin");
                    deinitializeSync();
                    frm.dispose();
                    System.setProperty("reload.simulator", "true");
                } else {
                    loadSkinFile("/iphone3gs.skin", frm);
                    refreshSkin(frm);
                }
            }
        }
    });
    return skinMenu;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ActionEvent(java.awt.event.ActionEvent) Node(org.w3c.dom.Node) DefaultTableModel(javax.swing.table.DefaultTableModel) Document(org.w3c.dom.Document) FilenameFilter(java.io.FilenameFilter) PathIterator(java.awt.geom.PathIterator) Preferences(java.util.prefs.Preferences) Vector(java.util.Vector) NamedNodeMap(org.w3c.dom.NamedNodeMap) BufferedInputStream(com.codename1.io.BufferedInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) NodeList(org.w3c.dom.NodeList) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) Point(java.awt.Point) StringTokenizer(java.util.StringTokenizer) ActionListener(java.awt.event.ActionListener) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileDialog(java.awt.FileDialog)

Example 5 with ButtonGroup

use of com.codename1.ui.ButtonGroup in project CodenameOne by codenameone.

the class HTMLForm method addRadioButton.

/**
 * Adds the specified RadioButton to the form.
 * Note that unlike adding to a Codename One form here the components are added logically only to query them for their value on submit.
 *
 * @param key The CheckBox's name/id
 * @param rb The RadioButton to add
 * @param value The value of the checkbox
 */
void addRadioButton(String key, RadioButton rb, String value) {
    if (rb.isSelected()) {
        defaultCheckedButtons.addElement(rb);
    } else {
        defaultUncheckedButtons.addElement(rb);
    }
    if (key == null) {
        // no id
        return;
    }
    Hashtable internal = (Hashtable) comps.get(key);
    ButtonGroup group = null;
    if (internal == null) {
        internal = new Hashtable();
        comps.put(key, internal);
        group = new ButtonGroup();
        buttonGroups.put(key, group);
    } else {
        group = (ButtonGroup) buttonGroups.get(key);
    }
    group.add(rb);
    internal.put(rb, value);
}
Also used : ButtonGroup(com.codename1.ui.ButtonGroup) Hashtable(java.util.Hashtable)

Aggregations

ActionEvent (java.awt.event.ActionEvent)3 ActionListener (java.awt.event.ActionListener)3 ButtonGroup (com.codename1.ui.ButtonGroup)2 Component (com.codename1.ui.Component)2 Container (com.codename1.ui.Container)2 Dimension (java.awt.Dimension)2 FontFormatException (java.awt.FontFormatException)2 Point (java.awt.Point)2 EOFException (java.io.EOFException)2 SQLException (java.sql.SQLException)2 ParseException (java.text.ParseException)2 Hashtable (java.util.Hashtable)2 Preferences (java.util.prefs.Preferences)2 BufferedInputStream (com.codename1.io.BufferedInputStream)1 BufferedOutputStream (com.codename1.io.BufferedOutputStream)1 BrowserComponent (com.codename1.ui.BrowserComponent)1 CheckBox (com.codename1.ui.CheckBox)1 Form (com.codename1.ui.Form)1 Graphics (com.codename1.ui.Graphics)1 Image (com.codename1.ui.Image)1