Example usage for javax.swing JComponent JComponent

List of usage examples for javax.swing JComponent JComponent

Introduction

In this page you can find the example usage for javax.swing JComponent JComponent.

Prototype

public JComponent() 

Source Link

Document

Default JComponent constructor.

Usage

From source file:Main.java

public static void main(String args[]) {
    JFrame f = new JFrame();
    f.add(new JComponent() {
        public void paintComponent(Graphics g) {

            // Some parameters.
            String text = "Some Label";
            int centerX = 150, centerY = 100;
            int ovalWidth = 200, ovalHeight = 100;

            // Draw oval
            g.setColor(Color.BLUE);
            g.fillOval(centerX - ovalWidth / 2, centerY - ovalHeight / 2, ovalWidth, ovalHeight);

            // Draw centered text
            FontMetrics fm = g.getFontMetrics();
            double textWidth = fm.getStringBounds(text, g).getWidth();
            g.setColor(Color.WHITE);
            g.drawString(text, (int) (centerX - textWidth / 2), (int) (centerY + fm.getMaxAscent() / 2));

        }//from   w  w w . ja v a  2  s .  c  om
    });

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(300, 300);
    f.setVisible(true);
}

From source file:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(//  ww  w . j  a v a2 s  . com
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}

From source file:com.oculusinfo.ml.spark.unsupervised.TestDPMeans.java

/**
 * @param args//from w  ww. j a  v a 2s . c o  m
 */
