Example usage for javax.swing JPanel setLayout

List of usage examples for javax.swing JPanel setLayout

Introduction

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

Prototype

public void setLayout(LayoutManager mgr) 

Source Link

Document

Sets the layout manager for this container.

Usage

From source file:Graph_with_jframe_and_arduino.java

public static void main(String[] args) {

    // create and configure the window
    JFrame window = new JFrame();
    window.setTitle("Sensor Graph GUI");
    window.setSize(600, 400);//from ww  w. j a v a2  s .  co  m
    window.setLayout(new BorderLayout());
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // create a drop-down box and connect button, then place them at the top of the window
    JComboBox<String> portList_combobox = new JComboBox<String>();
    Dimension d = new Dimension(300, 100);
    portList_combobox.setSize(d);
    JButton connectButton = new JButton("Connect");
    JPanel topPanel = new JPanel();
    topPanel.add(portList_combobox);
    topPanel.add(connectButton);
    window.add(topPanel, BorderLayout.NORTH);
    //pause button
    JButton Pause_btn = new JButton("Start");

    // populate the drop-down box
    SerialPort[] portNames;
    portNames = SerialPort.getCommPorts();
    //check for new port available
    Thread thread_port = new Thread() {
        @Override
        public void run() {
            while (true) {
                SerialPort[] sp = SerialPort.getCommPorts();
                if (sp.length > 0) {
                    for (SerialPort sp_name : sp) {
                        int l = portList_combobox.getItemCount(), i;
                        for (i = 0; i < l; i++) {
                            //check port name already exist or not
                            if (sp_name.getSystemPortName().equalsIgnoreCase(portList_combobox.getItemAt(i))) {
                                break;
                            }
                        }
                        if (i == l) {
                            portList_combobox.addItem(sp_name.getSystemPortName());
                        }

                    }

                } else {
                    portList_combobox.removeAllItems();

                }
                portList_combobox.repaint();

            }

        }

    };
    thread_port.start();
    for (SerialPort sp_name : portNames)
        portList_combobox.addItem(sp_name.getSystemPortName());

    //for(int i = 0; i < portNames.length; i++)
    //   portList.addItem(portNames[i].getSystemPortName());

    // create the line graph
    XYSeries series = new XYSeries("line 1");
    XYSeries series2 = new XYSeries("line 2");
    XYSeries series3 = new XYSeries("line 3");
    XYSeries series4 = new XYSeries("line 4");
    for (int i = 0; i < 100; i++) {
        series.add(x, 0);
        series2.add(x, 0);
        series3.add(x, 0);
        series4.add(x, 10);
        x++;
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);
    dataset.addSeries(series2);
    XYSeriesCollection dataset2 = new XYSeriesCollection();
    dataset2.addSeries(series3);
    dataset2.addSeries(series4);

    //create jfree chart
    JFreeChart chart = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading",
            dataset);
    JFreeChart chart2 = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading 2",
            dataset2);

    //color render for chart 1
    XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer();
    r1.setSeriesPaint(0, Color.RED);
    r1.setSeriesPaint(1, Color.GREEN);
    r1.setSeriesShapesVisible(0, false);
    r1.setSeriesShapesVisible(1, false);

    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(0, r1);
    plot.setRenderer(1, r1);

    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.DARK_GRAY);
    plot.setRangeGridlinePaint(Color.blue);

    //color render for chart 2
    XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer();
    r2.setSeriesPaint(0, Color.BLUE);
    r2.setSeriesPaint(1, Color.ORANGE);
    r2.setSeriesShapesVisible(0, false);
    r2.setSeriesShapesVisible(1, false);

    XYPlot plot2 = chart2.getXYPlot();
    plot2.setRenderer(0, r2);
    plot2.setRenderer(1, r2);

    ChartPanel cp = new ChartPanel(chart);
    ChartPanel cp2 = new ChartPanel(chart2);

    //multiple graph container
    JPanel graph_container = new JPanel();
    graph_container.setLayout(new BoxLayout(graph_container, BoxLayout.X_AXIS));
    graph_container.add(cp);
    graph_container.add(cp2);

    //add chart panel in main window
    window.add(graph_container, BorderLayout.CENTER);
    //window.add(cp2, BorderLayout.WEST);

    window.add(Pause_btn, BorderLayout.AFTER_LAST_LINE);
    Pause_btn.setEnabled(false);
    //pause btn action
    Pause_btn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (Pause_btn.getText().equalsIgnoreCase("Pause")) {

                if (chosenPort.isOpen()) {
                    try {
                        Output.write(0);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Start");
            } else {
                if (chosenPort.isOpen()) {
                    try {
                        Output.write(1);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Pause");
            }
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

    // configure the connect button and use another thread to listen for data
    connectButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (connectButton.getText().equals("Connect")) {
                // attempt to connect to the serial port
                chosenPort = SerialPort.getCommPort(portList_combobox.getSelectedItem().toString());
                chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
                if (chosenPort.openPort()) {
                    Output = chosenPort.getOutputStream();
                    connectButton.setText("Disconnect");
                    Pause_btn.setEnabled(true);
                    portList_combobox.setEnabled(false);
                }

                // create a new thread that listens for incoming text and populates the graph
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        Scanner scanner = new Scanner(chosenPort.getInputStream());
                        while (scanner.hasNextLine()) {
                            try {
                                String line = scanner.nextLine();
                                int number = Integer.parseInt(line);
                                series.add(x, number);
                                series2.add(x, number / 2);
                                series3.add(x, number / 1.5);
                                series4.add(x, number / 5);

                                if (x > 100) {
                                    series.remove(0);
                                    series2.remove(0);
                                    series3.remove(0);
                                    series4.remove(0);
                                }

                                x++;
                                window.repaint();
                            } catch (Exception e) {
                            }
                        }
                        scanner.close();
                    }
                };
                thread.start();
            } else {
                // disconnect from the serial port
                chosenPort.closePort();
                portList_combobox.setEnabled(true);
                Pause_btn.setEnabled(false);
                connectButton.setText("Connect");

            }
        }
    });

    // show the window
    window.setVisible(true);
}

