Example usage for java.awt BorderLayout PAGE_END

List of usage examples for java.awt BorderLayout PAGE_END

Introduction

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

Prototype

String PAGE_END

To view the source code for java.awt BorderLayout PAGE_END.

Click Source Link

Document

The component comes after the last line of the layout's content.

Usage

From source file:DialogDemo.java

/**
 * Used by createSimpleDialogBox and createFeatureDialogBox to create a pane
 * containing a description, a single column of radio buttons, and the Show
 * it! button./*w  ww . j a v  a2 s.  co m*/
 */
private JPanel createPane(String description, JRadioButton[] radioButtons, JButton showButton) {

    int numChoices = radioButtons.length;
    JPanel box = new JPanel();
    JLabel label = new JLabel(description);

    box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
    box.add(label);

    for (int i = 0; i < numChoices; i++) {
        box.add(radioButtons[i]);
    }

    JPanel pane = new JPanel(new BorderLayout());
    pane.add(box, BorderLayout.PAGE_START);
    pane.add(showButton, BorderLayout.PAGE_END);
    return pane;
}

From source file:net.schweerelos.parrot.CombinedParrotApp.java

private void initGUI(Properties properties) {
    try {//from  ww  w. j  av  a2s .c om
        this.setTitle(APP_TITLE);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                for (MainViewComponent mainViewComponent : mainViews) {
                    if (mainViewComponent instanceof ParrotStateListener) {
                        ((ParrotStateListener) mainViewComponent).parrotExiting();
                    }
                }
            }
        });
        setSize(920, 690);

        getContentPane().setLayout(new BorderLayout());

        UserInterfaceManager uiManager = new UserInterfaceManager(properties);
        navigators = new ArrayList<NavigatorComponent>(4);

        // main view
        listView = uiManager.createMainViewComponent(Style.TABLE);
        graphView = uiManager.createMainViewComponent(Style.GRAPH);
        mainViews.add(listView);
        mainViews.add(graphView);

        final JTabbedPane mainPanel = new JTabbedPane();
        mainPanel.add(graphView.getTitle(), graphView.asJComponent());
        mainPanel.add(listView.getTitle(), listView.asJComponent());

        mainPanel.setSelectedIndex(0);
        activeMainView = graphView;
        mainPanel.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                if (e.getSource() != mainPanel) {
                    return;
                }
                int selectedIndex = mainPanel.getSelectedIndex();
                if (selectedIndex == 0) {
                    activeMainView = graphView;
                } else if (selectedIndex == 1) {
                    activeMainView = listView;
                } else {
                    Logger logger = Logger.getLogger(CombinedParrotApp.class);
                    logger.warn("unknown tab index selected: " + selectedIndex);
                }
            }
        });

        add(mainPanel, BorderLayout.CENTER);

        // navigators
        JToolBar navigatorsBar = new JToolBar(JToolBar.HORIZONTAL);
        navigatorsBar.setMargin(new Insets(0, 11, 0, 0));
        navigatorsBar.setFloatable(false);
        getContentPane().add(navigatorsBar, BorderLayout.PAGE_START);

        // timeline
        NavigatorComponent timelineNavigator = uiManager.createTimelineNavigationComponent();
        navigators.add(timelineNavigator);

        JFrame timelineFrame = new JFrame(timelineNavigator.getNavigatorName() + "  " + APP_TITLE);

        timelineFrame.getContentPane().add(timelineNavigator.asJComponent());
        timelineFrame.pack();
        Point preferredLocation = new Point(0, 0);
        preferredFrameLocations.put(timelineFrame, preferredLocation);

        if (timelineNavigator.hasShowHideListener()) {
            timelineFrame.addComponentListener(timelineNavigator.getShowHideListener());
        }
        timelineFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        JToggleButton timelineButton = setupNavigatorButton(timelineNavigator.getNavigatorName(),
                timelineNavigator.getAcceleratorKey(), timelineNavigator);
        navigatorsBar.add(timelineButton);

        // map      
        NavigatorComponent mapNavigator = uiManager.createMapNavigationComponent();
        navigators.add(mapNavigator);

        JFrame mapFrame = new JFrame(mapNavigator.getNavigatorName() + "  " + APP_TITLE);

        mapFrame.getContentPane().add(mapNavigator.asJComponent());
        mapFrame.pack();
        preferredLocation = new Point(0,
                Toolkit.getDefaultToolkit().getScreenSize().height - mapFrame.getHeight());
        preferredFrameLocations.put(mapFrame, preferredLocation);

        if (mapNavigator.hasShowHideListener()) {
            mapFrame.addComponentListener(mapNavigator.getShowHideListener());
        }
        mapFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        JToggleButton mapButton = setupNavigatorButton(mapNavigator.getNavigatorName(),
                mapNavigator.getAcceleratorKey(), mapNavigator);
        navigatorsBar.add(mapButton);

        // search      
        NavigatorComponent searchNavigator = uiManager.createSearchComponent();
        navigators.add(searchNavigator);

        JFrame searchFrame = new JFrame(searchNavigator.getNavigatorName() + "  " + APP_TITLE);

        searchFrame.getContentPane().add(searchNavigator.asJComponent());
        searchFrame.pack();
        preferredLocation = new Point(
                Toolkit.getDefaultToolkit().getScreenSize().width - searchFrame.getWidth(), 0);
        preferredFrameLocations.put(searchFrame, preferredLocation);

        if (searchNavigator.hasShowHideListener()) {
            searchFrame.addComponentListener(searchNavigator.getShowHideListener());
        }
        searchFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        JToggleButton searchButton = setupNavigatorButton(searchNavigator.getNavigatorName(),
                searchNavigator.getAcceleratorKey(), searchNavigator);
        navigatorsBar.add(searchButton);

        // connections
        NavigatorComponent chainNavigator = uiManager.createChainNavigationComponent();
        navigators.add(chainNavigator);

        if (chainNavigator instanceof PickListener) {
            for (MainViewComponent mainViewComponent : mainViews) {
                mainViewComponent.addPickListener((PickListener) chainNavigator);
            }
        }

        if (chainNavigator.hasShowHideListener()) {
            chainNavigator.asJComponent().addComponentListener(chainNavigator.getShowHideListener());
        }

        JToggleButton connectionsButton = setupNavigatorButton(chainNavigator.getNavigatorName(),
                chainNavigator.getAcceleratorKey(), chainNavigator);
        navigatorsBar.add(connectionsButton);

        add(chainNavigator.asJComponent(), BorderLayout.PAGE_END);
        chainNavigator.asJComponent().setVisible(false);
    } catch (RuntimeException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (UnknownStyleException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:velocitekProStartAnalyzer.MainWindow.java

private void initialize() {
    JDBCPointDao jdbcPointDao = new JDBCPointDao();
    //SQLiteDB.createNewDatabase(dbName);
    jdbcPointDao.getConnection(dbName);/*from  w  w  w . jav a2s  .  com*/
    SQLiteDB.createNewTable(dbName);

    frame = new JFrame();
    frame.setBounds(1, 1, 1280, 720);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.getContentPane().setLayout(new BorderLayout(0, 0));
    setScrollTable(new JScrollPane());
    frame.getContentPane().add(copyrightLabel, BorderLayout.PAGE_END);
    btnPanel = new JPanel();
    frame.getContentPane().add(btnPanel, BorderLayout.NORTH);

    frame.addWindowStateListener(new WindowStateListener() {
        @Override
        public void windowStateChanged(WindowEvent event) {
            boolean isMaximized = isMaximized(event.getNewState());
            boolean wasMaximized = isMaximized(event.getOldState());

            if (isMaximized && !wasMaximized) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        defaultSize();
                    }
                });
            } else if (wasMaximized && !isMaximized) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        defaultSize();
                    }
                });
            }
        }
    });

    ReadXMLFile readXmlFile = new ReadXMLFile();

    btnLoadRouteData = new JButton("Reload");
    btnPanel.add(btnLoadRouteData);
    if (getFilePath() == null) {
        btnLoadRouteData.setEnabled(false);
    }
    btnLoadRouteData.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            readXmlFile.ReadXmlFile(getFilePath());
            loadDataFromDB();
        }
    });

    btnPanel.add(btnShowFileDialogButton);

    tableContainer = new JScrollPane(pointTable);
    frame.getContentPane().add(tableContainer, BorderLayout.SOUTH);
    graphMapSplitPanel = new JSplitPane();
    tableGraphMapSplitPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    graphMapSplitPanel.setResizeWeight(.5d);
    frame.getContentPane().add(tableGraphMapSplitPanel, BorderLayout.CENTER);
    JPanel dataAnalysisPanel = new JPanel();
    dataAnalysisPanel.add(dataAnalysisLabel);
    JPanel tableContainerPanel = new JPanel(new BorderLayout());
    tableContainerPanel.add(dataAnalysisPanel, BorderLayout.NORTH);
    tableContainerPanel.add(tableContainer);

    tableGraphMapSplitPanel.setTopComponent(graphMapSplitPanel);
    tableGraphMapSplitPanel.setBottomComponent(tableContainerPanel);

    graphMapSplitPanel.setLeftComponent(graphPanel);
    //mapPanel.setVisible(true);
    graphMapSplitPanel.setRightComponent(mapPanel);

    btnPanel.add(statusLabel);
    statusLabel.setVisible(true);
    //frame.add(statusLabel);

    openFile();
    loadDataFromDB();

    pointTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent event) {
            if (!JDBCPointDao.points.isEmpty()) {
                getMapPanel().map().removeAllMapMarkers();
                for (int pointTableID : pointTable.getSelectedRows()) {
                    MapMarkerDot mapPoint = new MapMarkerDot(null, null,
                            (double) pointTable.getValueAt(pointTableID, 4),
                            (double) pointTable.getValueAt(pointTableID, 5));
                    if (!getMapPanel().map().getMapMarkerList().contains(mapPoint)) {
                        getMapPanel().map().addMapMarker(mapPoint);
                    }
                    // mapPanel.map().setDisplayToFitMapMarkers();
                }
                int index = 0;
                for (int pointTableID : pointTable.getSelectedRows()) {
                    index = pointTableID;
                }
                Double x = Double.valueOf(pointTable.getValueAt(index, 0).toString());
                Double y = Double.valueOf(pointTable.getValueAt(index, 3).toString());

                //int test2 = (int) pointTable.getValueAt(pointTable.getSelectedRow(), 3);

                xCrosshair.setValue(x);
                yCrosshair.setValue(y);

            }
        }

    });

    popup = new JPopupMenu();

    btnDeleteSelected = new JMenuItem("Delete Selected");
    popup.add(btnDeleteSelected);
    btnDeleteSelected.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            deleteSelected();
            loadDataFromDB();
        }
    });

    btnDeleteAllButNotSelected = new JMenuItem("Set Selected as New Database");
    popup.add(btnDeleteAllButNotSelected);
    btnDeleteAllButNotSelected.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            deleteAllButNotSelected();
            loadDataFromDB();
            setStartFinishMapMarkers();
        }
    });

    btnSetStartTime = new JMenuItem("Set Race Time");
    popup.add(btnSetStartTime);

    btnSetStartTime.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                JDBCPointDao.pointsOld.clear();
                JDBCPointDao.pointsOld.addAll(JDBCPointDao.points);
                setStartTime(showSetStartTimeDialog());
                loadDataFromDB();
                setEndTime(showSetEndTimeDialog());
                loadDataFromDB();
                setStartFinishMapMarkers();
            } catch (NullPointerException exception) {
                return;
            }

        }
    });

    btnSetStartFinishMapMarkers = new JMenuItem("Show Start Finish");
    popup.add(btnSetStartFinishMapMarkers);
    popup.addSeparator();
    btnSetStartFinishMapMarkers.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStartFinishMapMarkers();
        }
    });

    btnMenuSaveSubmenu.add(btnSaveChartAsPng);
    btnSaveMapAsPng = new JMenuItem("Save Map as PNG");
    btnMenuSaveSubmenu.add(btnSaveMapAsPng);
    btnSaveTableAsPng = new JMenuItem("Save Table as PNG");
    btnMenuSaveSubmenu.add(btnSaveTableAsPng);
    btnMenuSaveSubmenu.add(btnSaveMapAsPng);
    btnMenuSaveSubmenu.addSeparator();
    btnMenuSaveSubmenu.add(btnSaveAsVCCForChart);
    if (JDBCPointDao.points.isEmpty()) {
        btnSaveAsVCC.setEnabled(false);
        btnSaveAsVCCForChart.setEnabled(false);
    }
    btnBackData = new JMenuItem("Back");
    popup.add(btnBackData);
    popup.addSeparator();

    if (JDBCPointDao.pointsOld.isEmpty()) {
        btnBackData.setEnabled(false);
    }

    JMenuItem btnResizeWindow = new JMenuItem("Resize Windows");
    popup.add(btnResizeWindow);
    popup.addSeparator();
    btnResizeWindow.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                defaultSize();
            } catch (NullPointerException exception) {
                return;
            }

        }
    });
    popup.add(btnMenuSaveSubmenu);
    popup.addSeparator();
    popup.add(btnAbout);

    btnAbout.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(frame,
                    "Velocitek Prostart Analyser v.1.4 - Copyright (C) 2017 Maciej Jdrzejko"
                            + "\n\nThis program is free software: you can redistribute it and/or modify"
                            + "\nit under the terms of the GNU General Public License as published by "
                            + "\nthe Free Software Foundation, either version 3 of the License, or"
                            + "\n(at your option) any later version."
                            + "\n\nThis program is distributed in the hope that it will be useful,"
                            + "\nbut WITHOUT ANY WARRANTY; without even the implied warranty of"
                            + "\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the"
                            + "\nGNU General Public License for more details."
                            + "\n\nYou should have received a copy of the GNU General Public License"
                            + "\nalong with this program.  If not, see http://www.gnu.org/licenses/ ");
        }
    });

    btnResetSpeedChart.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            loadDataFromDB();
        }
    });

    btnMedianSpeedChart.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int howManyTimes = selectHowManyTimes();
            for (int i = 0; i < howManyTimes; i++) {
                int iterator = 1;
                JDBCPointDao.dataSet.removeAllSeries();
                JDBCPointDao.speedTimeSeries.clear();
                for (Double medianSpeed : dataAnalysis.getMedianForChart()) {
                    JDBCPointDao.speedTimeSeries.add(iterator, medianSpeed);
                    iterator++;
                }
                JDBCPointDao.dataSet.addSeries(JDBCPointDao.speedTimeSeries);
                createChartPanel();

            }
        }
    });

    btnAvgSpeedChart.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int howManyTimes = selectHowManyTimes();
            for (int i = 0; i < howManyTimes; i++) {
                int iterator = 1;
                JDBCPointDao.dataSet.removeAllSeries();
                JDBCPointDao.speedTimeSeries.clear();
                for (Double avgSpeed : dataAnalysis.getAvgSpeedForChart()) {
                    JDBCPointDao.speedTimeSeries.add(iterator, avgSpeed);
                    iterator++;
                }
                JDBCPointDao.dataSet.addSeries(JDBCPointDao.speedTimeSeries);
                createChartPanel();
            }
        }
    });

    //Add listener to components that can bring up popup menus.

    frame.addMouseListener(popupListener);
    graphMapSplitPanel.addMouseListener(popupListener);
    tableContainer.addMouseListener(popupListener);
    pointTable.addMouseListener(popupListener);
    mapPanel.addMouseListener(popupListener);
    saveMapAsPng(mapPanel);
    saveTableAsPng(tableContainer);

    saveNewVCC();
    backData();

}