public static void main(String[] args) {
    int k = 5;

    try {
        FileUtils.deleteDirectory(new File("output/clusters"));
        FileUtils.deleteDirectory(new File("output/centroids"));
    } catch (IOException e1) {
        /* ignore (*/ }

    genTestData(k);

    JavaSparkContext sc = new JavaSparkContext("local", "OculusML");
    SparkDataSet ds = new SparkDataSet(sc);
    ds.load("test.txt", new InstanceParser());

    DPMeansClusterer clusterer = new DPMeansClusterer(80, 10, 0.001);
    clusterer.setOutputPaths("output/centroids", "output/clusters");

    clusterer.registerFeatureType("point", MeanNumericVectorCentroid.class, new EuclideanDistance(1.0));

    clusterer.doCluster(ds);

    try {
        final List<double[]> instances = readInstances();

        final Color[] colors = { Color.red, Color.blue, Color.green, Color.magenta, Color.yellow, Color.black,
                Color.orange, Color.cyan, Color.darkGray, Color.white };

        TestDPMeans t = new TestDPMeans();
        t.add(new JComponent() {
            private static final long serialVersionUID = 7920802321066846416L;

            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                for (double[] inst : instances) {
                    int color = (int) inst[0];
                    g.setColor(colors[color]);

                    Ellipse2D l = new Ellipse2D.Double(inst[1], inst[2], 5, 5);
                    g2.draw(l);
                }
            }
        });

        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(400, 400);
        t.setVisible(true);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.oculusinfo.ml.spark.unsupervised.TestThresholdClusterer.java

/**
 * @param args//from  w w  w  .ja va  2s .c  o  m
 */
public static void main(String[] args) {
    int k = 5;

    try {
        FileUtils.deleteDirectory(new File("output/clusters"));
        FileUtils.deleteDirectory(new File("output/centroids"));
    } catch (IOException e1) {
        /* ignore (*/ }

    genTestData(k);

    JavaSparkContext sc = new JavaSparkContext("local", "OculusML");
    SparkDataSet ds = new SparkDataSet(sc);
    ds.load("test.txt", new InstanceParser());

    ThresholdClusterer clusterer = new ThresholdClusterer(80);
    clusterer.setOutputPaths("output/centroids", "output/clusters");

    clusterer.registerFeatureType("point", MeanNumericVectorCentroid.class, new EuclideanDistance(1.0));

    clusterer.doCluster(ds);

    try {
        final List<double[]> instances = readInstances();

        final Color[] colors = { Color.red, Color.blue, Color.green, Color.magenta, Color.yellow, Color.black,
                Color.orange, Color.cyan, Color.darkGray, Color.white };

        TestThresholdClusterer t = new TestThresholdClusterer();
        t.add(new JComponent() {
            private static final long serialVersionUID = -5597119848880912541L;

            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                for (double[] inst : instances) {
                    int color = (int) inst[0];
                    g.setColor(colors[color]);

                    Ellipse2D l = new Ellipse2D.Double(inst[1], inst[2], 5, 5);
                    g2.draw(l);
                }
            }
        });

        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(400, 400);
        t.setVisible(true);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.oculusinfo.ml.spark.unsupervised.TestKMeans.java

/**
 * @param args//from  w  w  w.ja  va2  s . c  om
 */
public static void main(String[] args) {
    int k = 5;

    try {
        FileUtils.deleteDirectory(new File("output/clusters"));
        FileUtils.deleteDirectory(new File("output/centroids"));
    } catch (IOException e1) {
        /* ignore (*/ }

    genTestData(k);

    JavaSparkContext sc = new JavaSparkContext("local", "OculusML");
    SparkDataSet ds = new SparkDataSet(sc);
    ds.load("test.txt", new SparkInstanceParser() {
        private static final long serialVersionUID = 1L;

        @Override
        public Tuple2<String, Instance> call(String line) throws Exception {
            Instance inst = new Instance();

            String tokens[] = line.split(",");

            NumericVectorFeature v = new NumericVectorFeature("point");

            double x = Double.parseDouble(tokens[0]);
            double y = Double.parseDouble(tokens[1]);
            v.setValue(new double[] { x, y });

            inst.addFeature(v);

            return new Tuple2<String, Instance>(inst.getId(), inst);
        }
    });

    KMeansClusterer clusterer = new KMeansClusterer(k, 10, 0.001, "output/centroids", "output/clusters");

    clusterer.registerFeatureType("point", MeanNumericVectorCentroid.class, new EuclideanDistance(1.0));

    clusterer.doCluster(ds);

    try {
        final List<double[]> instances = readInstances();

        final Color[] colors = { Color.red, Color.blue, Color.green, Color.magenta, Color.yellow, Color.black,
                Color.orange, Color.cyan, Color.darkGray, Color.white };

        TestKMeans t = new TestKMeans();
        t.add(new JComponent() {
            private static final long serialVersionUID = 2059497051387104848L;

            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                for (double[] inst : instances) {
                    int color = (int) inst[0];
                    g.setColor(colors[color]);

                    Ellipse2D l = new Ellipse2D.Double(inst[1], inst[2], 5, 5);
                    g2.draw(l);
                }
            }
        });

        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(400, 400);
        t.setVisible(true);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:Main.java

Main() {
    getRootPane().setGlassPane(new JComponent() {
        public void paintComponent(Graphics g) {
            g.setColor(new Color(0, 0, 0, 100));
            g.fillRect(0, 0, getWidth(), getHeight());
            super.paintComponent(g);
        }//from  w w w.jav a  2s. c  om
    });
    JButton popDialog = new JButton("Block Frame");
    popDialog.addActionListener(e -> {
        getRootPane().getGlassPane().setVisible(true);
        JOptionPane.showMessageDialog(Main.this, "Shady!");
        getRootPane().getGlassPane().setVisible(false);
    });
    setContentPane(popDialog);
    pack();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setSize(350, 180);
}

From source file:ImageProcessingTest.java

public ImageProcessingFrame() {
    setTitle("ImageProcessingTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    add(new JComponent() {
        public void paintComponent(Graphics g) {
            if (image != null)
                g.drawImage(image, 0, 0, null);
        }/* ww w. j ava 2 s .  c  o m*/
    });

    JMenu fileMenu = new JMenu("File");
    JMenuItem openItem = new JMenuItem("Open");
    openItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            openFile();
        }
    });
    fileMenu.add(openItem);

    JMenuItem exitItem = new JMenuItem("Exit");
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
        }
    });
    fileMenu.add(exitItem);

    JMenu editMenu = new JMenu("Edit");
    JMenuItem blurItem = new JMenuItem("Blur");
    blurItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            float weight = 1.0f / 9.0f;
            float[] elements = new float[9];
            for (int i = 0; i < 9; i++)
                elements[i] = weight;
            convolve(elements);
        }
    });
    editMenu.add(blurItem);

    JMenuItem sharpenItem = new JMenuItem("Sharpen");
    sharpenItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            float[] elements = { 0.0f, -1.0f, 0.0f, -1.0f, 5.f, -1.0f, 0.0f, -1.0f, 0.0f };
            convolve(elements);
        }
    });
    editMenu.add(sharpenItem);

    JMenuItem brightenItem = new JMenuItem("Brighten");
    brightenItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            float a = 1.1f;
            // float b = 20.0f;
            float b = 0;
            RescaleOp op = new RescaleOp(a, b, null);
            filter(op);
        }
    });
    editMenu.add(brightenItem);

    JMenuItem edgeDetectItem = new JMenuItem("Edge detect");
    edgeDetectItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            float[] elements = { 0.0f, -1.0f, 0.0f, -1.0f, 4.f, -1.0f, 0.0f, -1.0f, 0.0f };
            convolve(elements);
        }
    });
    editMenu.add(edgeDetectItem);

    JMenuItem negativeItem = new JMenuItem("Negative");
    negativeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            short[] negative = new short[256 * 1];
            for (int i = 0; i < 256; i++)
                negative[i] = (short) (255 - i);
            ShortLookupTable table = new ShortLookupTable(0, negative);
            LookupOp op = new LookupOp(table, null);
            filter(op);
        }
    });
    editMenu.add(negativeItem);

    JMenuItem rotateItem = new JMenuItem("Rotate");
    rotateItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (image == null)
                return;
            AffineTransform transform = AffineTransform.getRotateInstance(Math.toRadians(5),
                    image.getWidth() / 2, image.getHeight() / 2);
            AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);
            filter(op);
        }
    });
    editMenu.add(rotateItem);

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fileMenu);
    menuBar.add(editMenu);
    setJMenuBar(menuBar);
}

