java - 将 JComboBox 与 ItemListener/ActionListener 结合使用

标签 java swing user-interface actionlistener jcombobox

我刚刚开始用 Java 编码,想知道如何实现这一点。我想要的是用户能够在文本框中输入文本,选择字体、颜色和大小,然后单击“确定”按钮时将显示在底部的标签中。任何帮助,将不胜感激。谢谢。

package textchanger;

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class textchanger implements ActionListener {

String[] fontStrings = {"Arial", "Arial Black", "Helvetica", "Impact", "Times New Roman"};
String[] sizeStrings = {"10", "12", "14", "16", "18"};
String[] colorStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
String[] bgStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};

JPanel panel;
JLabel labelText, labelFont, labelSize, labelColor, labelBG, labelOutput;
JTextField textField;
JComboBox comboFont, comboSize, comboColor, comboBG;
JButton btnOk, btnCancel;

public JPanel contentPane() { //Creates the GUI

    panel = new JPanel();
    panel.setLayout(new GridLayout(8, 8, 10, 10));

    labelText = new JLabel("Enter Text:");
    textField = new JTextField(10);

    labelFont = new JLabel("Select font type:");
    comboFont = new JComboBox(fontStrings);
    comboFont.setSelectedIndex(0);
    comboFont.addActionListener(this);

    labelSize = new JLabel("Select font size:");
    comboSize = new JComboBox(sizeStrings);
    comboSize.setSelectedIndex(0);
    comboSize.addActionListener(this);

    labelColor = new JLabel("Select font color:");
    comboColor = new JComboBox(colorStrings);
    comboColor.setSelectedIndex(0);
    comboColor.addActionListener(this);

    labelBG = new JLabel("Select a background color:");
    comboBG = new JComboBox(bgStrings);
    comboBG.setSelectedIndex(0);
    comboBG.addActionListener(this);

    btnOk = new JButton("Ok");
    btnCancel = new JButton("Cancel");

    labelOutput = new JLabel("");

    panel.add(labelText);
    panel.add(textField);
    panel.add(labelFont);
    panel.add(comboFont);
    panel.add(labelSize);
    panel.add(comboSize);
    panel.add(labelColor);
    panel.add(comboColor);
    panel.add(labelBG);
    panel.add(comboBG);
    panel.add(btnOk);
    panel.add(btnCancel);
    panel.add(labelOutput);

    return panel;

}

public static void main(String[] args) {
    JFrame frame = new JFrame("Fonts, Colors and Sizes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(650, 350);

    textchanger txtObj = new textchanger();
    frame.setContentPane(txtObj.contentPane());
    frame.setVisible(true);
    }
}

最佳答案

为了清楚起见和其他原因,我会避免让类实现 ActionListener。只需向每个 JComboBox 添加一个匿名 ActionListener 即可。像这样的事情

JComboBox comboFont;
JLabel label = new JLabel("label");
String fontString = "ariel";
int fontWeight = Font.PLAIN;
int fontSize = 16;
Font font = new Font(fontString, fontWeight, fontSize);
Color textColor = Color.BLACK

public JPanel contentPane() {
    comboFont = new JComboBox(fontStrings);
    comboFont.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            fontString = (String)comboFont.getSelectedItem();
            font = new Font(fontString, fontWeight, fontSize);
            label.setFont(font);
        }
    });
}

这将在从组合框中选择新字体时动态更改字体。您应该具有 FontfontSizefontWeight 的全局值,以便每个不同的组合框都可以使用它们并相应地在 操作执行

此外,请查看 this answer from AndrewThompson ,显示 JComboBox 中实际渲染的字体样式,其中所有字体均从系统字体中获取。这是一瞥。不要忘记对链接中的答案进行投票!

Font Chooser


