将JComboBox与ItemListener / ActionListener一起使用

时间:2014-03-10 03:38:44

标签: 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);
    }
}

1 个答案:

答案 0 :(得分:2)

为了清楚和其他原因,我会避免上课implements ActionListener。只需为每个ActionListener添加匿名JComboBox即可。像这样的东西

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中实际呈现的字体样式,以及从系统字体中获取的所有字体。这是一瞥。不要忘记在链接中向上投票!

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