From source file:SimpleAuthenticator.java

protected PasswordAuthentication getPasswordAuthentication() {

    // given a prompt?
    String prompt = getRequestingPrompt();
    if (prompt == null)
        prompt = "Please login...";

    // protocol/*from   w w  w .j  av a  2  s .  com*/
    String protocol = getRequestingProtocol();
    if (protocol == null)
        protocol = "Unknown protocol";

    // get the host
    String host = null;
    InetAddress inet = getRequestingSite();
    if (inet != null)
        host = inet.getHostName();
    if (host == null)
        host = "Unknown host";

    // port
    String port = "";
    int portnum = getRequestingPort();
    if (portnum != -1)
        port = ", port " + portnum + " ";

    // Build the info string
    String info = "Connecting to " + protocol + " mail service on host " + host + port;

    //JPanel d = new JPanel();
    // XXX - for some reason using a JPanel here causes JOptionPane
    // to display incorrectly, so we workaround the problem using
    // an anonymous JComponent.
    JComponent d = new JComponent() {
    };

    GridBagLayout gb = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    d.setLayout(gb);
    c.insets = new Insets(2, 2, 2, 2);

    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 0.0;
    d.add(constrain(new JLabel(info), gb, c));
    d.add(constrain(new JLabel(prompt), gb, c));

    c.gridwidth = 1;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.0;
    d.add(constrain(new JLabel("Username:"), gb, c));

    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1.0;
    String user = getDefaultUserName();
    JTextField username = new JTextField(user, 20);
    d.add(constrain(username, gb, c));

    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    c.anchor = GridBagConstraints.EAST;
    c.weightx = 0.0;
    d.add(constrain(new JLabel("Password:"), gb, c));

    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1.0;
    JPasswordField password = new JPasswordField("", 20);
    d.add(constrain(password, gb, c));
    // XXX - following doesn't work
    if (user != null && user.length() > 0)
        password.requestFocus();
    else
        username.requestFocus();

    int result = JOptionPane.showConfirmDialog(frame, d, "Login", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE);

    if (result == JOptionPane.OK_OPTION)
        return new PasswordAuthentication(username.getText(), password.getText());
    else
        return null;
}

