Example usage for java.awt Dimension Dimension

List of usage examples for java.awt Dimension Dimension

Introduction

In this page you can find the example usage for java.awt Dimension Dimension.

Prototype

public Dimension(int width, int height) 

Source Link

Document

Constructs a Dimension and initializes it to the specified width and specified height.

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  a 2s  . c o  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:MenuExample.java

public static void main(String s[]) {

    MenuExample example = new MenuExample();
    example.pane = new JTextPane();
    example.pane.setPreferredSize(new Dimension(250, 250));
    example.pane.setBorder(new BevelBorder(BevelBorder.LOWERED));

    JFrame frame = new JFrame("Menu Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(example.menuBar);//from w  w  w .  ja  v  a2  s  .c o m
    frame.getContentPane().add(example.pane, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
}

From source file:com.googlecode.sarasvati.visual.jung.JungVisualizer.java

@SuppressWarnings("serial")
public static void main(String[] args) throws Exception {
    TestSetup.init();//  ww w  . java  2s.co  m

    Session session = TestSetup.openSession();
    HibEngine engine = new HibEngine(session);

    JFrame frame = new JFrame("Workflow Visualizer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setMinimumSize(new Dimension(800, 600));

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    frame.getContentPane().add(splitPane);

    DefaultListModel listModel = new DefaultListModel();
    for (Graph g : engine.getRepository().getGraphs()) {
        listModel.addElement(g);
    }

    ListCellRenderer cellRenderer = new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            Graph g = (Graph) value;

            setText(g.getName() + "." + g.getVersion() + "  ");
            return this;
        }
    };

    final JList graphList = new JList(listModel);
    graphList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    graphList.setCellRenderer(cellRenderer);

    JScrollPane listScrollPane = new JScrollPane(graphList);
    listScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    listScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    splitPane.add(listScrollPane);

    //TreeLayout<NodeRef, Arc> layout = new TreeLayout<NodeRef, Arc>();

    DirectedSparseMultigraph<Node, Arc> graph = new DirectedSparseMultigraph<Node, Arc>();

    //final SpringLayout2<HibNodeRef, HibArc> layout = new SpringLayout2<HibNodeRef, HibArc>(graph);
    //final KKLayout<HibNodeRef, HibArc> layout = new KKLayout<HibNodeRef, HibArc>(graph);
    final TreeLayout layout = new TreeLayout(graph);
    final BasicVisualizationServer<Node, Arc> vs = new BasicVisualizationServer<Node, Arc>(layout);
    //vs.getRenderContext().setVertexLabelTransformer( new NodeLabeller() );
    //vs.getRenderContext().setEdgeLabelTransformer( new ArcLabeller() );
    vs.getRenderContext().setVertexShapeTransformer(new NodeShapeTransformer());
    vs.getRenderContext().setVertexFillPaintTransformer(new NodeColorTransformer());
    vs.getRenderContext().setLabelOffset(5);
    vs.getRenderContext().setVertexIconTransformer(new Transformer<Node, Icon>() {
        @Override
        public Icon transform(Node node) {
            return "task".equals(node.getType()) ? new TaskIcon(node) : null;
        }
    });

    Transformer<Arc, Paint> edgeColorTrans = new Transformer<Arc, Paint>() {
        private Color darkRed = new Color(128, 0, 0);

        @Override
        public Paint transform(Arc arc) {
            return "reject".equals(arc.getName()) ? darkRed : Color.black;
        }
    };

    vs.getRenderContext().setEdgeDrawPaintTransformer(edgeColorTrans);
    vs.getRenderContext().setArrowDrawPaintTransformer(edgeColorTrans);

    final JScrollPane scrollPane = new JScrollPane(vs);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

    splitPane.add(scrollPane);
    scrollPane.setBackground(Color.white);

    graphList.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }

            final Graph g = (Graph) graphList.getSelectedValue();

            if ((g == null && currentGraph == null) || (g != null && g.equals(currentGraph))) {
                return;
            }

            currentGraph = g;

            DirectedSparseMultigraph<Node, Arc> jungGraph = new DirectedSparseMultigraph<Node, Arc>();

            for (Node ref : currentGraph.getNodes()) {
                jungGraph.addVertex(ref);
            }

            for (Arc arc : currentGraph.getArcs()) {
                jungGraph.addEdge(arc, arc.getStartNode(), arc.getEndNode());
            }

            GraphTree graphTree = new GraphTree(g);
            layout.setGraph(jungGraph);
            layout.setInitializer(new NodeLocationTransformer(graphTree));
            scrollPane.repaint();
        }
    });

    frame.setVisible(true);
}