尝试一下。我修改了你的代码

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class textchanger {

    //String[] fontStrings = {"Arial", "Arial Black", "Helvetica", "Impact", "Times New Roman"};
    Integer[] fontSizes = {10, 12, 14, 16, 18, 20, 22, 24};
    String[] colorStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
    String[] bgStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
    String[] fontStyle = {"BOLD", "Italic", "Plain"};

    JPanel panel;
    JLabel labelText, labelFont, labelSize, labelColor, labelBG, labelOutput;
    JTextField textField;
    JComboBox comboFont, comboSize, comboColor, comboBG;
    JButton btnOk, btnCancel;

    String fontString;
    int fontWeight = Font.PLAIN;
    int fontSize;
    Font font = new Font(fontString, Font.PLAIN, fontSize);
    Color textColor;
    Color bgColor;

    static String text = "Text";
    static JLabel textLabel = new JLabel(text);
    JPanel textLabelPanel = new JPanel(new GridBagLayout());

    public JPanel contentPane() { //Creates the GUI

        panel = new JPanel();
        panel.setLayout(new GridLayout(7, 8, 10, 10));
        textLabelPanel.setPreferredSize(new Dimension(500, 50));

        labelText = new JLabel("Enter Text:");
        textField = new JTextField(10);
        textField.setText(text);

        textField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                String newText = textField.getText();
                textLabel.setText(newText);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                String newText = textField.getText();
                textLabel.setText(newText);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
            }

        });

        labelFont = new JLabel("Select font type:");
        GraphicsEnvironment ge = GraphicsEnvironment.
                getLocalGraphicsEnvironment();
        String[] fonts = ge.getAvailableFontFamilyNames();
        comboFont = new JComboBox(fonts);
        fontString = (String) comboFont.getItemAt(0);
        comboFont.setSelectedIndex(0);
        comboFont.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fontString = (String) comboFont.getSelectedItem();
                font = new Font(fontString, fontWeight, fontSize);
                textLabel.setFont(font);
            }
        });

        labelSize = new JLabel("Select font size:");
        comboSize = new JComboBox(fontSizes);
        comboSize.setSelectedIndex(0);
        fontSize = (Integer) comboSize.getItemAt(0);
        comboSize.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fontSize = (Integer) comboSize.getSelectedItem();
                font = new Font(fontString, fontWeight, fontSize);
                textLabel.setFont(font);
            }
        });

        labelColor = new JLabel("Select font color:");
        comboColor = new JComboBox(colorStrings);
        comboColor.setSelectedIndex(0);
        textColor = Color.RED;
        textLabel.setForeground(textColor);
        comboColor.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String colorString = (String) comboColor.getSelectedItem();
                switch (colorString) {
                    case "Red":
                        textColor = Color.RED;
                        break;
                    case "Blue":
                        textColor = Color.BLUE;
                        break;
                    case "Green":
                        textColor = Color.GREEN;
                        break;
                    case "Yellow":
                        textColor = Color.YELLOW;
                        break;
                    case "Orange":
                        textColor = Color.ORANGE;
                        break;
                    default:
                        textColor = Color.RED;
                }
                textLabel.setForeground(textColor);
            }
        });

        labelBG = new JLabel("Select a background color:");
        comboBG = new JComboBox(bgStrings);
        comboBG.setSelectedIndex(1);
        bgColor = Color.BLUE;
        textLabelPanel.setBackground(bgColor);
        comboBG.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String bgColorString = (String) comboBG.getSelectedItem();
                switch (bgColorString) {
                    case "Red":
                        bgColor = Color.RED;
                        break;
                    case "Blue":
                        bgColor = Color.BLUE;
                        break;
                    case "Green":
                        bgColor = Color.GREEN;
                        break;
                    case "Yellow":
                        bgColor = Color.YELLOW;
                        break;
                    case "Orange":
                        bgColor = Color.ORANGE;
                        break;
                    default:
                        bgColor = Color.RED;
                }
                textLabelPanel.setBackground(bgColor);
            }
        });

        btnOk = new JButton("Ok");
        btnCancel = new JButton("Cancel");

        labelOutput = new JLabel("");

        panel.add(labelText);
        panel.add(textField);
        panel.add(labelFont);
        panel.add(comboFont);
        panel.add(labelSize);
        panel.add(comboSize);
        panel.add(labelColor);
        panel.add(comboColor);
        panel.add(labelBG);
        panel.add(comboBG);
        panel.add(btnOk);
        panel.add(btnCancel);
        panel.add(labelOutput);

        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(panel);

        textLabelPanel.add(textLabel);
        mainPanel.add(textLabelPanel, BorderLayout.SOUTH);

        return mainPanel;

    }

    class FontCellRenderer extends DefaultListCellRenderer {

        public Component getListCellRendererComponent(
                JList list,
                Object value,
                int index,
                boolean isSelected,
                boolean cellHasFocus) {
            JLabel label = (JLabel) super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);
            Font font = new Font((String) value, Font.PLAIN, 20);
            label.setFont(font);
            return label;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Fonts, Colors and Sizes");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(650, 350);

                textchanger txtObj = new textchanger();
                frame.setContentPane(txtObj.contentPane());
                frame.setVisible(true);
            }
        });
    }
}

关于java - 将 JComboBox 与 ItemListener/ActionListener 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22291677/

相关文章:

java - 在 Swing 中的两个组件之间拖动

JavaScript/HTML 悬停菜单/工具栏

java - 如何为实体的 ID/名称生成随机字符串而不是数字?

java - 从数据库获取数据并将其与 JButton 一起显示在表格上

java - 使用 MapBox 生成两个位置的路线和方向

java - Jtable 值复制最后一个值

java - JPanel "Loop"/按钮被 "panel.removeAll();"重复?

java - 在 SWT UI 中删除窗口边框会禁用重新定位

java - BigDecimal 乘以 100 哪种方法更好?

java - Optional.get() 与重载 Optional.orElseThrow()