From source file:e3fraud.gui.MainWindow.java

public MainWindow() {
    super(new BorderLayout(5, 5));

    extended = false;/*from  w w w  . j a  v a 2  s  .  c om*/

    //Create the log first, because the action listeners
    //need to refer to it.
    log = new JTextArea(10, 50);
    log.setMargin(new Insets(5, 5, 5, 5));
    log.setEditable(false);
    logScrollPane = new JScrollPane(log);
    DefaultCaret caret = (DefaultCaret) log.getCaret();
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

    //        create the progress bar
    progressBar = new JProgressBar(0, 100);
    progressBar.setValue(progressBar.getMinimum());
    progressBar.setVisible(false);
    progressBar.setStringPainted(true);
    //Create the settings pane
    generationSettingLabel = new JLabel("Generate:");
    SpinnerModel collusionsSpinnerModel = new SpinnerNumberModel(1, 0, 3, 1);
    collusionSettingsPanel = new JPanel(new FlowLayout()) {
        @Override
        public Dimension getMaximumSize() {
            return getPreferredSize();
        }
    };
    // collusionSettingsPanel.setLayout(new BoxLayout(collusionSettingsPanel, BoxLayout.X_AXIS));
    collusionsButton = new JSpinner(collusionsSpinnerModel);
    collusionsLabel = new JLabel("collusion(s)");
    collusionSettingsPanel.add(collusionsButton);
    collusionSettingsPanel.add(collusionsLabel);

    rankingSettingLabel = new JLabel("Rank by:");
    lossButton = new JRadioButton("loss");
    lossButton.setToolTipText("Sort sub-ideal models based on loss for Target of Assessment (high -> low)");
    gainButton = new JRadioButton("gain");
    gainButton.setToolTipText(
            "Sort sub-ideal models based on gain of any actor except Target of Assessment (high -> low)");
    lossGainButton = new JRadioButton("loss + gain");
    lossGainButton.setToolTipText(
            "Sort sub-ideal models based on loss for Target of Assessment and, if equal, on gain of any actor except Target of Assessment");
    //gainLossButton = new JRadioButton("gain + loss");
    lossGainButton.setSelected(true);
    rankingGroup = new ButtonGroup();
    rankingGroup.add(lossButton);
    rankingGroup.add(gainButton);
    rankingGroup.add(lossGainButton);
    //rankingGroup.add(gainLossButton);
    groupingSettingLabel = new JLabel("Group by:");
    groupingButton = new JCheckBox("collusion");
    groupingButton.setToolTipText(
            "Groups sub-ideal models based on the pair of actors colluding before ranking them");
    groupingButton.setSelected(false);
    refreshButton = new JButton("Refresh");
    refreshButton.addActionListener(this);

    settingsPanel = new JPanel();
    settingsPanel.setLayout(new BoxLayout(settingsPanel, BoxLayout.PAGE_AXIS));
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    settingsPanel.add(generationSettingLabel);
    collusionSettingsPanel.setAlignmentX(LEFT_ALIGNMENT);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    settingsPanel.add(collusionSettingsPanel);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    rankingSettingLabel.setAlignmentY(TOP_ALIGNMENT);
    settingsPanel.add(rankingSettingLabel);
    settingsPanel.add(lossButton);
    settingsPanel.add(gainButton);
    settingsPanel.add(lossGainButton);
    //settingsPanel.add(gainLossButton);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    settingsPanel.add(groupingSettingLabel);
    settingsPanel.add(groupingButton);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    settingsPanel.add(refreshButton);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 20)));
    progressBar.setPreferredSize(
            new Dimension(settingsPanel.getSize().width, progressBar.getPreferredSize().height));
    settingsPanel.add(progressBar);

    //Create the result tree
    root = new DefaultMutableTreeNode("No models to display");
    treeModel = new DefaultTreeModel(root);
    tree = new JTree(treeModel);
    //tree.setUI(new CustomTreeUI());
    tree.setCellRenderer(new CustomTreeCellRenderer(tree));
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setLargeModel(true);
    resultScrollPane = new JScrollPane(tree);
    tree.addTreeSelectionListener(treeSelectionListener);

    //tree.setShowsRootHandles(true);
    //Create a file chooser for saving
    sfc = new JFileChooser();
    FileFilter jpegFilter = new FileNameExtensionFilter("JPEG image", new String[] { "jpg", "jpeg" });
    sfc.addChoosableFileFilter(jpegFilter);
    sfc.setFileFilter(jpegFilter);

    //Create a file chooser for loading
    fc = new JFileChooser();
    FileFilter rdfFilter = new FileNameExtensionFilter("RDF file", "RDF");
    fc.addChoosableFileFilter(rdfFilter);
    fc.setFileFilter(rdfFilter);

    //Create the open button.  
    openButton = new JButton("Load model", createImageIcon("images/Open24.png"));
    openButton.addActionListener(this);
    openButton.setToolTipText("Load a e3value model");

    //Create the ideal graph button. 
    idealGraphButton = new JButton("Show ideal graph", createImageIcon("images/Plot.png"));
    idealGraphButton.setToolTipText("Display ideal profitability graph");
    idealGraphButton.addActionListener(this);

    Dimension thinButtonDimension = new Dimension(15, 420);

    //Create the expand subideal graph button. 
    expandButton = new JButton(">");
    expandButton.setPreferredSize(thinButtonDimension);
    expandButton.setMargin(new Insets(0, 0, 0, 0));
    expandButton.setToolTipText("Expand to show non-ideal profitability graph for selected model");
    expandButton.addActionListener(this);

    //Create the collapse sub-ideal graph button. 
    collapseButton = new JButton("<");
    collapseButton.setPreferredSize(thinButtonDimension);
    collapseButton.setMargin(new Insets(0, 0, 0, 0));
    collapseButton.setToolTipText("Collapse non-ideal profitability graph for selected model");
    collapseButton.addActionListener(this);

    //Create the generation button. 
    generateButton = new JButton("Generate sub-ideal models", createImageIcon("images/generate.png"));
    generateButton.addActionListener(this);
    generateButton.setToolTipText("Generate sub-ideal models for the e3value model currently loaded");

    //Create the chart panel
    chartPane = new JPanel();
    chartPane.setLayout(new FlowLayout(FlowLayout.LEFT));
    chartPane.add(expandButton);

    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
    buttonPanel.add(openButton);
    buttonPanel.add(Box.createRigidArea(new Dimension(20, 0)));
    buttonPanel.add(generateButton);
    buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
    buttonPanel.add(idealGraphButton);

    //Add the buttons, the ranking options, the result list and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(settingsPanel, BorderLayout.LINE_START);
    add(resultScrollPane, BorderLayout.CENTER);

    add(logScrollPane, BorderLayout.PAGE_END);
    add(chartPane, BorderLayout.LINE_END);
    //and make a nice border around it
    setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 10));
}