From source file:NormSample.java

public void init() {

    // preparing values for the normalization forms ComboBox

    formValues.put("NFC", Normalizer.Form.NFC);
    formValues.put("NFD", Normalizer.Form.NFD);
    formValues.put("NFKC", Normalizer.Form.NFKC);
    formValues.put("NFKD", Normalizer.Form.NFKD);

    formComboBox = new JComboBox();

    for (Iterator it = formValues.keySet().iterator(); it.hasNext();) {
        formComboBox.addItem((String) it.next());
    }/* w  ww  . j a va  2 s .  c om*/

    // preparing samples for normalization

    // text with the acute accent symbol
    templateValues.put("acute accent", "touch" + "\u00e9");

    // text with ligature
    templateValues.put("ligature", "a" + "\ufb03" + "ance");

    // text with the cedilla
    templateValues.put("cedilla", "fa" + "\u00e7" + "ade");

    // text with half-width katakana
    templateValues.put("half-width katakana", "\uff81\uff6e\uff7a\uff9a\uff70\uff84");

    normalizationTemplate = new JComboBox();

    for (Iterator it = templateValues.keySet().iterator(); it.hasNext();) {
        normalizationTemplate.addItem((String) it.next());
    }

    // defining a component to output normalization results

    paintingComponent = new JComponent() {
        static final long serialVersionUID = -3725620407788489160L;

        public Dimension getSize() {
            return new Dimension(550, 200);
        }

        public Dimension getPreferredSize() {
            return new Dimension(550, 200);
        }

        public Dimension getMinimumSize() {
            return new Dimension(550, 200);
        }

        public void paint(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;

            g2.setFont(new Font("Serif", Font.PLAIN, 20));
            g2.setColor(Color.BLACK);
            g2.drawString("Original string:", 100, 80);
            g2.drawString("Normalized string:", 100, 120);
            g2.setFont(new Font("Serif", Font.BOLD, 24));

            // output of the original sample selected from the ComboBox

            String original_string = templateValues.get(normalizationTemplate.getSelectedItem());
            g2.drawString(original_string, 320, 80);

            // normalization and output of the normalized string

            String normalized_string;
            java.text.Normalizer.Form currentForm = formValues.get(formComboBox.getSelectedItem());
            normalized_string = Normalizer.normalize(original_string, currentForm);
            g2.drawString(normalized_string, 320, 120);
        }
    };
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    add(paintingComponent);
    JPanel controls = new JPanel();

    controls.setLayout(new BoxLayout(controls, BoxLayout.X_AXIS));
    controls.add(new Label("Normalization Form: "));
    controls.add(formComboBox);
    controls.add(new Label("Normalization Template:"));
    controls.add(normalizationTemplate);
    add(controls);
    formComboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            paintingComponent.repaint();
        }
    });

    normalizationTemplate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            paintingComponent.repaint();
        }
    });
}

From source file:br.fapesp.myutils.MyUtils.java

/**
 * Plot a matrix consisting of 0's and 1's.
 * //from   www .j a  va2 s .c om
 * @param map
 */
public static void plotBinaryMatrix(final int[][] map, int width, int height) {
    JFrame frame = new JFrame("Binary matrix plot");

    frame.add(new JComponent() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            int w = getWidth() / map.length;
            int h = getHeight() / map[0].length;

            for (int i = 0; i < map.length; i++) {
                for (int j = 0; j < map[0].length; j++) {
                    if (map[i][j] != 0) {
                        g.setColor(new Color(map[i][j]));
                        g.fillRect(i * w, j * h, w, h);
                    }
                }
            }
        }
    });

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(width, height);
    frame.setVisible(true);
}