Search in sources :

Example 41 with TextField

use of java.awt.TextField in project jgnash by ccavanaugh.

the class PayeePieChart method createPanel.

private JPanel createPanel() {
    JButton refreshButton = new JButton(rb.getString("Button.Refresh"));
    JButton addFilterButton = new JButton(rb.getString("Button.AddFilter"));
    final JButton saveButton = new JButton(rb.getString("Button.SaveFilters"));
    JButton deleteFilterButton = new JButton(rb.getString("Button.DeleteFilter"));
    JButton clearPrefButton = new JButton(rb.getString("Button.MasterDelete"));
    filterCombo = new JComboBox<>();
    startField = new DatePanel();
    endField = new DatePanel();
    txtAddFilter = new TextField();
    filterList = new ArrayList<>();
    filtersChanged = false;
    useFilters = new JCheckBox(rb.getString("Label.UseFilters"));
    useFilters.setSelected(true);
    showPercentCheck = new JCheckBox(rb.getString("Button.ShowPercentValues"));
    combo = AccountListComboBox.getFullInstance();
    final LocalDate dStart = DateUtils.getFirstDayOfTheMonth(LocalDate.now().minusYears(DEBIT));
    long start = pref.getLong(START_DATE, DateUtils.asEpochMilli(dStart));
    startField.setDate(DateUtils.asLocalDate(start));
    currentAccount = combo.getSelectedAccount();
    PieDataset[] data = createPieDataSet(currentAccount);
    JFreeChart chartCredit = createPieChart(currentAccount, data, CREDIT);
    chartPanelCredit = new ChartPanel(chartCredit, true, true, true, false, true);
    //                         (chart, properties, save, print, zoom, tooltips)
    JFreeChart chartDebit = createPieChart(currentAccount, data, DEBIT);
    chartPanelDebit = new ChartPanel(chartDebit, true, true, true, false, true);
    FormLayout layout = new FormLayout("p, $lcgap, 70dlu, 8dlu, p, $lcgap, 70dlu, $ugap, p, $lcgap:g, left:p", "d, $rgap, d, $ugap, f:p:g, $rgap, d");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);
    layout.setRowGroups(new int[][] { { DEBIT, 3 } });
    // row 1
    builder.append(combo, 9);
    builder.append(useFilters);
    builder.nextLine();
    builder.nextLine();
    // row 3
    builder.append(rb.getString("Label.StartDate"), startField);
    builder.append(rb.getString("Label.EndDate"), endField);
    builder.append(refreshButton);
    builder.append(showPercentCheck);
    builder.nextLine();
    builder.nextLine();
    // row 5
    FormLayout subLayout = new FormLayout("180dlu:g, 1dlu, 180dlu:g", "f:180dlu:g");
    DefaultFormBuilder subBuilder = new DefaultFormBuilder(subLayout);
    subBuilder.append(chartPanelCredit);
    subBuilder.append(chartPanelDebit);
    builder.append(subBuilder.getPanel(), 11);
    builder.nextLine();
    builder.nextLine();
    // row 7
    builder.append(txtAddFilter, 3);
    builder.append(addFilterButton, 3);
    builder.append(saveButton);
    builder.nextLine();
    // row
    builder.append(filterCombo, 3);
    builder.append(deleteFilterButton, 3);
    builder.append(clearPrefButton);
    builder.nextLine();
    JPanel panel = builder.getPanel();
    combo.addActionListener(e -> {
        Account newAccount = combo.getSelectedAccount();
        if (filtersChanged) {
            int result = JOptionPane.showConfirmDialog(null, rb.getString("Message.SaveFilters"), "Warning", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                saveButton.doClick();
            }
        }
        filtersChanged = false;
        String[] list = POUND_DELIMITER_PATTERN.split(pref.get(FILTER_TAG + newAccount.hashCode(), ""));
        filterList.clear();
        for (String filter : list) {
            if (!filter.isEmpty()) {
                filterList.add(filter);
            }
        }
        refreshFilters();
        setCurrentAccount(newAccount);
        pref.putLong(START_DATE, DateUtils.asEpochMilli(startField.getLocalDate()));
    });
    refreshButton.addActionListener(e -> {
        setCurrentAccount(currentAccount);
        pref.putLong(START_DATE, DateUtils.asEpochMilli(startField.getLocalDate()));
    });
    clearPrefButton.addActionListener(e -> {
        int result = JOptionPane.showConfirmDialog(null, rb.getString("Message.MasterDelete"), "Warning", JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            try {
                pref.clear();
            } catch (Exception ex) {
                System.out.println("Exception clearing preferences" + ex);
            }
        }
    });
    saveButton.addActionListener(e -> {
        final StringBuilder sb = new StringBuilder();
        for (String filter : filterList) {
            sb.append(filter);
            sb.append('#');
        }
        pref.put(FILTER_TAG + currentAccount.hashCode(), sb.toString());
        filtersChanged = false;
    });
    addFilterButton.addActionListener(e -> {
        String newFilter = txtAddFilter.getText();
        filterList.remove(newFilter);
        if (!newFilter.isEmpty()) {
            filterList.add(newFilter);
            filtersChanged = true;
            txtAddFilter.setText("");
        }
        refreshFilters();
    });
    deleteFilterButton.addActionListener(e -> {
        if (!filterList.isEmpty()) {
            String filter = (String) filterCombo.getSelectedItem();
            filterList.remove(filter);
            filtersChanged = true;
        }
        refreshFilters();
    });
    useFilters.addActionListener(e -> setCurrentAccount(currentAccount));
    showPercentCheck.addActionListener(e -> {
        ((PiePlot) chartPanelCredit.getChart().getPlot()).setLabelGenerator(showPercentCheck.isSelected() ? percentLabels : defaultLabels);
        ((PiePlot) chartPanelDebit.getChart().getPlot()).setLabelGenerator(showPercentCheck.isSelected() ? percentLabels : defaultLabels);
    });
    return panel;
}
Also used : FormLayout(com.jgoodies.forms.layout.FormLayout) JPanel(javax.swing.JPanel) Account(jgnash.engine.Account) ChartPanel(org.jfree.chart.ChartPanel) JButton(javax.swing.JButton) LocalDate(java.time.LocalDate) JFreeChart(org.jfree.chart.JFreeChart) JCheckBox(javax.swing.JCheckBox) PieDataset(org.jfree.data.general.PieDataset) DefaultPieDataset(org.jfree.data.general.DefaultPieDataset) DatePanel(jgnash.ui.components.DatePanel) DefaultFormBuilder(com.jgoodies.forms.builder.DefaultFormBuilder) TextField(java.awt.TextField) PiePlot(org.jfree.chart.plot.PiePlot)