From source file:BasicDnD.java

public BasicDnD() {
    super(new BorderLayout());
    JPanel leftPanel = createVerticalBoxPanel();
    JPanel rightPanel = createVerticalBoxPanel();

    // Create a table model.
    DefaultTableModel tm = new DefaultTableModel();
    tm.addColumn("Column 0");
    tm.addColumn("Column 1");
    tm.addColumn("Column 2");
    tm.addColumn("Column 3");
    tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" });
    tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" });
    tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" });
    tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" });

    // LEFT COLUMN
    // Use the table model to create a table.
    table = new JTable(tm);
    leftPanel.add(createPanelForComponent(table, "JTable"));

    // Create a color chooser.
    colorChooser = new JColorChooser();
    leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser"));

    // RIGHT COLUMN
    // Create a textfield.
    textField = new JTextField(30);
    textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast");
    rightPanel.add(createPanelForComponent(textField, "JTextField"));

    // Create a scrolled text area.
    textArea = new JTextArea(5, 30);
    textArea.setText("Favorite shows:\nBuffy, Alias, Angel");
    JScrollPane scrollPane = new JScrollPane(textArea);
    rightPanel.add(createPanelForComponent(scrollPane, "JTextArea"));

    // Create a list model and a list.
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("Martha Washington");
    listModel.addElement("Abigail Adams");
    listModel.addElement("Martha Randolph");
    listModel.addElement("Dolley Madison");
    listModel.addElement("Elizabeth Monroe");
    listModel.addElement("Louisa Adams");
    listModel.addElement("Emily Donelson");
    list = new JList(listModel);
    list.setVisibleRowCount(-1);/*from   w  w  w. java2s.c  o  m*/
    list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    list.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            if (dl.getIndex() == -1) {
                return false;
            }
            return true;
        }

        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }

            // Check for String flavor
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                displayDropLocation("List doesn't accept a drop of this type.");
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            DefaultListModel listModel = (DefaultListModel) list.getModel();
            int index = dl.getIndex();
            boolean insert = dl.isInsert();
            // Get the current string under the drop.
            String value = (String) listModel.getElementAt(index);

            // Get the string that is being dropped.
            Transferable t = info.getTransferable();
            String data;
            try {
                data = (String) t.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }

            // Display a dialog with the drop information.
            String dropValue = "\"" + data + "\" dropped ";
            if (dl.isInsert()) {
                if (dl.getIndex() == 0) {
                    displayDropLocation(dropValue + "at beginning of list");
                } else if (dl.getIndex() >= list.getModel().getSize()) {
                    displayDropLocation(dropValue + "at end of list");
                } else {
                    String value1 = (String) list.getModel().getElementAt(dl.getIndex() - 1);
                    String value2 = (String) list.getModel().getElementAt(dl.getIndex());
                    displayDropLocation(dropValue + "between \"" + value1 + "\" and \"" + value2 + "\"");
                }
            } else {
                displayDropLocation(dropValue + "on top of " + "\"" + value + "\"");
            }

            /**
             * This is commented out for the basicdemo.html tutorial page. * If you
             * add this code snippet back and delete the * "return false;" line, the
             * list will accept drops * of type string. // Perform the actual
             * import. if (insert) { listModel.add(index, data); } else {
             * listModel.set(index, data); } return true;
             */
            return false;
        }

        public int getSourceActions(JComponent c) {
            return COPY;
        }

        protected Transferable createTransferable(JComponent c) {
            JList list = (JList) c;
            Object[] values = list.getSelectedValues();

            StringBuffer buff = new StringBuffer();

            for (int i = 0; i < values.length; i++) {
                Object val = values[i];
                buff.append(val == null ? "" : val.toString());
                if (i != values.length - 1) {
                    buff.append("\n");
                }
            }
            return new StringSelection(buff.toString());
        }
    });
    list.setDropMode(DropMode.ON_OR_INSERT);

    JScrollPane listView = new JScrollPane(list);
    listView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(listView, "JList"));

    // Create a tree.
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia");
    DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon");
    rootNode.add(sharon);
    DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya");
    sharon.add(maya);
    DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya");
    sharon.add(anya);
    sharon.add(new DefaultMutableTreeNode("Bongo"));
    maya.add(new DefaultMutableTreeNode("Muffin"));
    anya.add(new DefaultMutableTreeNode("Winky"));
    DefaultTreeModel model = new DefaultTreeModel(rootNode);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(treeView, "JTree"));

    // Create the toggle button.
    toggleDnD = new JCheckBox("Turn on Drag and Drop");
    toggleDnD.setActionCommand("toggleDnD");
    toggleDnD.addActionListener(this);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
    splitPane.setOneTouchExpandable(true);

    add(splitPane, BorderLayout.CENTER);
    add(toggleDnD, BorderLayout.PAGE_END);
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}