From source file:DateTimeEditor.java

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = (JPanel) frame.getContentPane();
    panel.setLayout(new BorderLayout());
    JTextField field = new JTextField(20);
    Spinner spinner = new Spinner();

    panel.add(field, "Center");
    panel.add(spinner, "East");

    Dimension dim = frame.getToolkit().getScreenSize();
    frame.setLocation(dim.width / 2 - frame.getWidth() / 2, dim.height / 2 - frame.getHeight() / 2);
    frame.pack();/*from   www .  j a v  a 2s .c  o m*/
    frame.show();
}

From source file:de.codesourcery.geoip.Main.java

public static void main(String[] args) throws Exception {
    final IGeoLocator<StringSubject> locator = createGeoLocator();

    final JFrame frame = new JFrame("GeoIP");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent e) {
            try {
                locator.dispose();/*from   w ww  . j  a  va2 s.c o m*/
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        };
    });

    final MapImage image = MapImage.getRobinsonWorldMap(); // MapImage.getMillerWorldMap();      
    final MapCanvas canvas = new MapCanvas(image);

    for (GeoLocation<StringSubject> loc : locator.locate(getSpammers())) {
        if (loc.hasValidCoordinates()) {
            canvas.addCoordinate(PointRenderer.createPoint(loc, Color.YELLOW));
        }
    }

    //      canvas.addCoordinate( PointRenderer.createPoint( ZERO , Color.YELLOW ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( WELLINGTON , Color.RED ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( MELBOURNE , Color.RED ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( HAMBURG , Color.RED ) );

    final double heightToWidth = image.height() / (double) image.width(); // preserve aspect ratio of map
    canvas.setPreferredSize(new Dimension(640, (int) Math.round(640 * heightToWidth)));

    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());

    panel.add(new JLabel("Scale-X"));
    final JTextField scaleX = new JTextField(Double.toString(image.getScaleX()));
    scaleX.setColumns(5);

    final JTextField scaleY = new JTextField(Double.toString(image.getScaleY()));
    scaleY.setColumns(5);

    final ActionListener listener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            double x = Double.parseDouble(scaleX.getText());
            double y = Double.parseDouble(scaleY.getText());
            image.setScale(x, y);
            canvas.repaint();
        }
    };
    scaleX.addActionListener(listener);
    scaleY.addActionListener(listener);

    panel.add(new JLabel("Scale-X"));
    panel.add(scaleX);

    panel.add(new JLabel("Scale-Y"));
    panel.add(scaleY);

    final JTextField ipAddress = new JTextField("www.kickstarter.com");
    ipAddress.setColumns(20);

    final ActionListener ipListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final String destinationIP = ipAddress.getText();
            if (StringUtils.isBlank(destinationIP)) {
                return;
            }

            /*
             * Perform traceroute.
             */
            final List<String> hops;
            try {
                if (TracePath.isPathTracingAvailable()) {
                    hops = TracePath.trace(destinationIP);
                } else {
                    System.err.println("tracepath not available.");
                    if (TracePath.isValidAddress(destinationIP)) {
                        hops = new ArrayList<>();
                        hops.add(destinationIP);
                    } else {
                        System.err.println(destinationIP + " is no valid IP");
                        return;
                    }
                }
            } catch (Exception ex) {
                System.err.println("Failed to trace " + destinationIP);
                ex.printStackTrace();
                return;
            }

            System.out.println("Trace contains " + hops.size() + " IPs");

            /*
             * Gather locations.
             */
            final List<StringSubject> subjects = new ArrayList<>();
            for (String ip : hops) {
                subjects.add(new StringSubject(ip));
            }

            final List<GeoLocation<StringSubject>> locations;
            try {
                long time = -System.currentTimeMillis();
                locations = locator.locate(subjects);
                time += System.currentTimeMillis();

                System.out.println("Locating hops for " + destinationIP + " returned " + locations.size()
                        + " valid locations ( time: " + time + " ms)");
                System.out.flush();

            } catch (Exception e2) {
                e2.printStackTrace();
                return;
            }

            /*
             * Weed-out invalid/unknown locations.
             */
            {
                GeoLocation<StringSubject> previous = null;
                for (Iterator<GeoLocation<StringSubject>> it = locations.iterator(); it.hasNext();) {
                    final GeoLocation<StringSubject> location = it.next();
                    if (!location.hasValidCoordinates()
                            || (previous != null && previous.coordinate().equals(location.coordinate()))) {
                        it.remove();
                        System.err.println("Ignoring invalid/duplicate location for " + location);
                    } else {
                        previous = location;
                    }
                }
            }

            /*
             * Populate chart.
             */

            System.out.println("Adding " + locations.size() + " hops to chart");
            System.out.flush();

            canvas.removeAllCoordinates();

            if (locations.size() == 1) {
                canvas.addCoordinate(
                        PointRenderer.createPoint(locations.get(0), getLabel(locations.get(0)), Color.BLACK));
            } else if (locations.size() > 1) {
                GeoLocation<StringSubject> previous = locations.get(0);
                MapPoint previousPoint = PointRenderer.createPoint(previous, getLabel(previous), Color.BLACK);
                final int len = locations.size();
                for (int i = 1; i < len; i++) {
                    final GeoLocation<StringSubject> current = locations.get(i);
                    //                  final MapPoint currentPoint = PointRenderer.createPoint( current , getLabel( current ) , Color.BLACK );
                    final MapPoint currentPoint = PointRenderer.createPoint(current, Color.BLACK);

                    //                  canvas.addCoordinate( LineRenderer.createLine( previousPoint , currentPoint , Color.RED ) );
                    canvas.addCoordinate(CurvedLineRenderer.createLine(previousPoint, currentPoint, Color.RED));

                    previous = locations.get(i);
                    previousPoint = currentPoint;
                }
            }
            System.out.println("Finished adding");
            System.out.flush();
            canvas.repaint();
        }
    };
    ipAddress.addActionListener(ipListener);

    panel.add(new JLabel("IP"));
    panel.add(ipAddress);

    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(panel, BorderLayout.NORTH);
    frame.getContentPane().add(canvas, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) {
    JPanel mainPanel = new JPanel();
    JTextField field = new JTextField(20);
    JTextField field1 = new JTextField(20);

    field.getDocument().addDocumentListener(new DocumentListener() {
        @Override/*from  ww  w  . j a v  a 2  s.  c  o m*/
        public void changedUpdate(DocumentEvent e) {
            updateLabel(e);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateLabel(e);
        }

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

        private void updateLabel(DocumentEvent e) {
            field1.setText(field.getText());
        }
    });

    mainPanel.setLayout(new GridLayout(1, 0, 10, 0));
    mainPanel.add(field);
    mainPanel.add(field1);

    JFrame frame = new JFrame();
    frame.getContentPane().add(mainPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

private static JPanel createLogin() {
    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    JLabel label = new JLabel("login panel.");
    label.setFont(label.getFont().deriveFont(Font.ITALIC, 24f));
    label.setAlignmentX(0.5f);/* ww  w .j  a v  a  2  s . co  m*/
    label.setBorder(new EmptyBorder(0, 20, 0, 20));
    p.add(Box.createVerticalStrut(36));
    p.add(label);
    p.add(Box.createVerticalStrut(144));
    return p;
}

From source file:Main.java

public static void getPanelGridBagLayout(JPanel panel) {
    panel.setLayout(new GridBagLayout());
}

From source file:Main.java

public static JPanel boxPanel(int axis) {
    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, axis));
    return p;/*w  w  w  .  j ava 2 s . co  m*/
}

From source file:Main.java

public static JPanel createPageBoxLaidOutPanel() {
    final JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
    return p;//from  www  . ja v a 2 s .  c o  m
}

From source file:Main.java

public static JPanel createPanel(LayoutManager layout) {
    JPanel panel = new JPanel();
    panel.setLayout(layout);
    return panel;
}

From source file:Main.java

public static JPanel createLineBoxLaidOutPanel() {
    final JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS));
    return p;//from   w  w w  .  ja v  a  2  s .  c  om
}