Example 42 with TextField

use of java.awt.TextField in project java-design-patterns by iluwatar.

the class View method createView.

/**
 * initialize the GUI.
 */
public void createView() {
    var frame = new JFrame("Album");
    var b1 = Box.createHorizontalBox();
    frame.add(b1);
    albumList = new JList<>(model.getAlbumList());
    albumList.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(final MouseEvent e) {
            model.setSelectedAlbumNumber(albumList.getSelectedIndex() + 1);
            loadFromPMod();
        }
    });
    b1.add(albumList);
    var b2 = Box.createVerticalBox();
    b1.add(b2);
    txtArtist = new TextField();
    txtTitle = new TextField();
    txtArtist.setSize(WIDTH_TXT, HEIGHT_TXT);
    txtTitle.setSize(WIDTH_TXT, HEIGHT_TXT);
    chkClassical = new JCheckBox();
    txtComposer = new TextField();
    chkClassical.addActionListener(itemEvent -> {
        txtComposer.setEditable(chkClassical.isSelected());
        if (!chkClassical.isSelected()) {
            txtComposer.setText("");
        }
    });
    txtComposer.setSize(WIDTH_TXT, HEIGHT_TXT);
    txtComposer.setEditable(model.getIsClassical());
    apply = new JButton("Apply");
    apply.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(final MouseEvent e) {
            saveToPMod();
            loadFromPMod();
        }
    });
    cancel = new JButton("Cancel");
    cancel.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(final MouseEvent e) {
            loadFromPMod();
        }
    });
    b2.add(txtArtist);
    b2.add(txtTitle);
    b2.add(chkClassical);
    b2.add(txtComposer);
    b2.add(apply);
    b2.add(cancel);
    frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    frame.setBounds(LOCATION_X, LOCATION_Y, WIDTH, HEIGHT);
    frame.setVisible(true);
}
Also used : JCheckBox(javax.swing.JCheckBox) MouseEvent(java.awt.event.MouseEvent) JFrame(javax.swing.JFrame) MouseAdapter(java.awt.event.MouseAdapter) JButton(javax.swing.JButton) TextField(java.awt.TextField)