From source file:org.orbisgis.mapeditor.map.MapEditor.java

@Activate
public void activate() {
    this.mapsManager = new MapsManager(viewWorkspace.getMapContextPath(), dataManager, editorManager);
    dockingPanelParameters = new DockingPanelParameters();
    dockingPanelParameters.setName("map_editor");
    updateMapLabel();/*  w w  w  . j a  va 2s . c om*/
    dockingPanelParameters.setTitleIcon(MapEditorIcons.getIcon("map"));
    dockingPanelParameters.setMinimizable(false);
    dockingPanelParameters.setExternalizable(false);
    dockingPanelParameters.setCloseable(false);
    dockingPanelParameters.setLayout(mapEditorPersistence);
    dockingPanelParameters.setVisible(true);
    layeredPane.add(mapControl, 1);
    layeredPane.add(mapsManager, 0);
    mapsManager.setVisible(false);
    mapsManager.setMapsManagerPersistence(mapEditorPersistence.getMapsManagerPersistence());
    // when the layout is loaded, this editor will load the map element linked with this layout
    mapEditorPersistence.addPropertyChangeListener(MapEditorPersistence.PROP_DEFAULTMAPCONTEXT,
            EventHandler.create(PropertyChangeListener.class, this, "onSerialisationMapChange"));
    add(layeredPane, BorderLayout.CENTER);
    add(mapStatusBar, BorderLayout.PAGE_END);
    //Declare Tools of Map Editors
    //Add the tools in the docking Panel title
    createActions();
    dockingPanelParameters.setDockActions(actions.getActions());
    // Tools that will be created later will also be set in the docking panel
    // thanks to this listener
    actions.addPropertyChangeListener(new ActionDockingListener(dockingPanelParameters));
    //Set the Drop target
    dragDropHandler = new MapTransferHandler();
    this.setTransferHandler(dragDropHandler);
}

