【问题标题】:Using JComboBox with ItemListener/ActionListener将 JComboBox 与 ItemListener/ActionListener 一起使用
【发布时间】:2014-03-10 03:38:43
【问题描述】:

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

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);
    }
}

【问题讨论】:

    标签: java swing user-interface actionlistener jcombobox


    【解决方案1】:

    出于清楚和其他原因,我会避免将课程设为implements 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 的全局值,以便每个不同的组合框都可以使用它们并在actionPerformed 中相应地更改字体

    另外,看看this answer from AndrewThompson,在JComboBox 中显示了实际渲染的字体样式,所有字体都是从系统字体中获取的。这是一瞥。不要忘记在链接中为答案投票!


    试试这个。我修改了你的代码

    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);
                }
            });
        }
    }
    

    【讨论】:

    • 正是我想要的!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多