Example 43 with TextField

use of java.awt.TextField in project JSettlers2 by jdmonin.

the class SOCPlayerInterface method initInterfaceElements.

/**
 * Setup the interface elements
 *
 * @param firstCall First setup call for this window; do global things
 *   such as windowListeners, not just component-specific things.
 */
protected void initInterfaceElements(boolean firstCall) {
    /**
     * initialize the text input and display and add them to the interface.
     * Moved first so they'll be at top of the z-order, for use with textDisplaysLargerTemp.
     * In 6-player games, these text areas' sizes are "zoomed" larger temporarily when
     * the mouse hovers over them, for better visibility.
     */
    textDisplaysLargerTemp = false;
    textDisplaysLargerTemp_needsLayout = false;
    textDisplaysLargerWhen = 0L;
    textInputHasMouse = false;
    textDisplayHasMouse = false;
    chatDisplayHasMouse = false;
    sbFixNeeded = false;
    sbFixLHasMouse = false;
    sbFixRHasMouse = false;
    sbFixBHasMouse = false;
    if (firstCall && is6player)
        // react when mouse leaves the Frame
        addMouseListener(this);
    textDisplay = new SnippingTextArea("", 40, 80, TextArea.SCROLLBARS_VERTICAL_ONLY, 80);
    textDisplay.setFont(new Font("SansSerif", Font.PLAIN, 10));
    textDisplay.setBackground(new Color(255, 230, 162));
    textDisplay.setForeground(Color.black);
    textDisplay.setEditable(false);
    add(textDisplay);
    if (is6player)
        textDisplay.addMouseListener(this);
    chatDisplay = new SnippingTextArea("", 40, 80, TextArea.SCROLLBARS_VERTICAL_ONLY, 100);
    chatDisplay.setFont(new Font("SansSerif", Font.PLAIN, 10));
    chatDisplay.setBackground(new Color(255, 230, 162));
    chatDisplay.setForeground(Color.black);
    chatDisplay.setEditable(false);
    if (is6player)
        chatDisplay.addMouseListener(this);
    add(chatDisplay);
    textInput = new TextField();
    textInput.setFont(new Font("SansSerif", Font.PLAIN, 10));
    textInputListener = new SOCPITextfieldListener(this);
    textInputHasSent = false;
    textInputGreyCountdown = textInputGreyCountFrom;
    textInput.addKeyListener(textInputListener);
    textInput.addTextListener(textInputListener);
    textInput.addFocusListener(textInputListener);
    FontMetrics fm = this.getFontMetrics(textInput.getFont());
    textInput.setSize(SOCBoardPanel.PANELX, fm.getHeight() + 4);
    // new Color(255, 230, 162));
    textInput.setBackground(Color.white);
    textInput.setForeground(Color.black);
    textInput.setEditable(false);
    // due to "please wait"
    textInputIsInitial = false;
    // "Please wait..."
    textInput.setText(strings.get("base.please.wait"));
    add(textInput);
    textInput.addActionListener(this);
    if (is6player)
        textInput.addMouseListener(this);
    /**
     * initialize the player hand displays and add them to the interface
     */
    hands = new SOCHandPanel[game.maxPlayers];
    for (int i = 0; i < hands.length; i++) {
        SOCHandPanel hp = new SOCHandPanel(this, game.getPlayer(i));
        hands[i] = hp;
        hp.setSize(180, 120);
        add(hp);
        ColorSquare blank = hp.getBlankStandIn();
        blank.setSize(180, 120);
        add(blank);
    }
    /**
     * initialize the building interface and add it to the main interface
     */
    buildingPanel = new SOCBuildingPanel(this);
    buildingPanel.setSize(200, SOCBuildingPanel.MINHEIGHT);
    add(buildingPanel);
    /**
     * initialize the game board display and add it to the interface
     */
    boardPanel = new SOCBoardPanel(this);
    // sea blue; briefly visible at start before water tiles are drawn
    boardPanel.setBackground(new Color(63, 86, 139));
    boardPanel.setForeground(Color.black);
    Dimension bpMinSz = boardPanel.getMinimumSize();
    boardPanel.setSize(bpMinSz.width, bpMinSz.height);
    boardIsScaled = false;
    add(boardPanel);
    if (game.isGameOptionDefined("PL")) {
        updatePlayerLimitDisplay(true, false, -1);
    // Player data may not be received yet;
    // game is created empty, then SITDOWN messages are received from server.
    // gameState is at default 0 (NEW) during JOINGAMEAUTH and SITDOWN.
    // initInterfaceElements is also called at board reset.
    // updatePlayerLimitDisplay will check the current gameState.
    }
    /**
     * In 6-player games, text areas temporarily zoom when the mouse is over them.
     * On windows, the scrollbars aren't considered part of the text areas, so
     * we get a mouseExited when user is trying to scroll the text area.
     * Workaround: Instead of looking for mouseExited, look for mouseEntered on
     * handpanels or boardpanel.
     */
    if (is6player) {
        if (SOCPI_isPlatformWindows) {
            sbFixNeeded = true;
            // upper-left
            hands[0].addMouseListener(this);
            // upper-right
            hands[1].addMouseListener(this);
            boardPanel.addMouseListener(this);
        // Note not just on firstCall,
        // because hands[] is initialized above.
        }
    }
    if (firstCall) {
        // If player requests window close, ask if they're sure, leave game if so
        addWindowListener(new PIWindowAdapter(gameDisplay, this));
    }
}
Also used : Color(java.awt.Color) Dimension(java.awt.Dimension) Font(java.awt.Font) FontMetrics(java.awt.FontMetrics) TextField(java.awt.TextField)