From source file:DialogDemo.java

/**
 * Like createPane, but creates a pane with 2 columns of radio buttons. The
 * number of buttons passed in *must* be even.
 *///from   w  w w .  j  a va 2  s . c o m
private JPanel create2ColPane(String description, JRadioButton[] radioButtons, JButton showButton) {
    JLabel label = new JLabel(description);
    int numPerColumn = radioButtons.length / 2;

    JPanel grid = new JPanel(new GridLayout(0, 2));
    for (int i = 0; i < numPerColumn; i++) {
        grid.add(radioButtons[i]);
        grid.add(radioButtons[i + numPerColumn]);
    }

    JPanel box = new JPanel();
    box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
    box.add(label);
    grid.setAlignmentX(0.0f);
    box.add(grid);

    JPanel pane = new JPanel(new BorderLayout());
    pane.add(box, BorderLayout.PAGE_START);
    pane.add(showButton, BorderLayout.PAGE_END);

    return pane;
}

From source file:com.tascape.qa.th.android.driver.App.java

/**
 * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting
 * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction.
 *
 * @param timeoutMinutes timeout in minutes to fail the manual steps
 *
 * @throws Exception if case of error/* w  w w .  j a  va 2  s  .c om*/
 */
public void interactManually(int timeoutMinutes) throws Exception {
    LOG.info("Start manual UI interaction");
    long end = System.currentTimeMillis() + timeoutMinutes * 60000L;

    AtomicBoolean visible = new AtomicBoolean(true);
    AtomicBoolean pass = new AtomicBoolean(false);
    String tName = Thread.currentThread().getName() + "m";
    SwingUtilities.invokeLater(() -> {
        JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail());
        jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        JPanel jpContent = new JPanel(new BorderLayout());
        jd.setContentPane(jpContent);
        jpContent.setPreferredSize(new Dimension(1088, 828));
        jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JPanel jpInfo = new JPanel();
        jpContent.add(jpInfo, BorderLayout.PAGE_START);
        jpInfo.setLayout(new BorderLayout());
        {
            JButton jb = new JButton("PASS");
            jb.setForeground(Color.green.darker());
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_START);
            jb.addActionListener(event -> {
                pass.set(true);
                jd.dispose();
                visible.set(false);
            });
        }
        {
            JButton jb = new JButton("FAIL");
            jb.setForeground(Color.red);
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_END);
            jb.addActionListener(event -> {
                pass.set(false);
                jd.dispose();
                visible.set(false);
            });
        }

        JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        new SwingWorker<Long, Long>() {
            @Override
            protected Long doInBackground() throws Exception {
                while (System.currentTimeMillis() < end) {
                    Thread.sleep(1000);
                    long left = (end - System.currentTimeMillis()) / 1000;
                    this.publish(left);
                }
                return 0L;
            }

            @Override
            protected void process(List<Long> chunks) {
                Long l = chunks.get(chunks.size() - 1);
                jlTimeout.setText(l + " seconds left");
                if (l < 850) {
                    jlTimeout.setForeground(Color.red);
                }
            }
        }.execute();

        JPanel jpResponse = new JPanel(new BorderLayout());
        JPanel jpProgress = new JPanel(new BorderLayout());
        jpResponse.add(jpProgress, BorderLayout.PAGE_START);

        JTextArea jtaJson = new JTextArea();
        jtaJson.setEditable(false);
        jtaJson.setTabSize(4);
        Font font = jtaJson.getFont();
        jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize()));

        JTree jtView = new JTree();

        JTabbedPane jtp = new JTabbedPane();
        jtp.add("tree", new JScrollPane(jtView));
        jtp.add("json", new JScrollPane(jtaJson));

        jpResponse.add(jtp, BorderLayout.CENTER);

        JPanel jpScreen = new JPanel();
        jpScreen.setMinimumSize(new Dimension(200, 200));
        jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS));
        JScrollPane jsp1 = new JScrollPane(jpScreen);
        jpResponse.add(jsp1, BorderLayout.LINE_START);

        JPanel jpJs = new JPanel(new BorderLayout());
        JTextArea jtaJs = new JTextArea();
        jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER);

        JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs);
        jSplitPane.setResizeWeight(0.88);
        jpContent.add(jSplitPane, BorderLayout.CENTER);

        JPanel jpLog = new JPanel();
        jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
        jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS));

        JCheckBox jcbTap = new JCheckBox("Enable Click", null, false);
        jpLog.add(jcbTap);
        jpLog.add(Box.createHorizontalStrut(8));

        JButton jbLogUi = new JButton("Log Screen");
        jpResponse.add(jpLog, BorderLayout.PAGE_END);
        {
            jpLog.add(jbLogUi);
            jbLogUi.addActionListener((ActionEvent event) -> {
                jtaJson.setText("waiting for screenshot...");
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        LOG.debug("\n\n");
                        try {
                            WindowHierarchy wh = device.loadWindowHierarchy();
                            jtView.setModel(getModel(wh));

                            jtaJson.setText("");
                            jtaJson.append(wh.root.toJson().toString(2));
                            jtaJson.append("\n");

                            File png = device.takeDeviceScreenshot();
                            BufferedImage image = ImageIO.read(png);

                            int w = device.getDisplayWidth();
                            int h = device.getDisplayHeight();

                            BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                            Graphics2D g2 = resizedImg.createGraphics();
                            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                            g2.drawImage(image, 0, 0, w, h, null);
                            g2.dispose();

                            JLabel jLabel = new JLabel(new ImageIcon(resizedImg));
                            jpScreen.removeAll();
                            jsp1.setPreferredSize(new Dimension(w + 30, h));
                            jpScreen.add(jLabel);

                            jLabel.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY());
                                    if (jcbTap.isSelected()) {
                                        device.click(e.getPoint().x, e.getPoint().y);
                                        device.waitForIdle();
                                        jbLogUi.doClick();
                                    }
                                }
                            });
                        } catch (Exception ex) {
                            LOG.error("Cannot log screen", ex);
                            jtaJson.append("Cannot log screen");
                        }
                        jtaJson.append("\n\n\n");
                        LOG.debug("\n\n");

                        jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1);
                        jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1);
                    }
                };
                t.start();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbLogMsg = new JButton("Log Message");
            jpLog.add(jbLogMsg);
            JTextField jtMsg = new JTextField(10);
            jpLog.add(jtMsg);
            jtMsg.addFocusListener(new FocusListener() {
                @Override
                public void focusLost(final FocusEvent pE) {
                }

                @Override
                public void focusGained(final FocusEvent pE) {
                    jtMsg.selectAll();
                }
            });
            jtMsg.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(java.awt.event.KeyEvent e) {
                    if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                        jbLogMsg.doClick();
                    }
                }
            });
            jbLogMsg.addActionListener(event -> {
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        String msg = jtMsg.getText();
                        if (StringUtils.isNotBlank(msg)) {
                            LOG.info("{}", msg);
                            jtMsg.selectAll();
                        }
                    }
                };
                t.start();
                try {
                    t.join();
                } catch (InterruptedException ex) {
                    LOG.error("Cannot take screenshot", ex);
                }
                jtMsg.requestFocus();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbClear = new JButton("Clear");
            jpLog.add(jbClear);
            jbClear.addActionListener(event -> {
                jtaJson.setText("");
            });
        }

        JPanel jpAction = new JPanel();
        jpContent.add(jpAction, BorderLayout.PAGE_END);
        jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS));
        jpJs.add(jpAction, BorderLayout.PAGE_END);

        jd.pack();
        jd.setVisible(true);
        jd.setLocationRelativeTo(null);

        jbLogUi.doClick();
    });

    while (visible.get()) {
        if (System.currentTimeMillis() > end) {
            LOG.error("Manual UI interaction timeout");
            break;
        }
        Thread.sleep(500);
    }

    if (pass.get()) {
        LOG.info("Manual UI Interaction returns PASS");
    } else {
        Assert.fail("Manual UI Interaction returns FAIL");
    }
}

