侦听器中按钮的随机面板颜色只能使用一次

时间:2019-05-19 17:49:58

标签: java swing colors jframe jlabel

我的侦听器只执行一次方法changeColor()

尝试了不同版本的随机颜色创建器

代码:

// Java program to create a blank text
// field of definite number of columns.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Main extends JFrame implements ActionListener {
    // JTextField
    static JTextField textField;

    // JFrame
    static JFrame frame;

    // JButton
    static JButton button;

    // label to display text
    static JLabel label;

    static JPanel panel;

    // main class
    public static void main(String[] args)
    {
        // create a new frame to stor text field and button
        frame = new JFrame("textfield");

        // create a label to display text
        label = new JLabel("nothing entered");

        // create a new button
        button = new JButton("submit");

        // create a panel
        panel = new JPanel();

        // create an object of the text class
        Main te = new Main();

        // addActionListener to button
        button.addActionListener(te);

        // create an object of JTextField with 16 columns
        textField = new JTextField(16);

        // add buttons and textfield to label and then to panel
        panel.add(textField);
        panel.add(button);
        panel.add(label);

        label.setOpaque(true);

        // add panel to frame
        frame.add(panel);

        // set the size of frame
        frame.setSize(300, 300);

        panel.setBackground(Color.cyan);

        frame.show();
    }

    // if the button is pressed
    @Override
    public void actionPerformed(java.awt.event.ActionEvent e)
    {
        String s = e.getActionCommand();
        if (s.equals("submit")) {

            // set the text of the label to the text of the field
            if(textField.getText().equals("hue")) {
                panel.setBackground(changeColor());
            }

            label.setText(textField.getText());

            // set the text of field to blank
            textField.setText(" ");
        }
    }
    public Color changeColor() {
        Color randomColor = new Color((int)(Math.random() * 0x1000000));
        return randomColor;
    }
}

我希望程序在textField中键入“色相”并使用按钮提交时,一遍又一遍地创建新的颜色。 不幸的是,这只能起作用一次。

1 个答案:

答案 0 :(得分:1)

78行您的呼叫:

textField.setText(" ");

我想你想打电话:

textField.setText("");

真正使您的文本字段为空。 “”与“”不同

首次按下按钮后,文本字段将包含“”。如果您随后输入hue,则文本字段的内容为“ hue”而不是“ hue”。

因此,您在true处的if语句不是textField.getText().equals("hue"),并且您的方法没有被调用。

相关问题