From source file:edu.jhuapl.graphs.jfreechart.TimeSeriesEffectsTest.java

public static void main(String[] args) throws GraphException {
    JFreeChart chart = getSource().getChart();
    //      ((XYPlot)chart.getPlot()).setAxisOffset(new RectangleInsets(0, 0, 0, 0));
    JFrame frame = new JFrame("Graph");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    ChartPanel content = new ChartPanel(chart);
    content.setPreferredSize(new Dimension(800, 500));

    frame.getContentPane().add(content);

    frame.pack();//from   w ww.ja v a2 s  .c o  m
    frame.setVisible(true);
}

From source file:edu.gmu.isa681.client.Main.java

public static void main(String[] args) {
    log.info("Setting look and feel...");

    try {/*  w  w  w. ja  v  a2s .co m*/
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }

    } catch (Exception ex1) {
        log.warn(ex1.getMessage(), ex1);
        log.warn("Nimbus is not available.");
        log.warn("Switching to system look and feel");
        log.warn("Some GUI discrepancies may occur!");

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex2) {
            log.error(ex2.getMessage(), ex2);
            log.error("Could not setup a look and feel.");
            System.exit(1);
        }
    }

    log.info("Initializing GUI...");

    final JFrame frame = new JFrame();
    frame.setTitle("GoForward");
    frame.setBackground(new Color(0, 100, 0));
    UIManager.put("nimbusBase", new Color(0, 100, 0));
    //UIManager.put("nimbusBlueGrey", new Color(0, 100, 0));
    UIManager.put("control", new Color(0, 100, 0));

    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    frame.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            frame.setPreferredSize(frame.getSize());
        }
    });

    Dimension dim = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    if (dim.width < 1366) {
        frame.setPreferredSize(new Dimension(800, 600));
    } else {
        frame.setPreferredSize(new Dimension(1200, 700));
    }

    //frame.setResizable(false);
    frame.setLocationByPlatform(true);
    frame.pack();

    Client client = new Client("localhost", Constants.SERVER_PORT);
    Controller controller = new Controller(client, frame);
    controller.applicationStarted();

    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    log.info("Started");
}

From source file:com.microsoftopentechnologies.adinteractiveauth.Program.java

public static void main(String[] args) {
    // we expect the following arguments to be passed in:
    //  [1] a/d login URL
    //  [2] redirect URI
    //  [3] callback url to which the auth code needs to be sent
    //  [4] window title text
    //  [5] optional boolean indicating whether we should invoke System.exit once done
    if (args.length < 4) {
        return;//  w w w.  j a  v a 2s.c  o m
    }

    String url = args[0];
    String redirectUri = args[1];
    final String callbackUrl = args[2];
    String windowTitle = args[3];
    boolean shouldExit = (args.length > 4) && Boolean.parseBoolean(args[4]);

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText(windowTitle);
    Browser browser = null;
    ADAuthCodeCallback authCodeCallback = new ADAuthCodeCallback(display, callbackUrl);

    shell.setLayout(new FillLayout());
    Monitor monitor = display.getPrimaryMonitor();
    Rectangle bounds = monitor.getBounds();
    Dimension size = new Dimension((int) (bounds.width * 0.25), (int) (bounds.height * 0.55));
    shell.setSize(size.width, size.height);
    shell.setLocation((bounds.width - size.width) / 2, (bounds.height - size.height) / 2);

    try {
        browser = new org.eclipse.swt.browser.Browser(shell, SWT.NONE);
    } catch (SWTError err) {
        authCodeCallback.onFailed(
                "Unable to load the browser component on this system. Here's some additional information: \n"
                        + err.getMessage());
        return;
    }

    BrowserLocationListener locationListener = new BrowserLocationListener(redirectUri, authCodeCallback);
    browser.addLocationListener(locationListener);
    browser.setUrl(url);

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }

    display.dispose();

    // notify the caller that the window was closed
    try {
        httpRequest(new URI(callbackUrl).resolve("closed").toURL());
    } catch (IOException ignored) {
    } catch (URISyntaxException ignored) {
    }

    if (shouldExit) {
        System.exit(0);
    }
}