From source file:de.uka.aifb.com.systemDynamics.gui.ModelExecutionChartPanel.java

/**
 * Creates panel.//from w  w  w . j a v  a 2 s  . c  om
 */
private void createPanel() {
    setLayout(new BorderLayout());

    // CENTER: chart
    ChartPanel chartPanel = new ChartPanel(createChart());
    // no context menu
    chartPanel.setPopupMenu(null);
    // not zoomable
    chartPanel.setMouseZoomable(false);
    add(chartPanel, BorderLayout.CENTER);

    // LINE_END: series table
    JPanel tablePanel = new JPanel(new GridBagLayout());
    String[] columnNames = { messages.getString("ModelExecutionChartPanel.Table.ColumnNames.ExtraAxis"),
            messages.getString("ModelExecutionChartPanel.Table.ColumnNames.LevelNode") };
    final MyTableModel tableModel = new MyTableModel(columnNames, xySeriesArray.length);
    for (int i = 0; i < xySeriesArray.length; i++) {
        tableModel.addEntry((String) xySeriesArray[i].getKey());
    }
    JTable table = new JTable(tableModel);
    table.setRowSelectionAllowed(false);
    JScrollPane tableScrollPane = new JScrollPane(table);
    int width = (int) Math.min(300, table.getPreferredSize().getWidth());
    int height = (int) Math.min(200, table.getPreferredSize().getHeight());
    tableScrollPane.getViewport().setPreferredSize(new Dimension(width, height));
    tableScrollPane.setMaximumSize(tableScrollPane.getViewport().getPreferredSize());
    axesButton = new JButton(messages.getString("ModelExecutionChartPanel.AxesButton.Text"));
    axesButton.setToolTipText(messages.getString("ModelExecutionChartPanel.AxesButton.ToolTipText"));
    axesButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // create XYSeriesCollections (and renderer)
            XYSeriesCollection standardData = new XYSeriesCollection();
            XYLineAndShapeRenderer standardRenderer = new XYLineAndShapeRenderer(true, false);
            LinkedList<XYSeriesCollection> extraDataList = new LinkedList<XYSeriesCollection>();
            LinkedList<XYLineAndShapeRenderer> extraRendererList = new LinkedList<XYLineAndShapeRenderer>();
            for (int i = 0; i < tableModel.getRowCount(); i++) {
                if (tableModel.getValueAt(i, 0).equals(Boolean.FALSE)) {
                    standardData.addSeries(xySeriesArray[i]);
                    standardRenderer.setSeriesPaint(standardData.getSeriesCount() - 1,
                            DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i
                                    % DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length]);
                } else {
                    // extra axis
                    XYSeriesCollection extraData = new XYSeriesCollection();
                    extraData.addSeries(xySeriesArray[i]);
                    extraDataList.add(extraData);
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    extraRendererList.add(renderer);
                    renderer.setSeriesPaint(0, DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i
                            % DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length]);
                }
            }
            LinkedList<XYSeriesCollection> dataList = new LinkedList<XYSeriesCollection>();
            LinkedList<XYLineAndShapeRenderer> rendererList = new LinkedList<XYLineAndShapeRenderer>();
            if (!standardData.getSeries().isEmpty()) {
                dataList.add(standardData);
                rendererList.add(standardRenderer);
            }
            for (XYSeriesCollection data : extraDataList) {
                dataList.add(data);
            }
            for (XYLineAndShapeRenderer renderer : extraRendererList) {
                rendererList.add(renderer);
            }

            // creates axes
            LinkedList<NumberAxis> axesList = new LinkedList<NumberAxis>();
            if (!standardData.getSeries().isEmpty()) {
                NumberAxis axis = new NumberAxis(messages.getString("ModelExecutionChartPanel.Value"));
                axis.setNumberFormatOverride(NumberFormat.getInstance(locale));
                axesList.add(axis);
            }
            for (XYSeriesCollection data : extraDataList) {
                NumberAxis axis = new NumberAxis((String) data.getSeries(0).getKey());
                axis.setNumberFormatOverride(NumberFormat.getInstance(locale));
                axesList.add(axis);
            }

            // store data and axes in plot
            XYPlot plot = chart.getXYPlot();
            plot.clearRangeAxes();
            plot.setRangeAxes(axesList.toArray(new NumberAxis[0]));
            for (int i = 0; i < plot.getDatasetCount(); i++) {
                plot.setDataset(i, null);
            }
            int datasetIndex = 0;
            Iterator<XYSeriesCollection> datasetIterator = dataList.iterator();
            Iterator<XYLineAndShapeRenderer> rendererIterator = rendererList.iterator();
            while (datasetIterator.hasNext()) {
                plot.setDataset(datasetIndex, datasetIterator.next());
                plot.setRenderer(datasetIndex, rendererIterator.next());
                datasetIndex++;
            }
            for (int i = 0; i < plot.getDatasetCount(); i++) {
                plot.mapDatasetToRangeAxis(i, i);
            }
        }
    });
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.CENTER;
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(0, 0, 10, 0);
    tablePanel.add(tableScrollPane, c);
    c.gridx = 0;
    c.gridy = 1;
    tablePanel.add(axesButton, c);
    add(tablePanel, BorderLayout.LINE_END);

    // PAGE_END: number of rounds and execution button
    JPanel commandPanel = new JPanel();
    commandPanel.add(new JLabel(messages.getString("ModelExecutionChartPanel.NumberRounds")));
    final JTextField numberRoundsField = new JTextField("1", 5);
    numberRoundsField.addFocusListener(this);
    commandPanel.add(numberRoundsField);
    executionButton = new JButton(messages.getString("ModelExecutionChartPanel.ExecutionButton.Text"));
    executionButton.setToolTipText(messages.getString("ModelExecutionChartPanel.ExecutionButton.ToolTipText"));
    executionButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int numberRounds = 0;
            boolean correctNumber = false;
            try {
                numberRounds = integerNumberFormatter.parse(numberRoundsField.getText()).intValue();
            } catch (ParseException parseExcep) {
                // do nothing
            }

            if (numberRounds >= 1) {
                correctNumber = true;
            }

            if (correctNumber) {
                ModelExecutionThread executionThread = new ModelExecutionThread(numberRounds);
                executionThread.start();
            } else {
                JOptionPane.showMessageDialog(null,
                        messages.getString("ModelExecutionChartPanel.Error.Message"),
                        messages.getString("ModelExecutionChartPanel.Error.Title"), JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    commandPanel.add(executionButton);
    add(commandPanel, BorderLayout.PAGE_END);
}

From source file:JDAC.JDAC.java

public JDAC() {
    setTitle("JDAC");

    ImageIcon img = new ImageIcon("logo.png");
    setIconImage(img.getImage());//from  w  w w. j av a  2s  .  c o  m

    //setLayout(new FlowLayout());

    mDataset = createDataset("A");

    mChart = ChartFactory.createXYLineChart("Preview", "Time (ms)", "Value", mDataset, PlotOrientation.VERTICAL,
            false, true, false);

    mLastChart = ChartFactory.createXYLineChart("Last n values", "Time (ms)", "Value", createLastDataset("B"),
            PlotOrientation.VERTICAL, false, true, false);
    mChart.getXYPlot().getDomainAxis().setLowerMargin(0);
    mChart.getXYPlot().getDomainAxis().setUpperMargin(0);
    mLastChart.getXYPlot().getDomainAxis().setLowerMargin(0);
    mLastChart.getXYPlot().getDomainAxis().setUpperMargin(0);

    ChartPanel chartPanel = new ChartPanel(mChart);
    ChartPanel chartLastPanel = new ChartPanel(mLastChart);
    //chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) );

    XYPlot plot = mChart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesPaint(0, Color.GREEN);
    renderer.setSeriesStroke(0, new BasicStroke(1.0f));
    plot.setRenderer(renderer);

    XYPlot lastPlot = mLastChart.getXYPlot();
    XYLineAndShapeRenderer lastRenderer = new XYLineAndShapeRenderer();
    lastRenderer.setSeriesPaint(0, Color.RED);
    lastRenderer.setSeriesStroke(0, new BasicStroke(1.0f));
    lastPlot.setRenderer(lastRenderer);

    resetChartButton = new JButton("Reset");
    resetChartButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            resetChart();
        }
    });

    mMenuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    JMenu sensorMenu = new JMenu("Sensor");
    JMenu deviceMenu = new JMenu("Device");
    portSubMenu = new JMenu("Port");
    JMenu helpMenu = new JMenu("Help");

    serialStatusLabel = new JLabel("Disconnected");
    statusLabel = new JLabel("Ready");
    clearStatus = new LabelClear(statusLabel);
    clearStatus.resetTime();

    connectButton = new JMenuItem("Connect");
    disconnectButton = new JMenuItem("Disconnect");
    startButton = new JButton("Start");
    stopButton = new JButton("Stop");
    scanButton = new JMenuItem("Refresh port list");
    exportCSVButton = new JMenuItem("Export data to CSV");
    exportCSVButton.setAccelerator(KeyStroke.getKeyStroke("control S"));
    exportCSVButton.setMnemonic(KeyEvent.VK_S);
    exportPNGButton = new JMenuItem("Export chart to PNG");

    JPanel optionsPanel = new JPanel(new BorderLayout());

    JMenuItem exitItem = new JMenuItem("Exit");
    exitItem.setAccelerator(KeyStroke.getKeyStroke("control X"));
    exitItem.setMnemonic(KeyEvent.VK_X);

    JMenuItem aboutItem = new JMenuItem("About");
    JMenuItem helpItem = new JMenuItem("Help");
    JMenuItem quickStartItem = new JMenuItem("Quick start");

    lastSpinner = new JSpinner(new SpinnerNumberModel(10, 0, 1000, 1));

    ActionListener mSensorListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setSensor(e.getActionCommand());
        }
    };
    ButtonGroup sensorGroup = new ButtonGroup();
    JRadioButtonMenuItem tmpRadioButton = new JRadioButtonMenuItem("Temperature");
    sensorGroup.add(tmpRadioButton);
    sensorMenu.add(tmpRadioButton);
    tmpRadioButton.addActionListener(mSensorListener);
    tmpRadioButton = new JRadioButtonMenuItem("Distance");
    sensorGroup.add(tmpRadioButton);
    sensorMenu.add(tmpRadioButton);
    tmpRadioButton.addActionListener(mSensorListener);
    tmpRadioButton = new JRadioButtonMenuItem("Voltage");
    sensorGroup.add(tmpRadioButton);
    sensorMenu.add(tmpRadioButton);
    tmpRadioButton.addActionListener(mSensorListener);
    tmpRadioButton = new JRadioButtonMenuItem("Generic");
    tmpRadioButton.setSelected(true);
    setSensor("Generic");
    sensorGroup.add(tmpRadioButton);
    sensorMenu.add(tmpRadioButton);
    tmpRadioButton.addActionListener(mSensorListener);

    connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (selectedPortName == null) {
                setStatus("No port selected");
                return;
            }
            connect(selectedPortName);
        }
    });
    disconnectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            serialStatusLabel.setText("Disconnecting...");
            if (serialPort == null) {
                serialStatusLabel.setText("Disconnected");
                serialConnected = false;
                return;
            }

            stopCollect();
            disconnect();
        }
    });
    scanButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            searchForPorts();
        }
    });
    exportCSVButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            saveData();
        }
    });
    exportPNGButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            exportPNG();
        }
    });
    startButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            startCollect();
        }
    });
    stopButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            stopCollect();
        }
    });
    lastSpinner.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            numLastValues = (Integer) lastSpinner.getValue();
            updateLastTitle();
        }
    });
    updateLastTitle();
    exitItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    helpItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new HelpFrame();
        }
    });
    aboutItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new AboutFrame();
        }
    });
    quickStartItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new StartFrame();
        }
    });

    fileMenu.add(exportCSVButton);
    fileMenu.add(exportPNGButton);
    fileMenu.addSeparator();
    fileMenu.add(exitItem);
    deviceMenu.add(connectButton);
    deviceMenu.add(disconnectButton);
    deviceMenu.addSeparator();
    deviceMenu.add(portSubMenu);
    deviceMenu.add(scanButton);
    helpMenu.add(quickStartItem);
    helpMenu.add(helpItem);
    helpMenu.add(aboutItem);

    mMenuBar.add(fileMenu);
    mMenuBar.add(sensorMenu);
    mMenuBar.add(deviceMenu);
    mMenuBar.add(helpMenu);

    JPanel controlsPanel = new JPanel();
    controlsPanel.add(startButton);
    controlsPanel.add(stopButton);
    controlsPanel.add(resetChartButton);
    optionsPanel.add(controlsPanel, BorderLayout.LINE_START);

    JPanel lastPanel = new JPanel(new FlowLayout());
    lastPanel.add(new JLabel("Shown values: "));
    lastPanel.add(lastSpinner);
    optionsPanel.add(lastPanel);

    JPanel serialPanel = new JPanel(new FlowLayout());
    serialPanel.add(serialStatusLabel);
    optionsPanel.add(serialPanel, BorderLayout.LINE_END);

    add(optionsPanel, BorderLayout.PAGE_START);

    JPanel mainPanel = new JPanel(new GridLayout(0, 2));
    mainPanel.add(chartPanel);
    mainPanel.add(chartLastPanel);
    add(mainPanel);

    add(statusLabel, BorderLayout.PAGE_END);
    setJMenuBar(mMenuBar);

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            dispose();
        }
    });

    setSize(800, 800);
    pack();
    new StartFrame();

    //center on screen
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - getHeight()) / 2);
    setLocation(x, y);

    setVisible(true);
}