Example 44 with TextField

use of java.awt.TextField in project JSettlers2 by jdmonin.

the class NewGameOptionsFrame method readOptsValuesFromControls.

/**
 * Read option values from controls, as prep to request the new game.
 * If there is a problem (out of range, bad character in integer field, etc),
 * set {@link #msgText} and set focus on the field.
 * @param checkOptionsMinVers Warn the user if the options will require a
 *           minimum client version?  Won't do so if {@link #forPractice} is set,
 *           because this isn't a problem for local practice games.
 *           The warning is skipped if that minimum is an old version
 *           &lt;= {@link Version#versionNumberMaximumNoWarn()}.
 * @return true if all were read OK, false if a problem (such as NumberFormatException)
 */
private boolean readOptsValuesFromControls(final boolean checkOptionsMinVers) {
    if (readOnly)
        // shouldn't be called in that case
        return false;
    boolean allOK = true;
    for (Component ctrl : controlsOpts.keySet()) {
        if (ctrl instanceof Label)
            continue;
        SOCGameOption op = controlsOpts.get(ctrl);
        if (op.key.equals("SC")) {
            // Special case: AWT event listeners have already set its value from controls
            if (!op.getBoolValue())
                op.setStringValue("");
            continue;
        }
        if (ctrl instanceof Checkbox) {
            op.setBoolValue(((Checkbox) ctrl).getState());
        } else if (ctrl instanceof TextField) {
            String txt = ((TextField) ctrl).getText().trim();
            if ((op.optType == SOCGameOption.OTYPE_STR) || (op.optType == SOCGameOption.OTYPE_STRHIDE)) {
                try {
                    op.setStringValue(txt);
                } catch (IllegalArgumentException ex) {
                    allOK = false;
                    // only a single line of text allowed
                    msgText.setText(strings.get("game.options.singleline"));
                    ctrl.requestFocusInWindow();
                }
            } else {
            // OTYPE_INT, OTYPE_INTBOOL; defer setting until after all checkboxes have been read
            }
        } else if (ctrl instanceof Choice) {
            // this works with OTYPE_INT, OTYPE_INTBOOL, OTYPE_ENUM, OTYPE_ENUMBOOL
            // 0 to n-1
            int chIdx = ((Choice) ctrl).getSelectedIndex();
            if (chIdx != -1)
                op.setIntValue(chIdx + op.minIntValue);
            else
                allOK = false;
        }
    }
    // Use 0 if blank (still checks if in range).
    for (Component ctrl : controlsOpts.keySet()) {
        if (!(ctrl instanceof TextField))
            continue;
        SOCGameOption op = controlsOpts.get(ctrl);
        if (op.optType == SOCGameOption.OTYPE_INTBOOL) {
            if (!op.getBoolValue())
                continue;
        } else if (op.optType != SOCGameOption.OTYPE_INT) {
            continue;
        }
        String txt = ((TextField) ctrl).getText().trim();
        try {
            int iv;
            if (txt.length() > 0)
                iv = Integer.parseInt(txt);
            else
                iv = 0;
            op.setIntValue(iv);
            if (iv != op.getIntValue()) {
                allOK = false;
                msgText.setText(// "out of range"
                strings.get("game.options.outofrange", op.minIntValue, op.maxIntValue));
                ctrl.requestFocusInWindow();
            }
        } catch (NumberFormatException ex) {
            allOK = false;
            // "please use only digits here"
            msgText.setText(strings.get("game.options.onlydigits"));
            ctrl.requestFocusInWindow();
        }
    }
    if (allOK && checkOptionsMinVers && !forPractice) {
        int optsVers = SOCVersionedItem.itemsMinimumVersion(controlsOpts);
        if ((optsVers > -1) && (optsVers > Version.versionNumberMaximumNoWarn())) {
            allOK = false;
            new VersionConfirmDialog(this, optsVers).setVisible(true);
        }
    }
    return allOK;
}
Also used : Choice(java.awt.Choice) Checkbox(java.awt.Checkbox) SOCGameOption(soc.game.SOCGameOption) Label(java.awt.Label) TextField(java.awt.TextField) Component(java.awt.Component)