From source file:Composite.java

public static void main(String s[]) {
    JFrame f = new JFrame("Composite");
    f.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);/*from  ww w  .  j  av  a  2 s. c  o  m*/
        }
    });
    JApplet applet = new Composite();
    f.getContentPane().add("Center", applet);
    applet.init();
    f.pack();
    f.setSize(new Dimension(300, 300));
    f.show();
}

From source file:UndoableTextArea.java

public static void main(String[] arg) {
    Main m = new Main();
    m.setVisible(true);/*from   w  ww .jav a  2  s. c om*/
    m.setSize(new Dimension(400, 300));
    m.validate();
}

From source file:org.mili.jmibs.jfree.examples.Example5.java

/**
 * @param args//from   w w  w.  ja  v a  2s  . c  o m
 */
public static void main(String[] args) {
    /* list with iterations. */
    List<Integer> il = new ArrayList<Integer>() {
        {
            add(100);
            add(1000);
            add(10000);
        }
    };

    /* list with object loadings. */
    List<Integer> ol = new ArrayList<Integer>() {
        {
            add(1000);
            add(10000);
        }
    };

    /* create the suite. */
    BenchmarkSuite bs = DefaultIterationObjectLoadBenchmarkSuite.create(il, ol);

    /* add some benches. */
    bs.addBenchmark(new ReplaceStringBenchmark());
    bs.addBenchmark(new ReplaceStringAppendBenchmark());
    bs.addBenchmark(new ReplaceStringAppendSingleBenchmark());

    /* execute the suite. */
    IterationObjectLoadBenchmarkSuiteResult bsr = (IterationObjectLoadBenchmarkSuiteResult) bs.execute();

    /* create a renderer. */
    BenchmarkSuiteResultRenderer<JFreeChart> bsrr = JFreeChartBarIterationObjectLoadBenchmarkSuiteResultRenderer
            .create();

    /* display the results. */
    ApplicationFrame af = new ApplicationFrame(bsr.getBenchmarkSuite().getName());
    ChartPanel chartPanel = new ChartPanel(bsrr.render(bsr));
    chartPanel.setFillZoomRectangle(true);
    chartPanel.setMouseZoomable(true);
    chartPanel.setPreferredSize(new Dimension(640, 480));
    af.setContentPane(chartPanel);
    af.pack();
    RefineryUtilities.centerFrameOnScreen(af);
    af.setVisible(true);
}

From source file:org.mili.jmibs.jfree.examples.Example4.java

/**
 * @param args/*from   ww  w. ja va 2s  .  co  m*/
 */
public static void main(String[] args) {
    /* list with iterations. */
    List<Integer> il = new ArrayList<Integer>() {
        {
            add(100);
            add(1000);
            add(10000);
        }
    };

    /* list with object loadings. */
    List<Integer> ol = new ArrayList<Integer>() {
        {
            add(1000);
            add(10000);
        }
    };

    /* create the suite. */
    BenchmarkSuite bs = DefaultIterationObjectLoadBenchmarkSuite.create(il, ol);

    /* add some benches. */
    bs.addBenchmark(new AppendStringBufferBenchmark());
    bs.addBenchmark(new AppendStringBuilderBenchmark());
    bs.addBenchmark(new AppendStringConcatBenchmark());
    bs.addBenchmark(new AppendStringPlusBenchmark());

    /* execute the suite. */
    IterationObjectLoadBenchmarkSuiteResult bsr = (IterationObjectLoadBenchmarkSuiteResult) bs.execute();

    /* create a renderer. */
    BenchmarkSuiteResultRenderer<JFreeChart> bsrr = JFreeChartBarIterationObjectLoadBenchmarkSuiteResultRenderer
            .create();

    /* display the results. */
    ApplicationFrame af = new ApplicationFrame(bsr.getBenchmarkSuite().getName());
    ChartPanel chartPanel = new ChartPanel(bsrr.render(bsr));
    chartPanel.setFillZoomRectangle(true);
    chartPanel.setMouseZoomable(true);
    chartPanel.setPreferredSize(new Dimension(640, 480));
    af.setContentPane(chartPanel);
    af.pack();
    RefineryUtilities.centerFrameOnScreen(af);
    af.setVisible(true);
}