Example 45 with TextField

use of java.awt.TextField in project JSettlers2 by jdmonin.

the class NewGameOptionsFrame method initOption_int.

/**
 * Based on this game option's type, present its intvalue either as
 * a numeric textfield, or a popup menu if min/max are near each other.
 * The maximum min/max distance which creates a popup is {@link #INTFIELD_POPUP_MAXRANGE}.
 * @param op A SOCGameOption with an integer value, that is,
 *           of type {@link SOCGameOption#OTYPE_INT OTYPE_INT}
 *           or {@link SOCGameOption#OTYPE_INTBOOL OTYPE_INTBOOL}
 * @return an IntTextField or {@link java.awt.Choice} (popup menu)
 */
private Component initOption_int(SOCGameOption op) {
    // OTYPE_* - if a new type is added, update this method's javadoc.
    int optrange = op.maxIntValue - op.minIntValue;
    Component c;
    if ((optrange > INTFIELD_POPUP_MAXRANGE) || (optrange < 0)) {
        // IntTextField with width based on number of digits in min/max .
        int amaxv = Math.abs(op.maxIntValue);
        int aminv = Math.abs(op.minIntValue);
        final int magn;
        if (amaxv > aminv)
            magn = amaxv;
        else
            magn = aminv;
        int twidth = 1 + (int) Math.ceil(Math.log10(magn));
        if (twidth < 3)
            twidth = 3;
        c = new IntTextField(op.getIntValue(), twidth);
        // for op.ChangeListener and userChanged
        ((TextField) c).addTextListener(this);
    } else {
        Choice ch = new Choice();
        for (int i = op.minIntValue; i <= op.maxIntValue; ++i) ch.add(Integer.toString(i));
        int defaultIdx = op.getIntValue() - op.minIntValue;
        if (defaultIdx > 0)
            ch.select(defaultIdx);
        // for op.ChangeListener and userChanged
        ch.addItemListener(this);
        c = ch;
    }
    return c;
}
Also used : Choice(java.awt.Choice) TextField(java.awt.TextField) Component(java.awt.Component)

Aggregations

TextField (java.awt.TextField)56 Checkbox (java.awt.Checkbox)21 Choice (java.awt.Choice)21 Label (java.awt.Label)18 Panel (java.awt.Panel)17 Button (java.awt.Button)13 GenericDialog (ij.gui.GenericDialog)11 GridBagConstraints (java.awt.GridBagConstraints)11 GridBagLayout (java.awt.GridBagLayout)11 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)10 Color (java.awt.Color)9 Component (java.awt.Component)8 Vector (java.util.Vector)8 BorderLayout (java.awt.BorderLayout)6 FlowLayout (java.awt.FlowLayout)6 Dimension (java.awt.Dimension)5 Frame (java.awt.Frame)5 Insets (java.awt.Insets)5 Point (java.awt.Point)5 JPanel (javax.swing.JPanel)5