带参数的setBackgroundcolor

时间:2014-07-23 09:17:48

标签: java swing colors background jtextfield

我正在尝试使用MVC-Structure创建一个小GUI,现在我希望能够在我的GUI中从Listener类设置JTextField的背景:

package gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Date;

public class Gui extends JFrame {

    private JTextField jtf;
    private JLabel lblStatus;


    public Gui() {
        new JFrame();
        jtf = new JTextField();
        //jtf.addKeyListener(this);
        lblStatus = new JLabel("Zeit:");

        setSize(700, 60);
        setTitle("Tippmaster V1.0");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setLayout(new GridLayout(1, 2));
        add(jtf);
        add(lblStatus);
        setVisible(true);

    }
    public void addKeyListener(KeyListener kl){
        jtf.addKeyListener(kl);

    public void setStatus(String status){
        lblStatus.setText(status);
    }

    /**
    * 
    * @param color should involve the information of the color for example GREEN
    */
    public void setBackgroundcolor(Color color){
        jtf.setBackground(Color.color);
    }

}

所以我不能只在Listener Class中写一下:

package controller;

import gui.Gui;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * Created by tq67 on 23.07.2014.
 */
public class CharListener implements KeyListener {

    private Gui gui;

    public CharListener(Gui gui) {
        this.gui = gui;

    }

    @Override
    public void keyPressed(KeyEvent arg0) {      /* Nothing to do */        }

    @Override
    public void keyReleased(KeyEvent arg0) {

            //Here I want to set the parameter sth like this or maybe only Green Blue etc..
            gui.setBackground(Color.GREEN);     
    }

    @Override
    public void keyTyped(KeyEvent e) {       /* Nothing to do */        }
}

这可能或者我应该将String作为参数并在GUI类中解析它吗? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

我自己发现了这个问题:

因为我将Color对象作为参数发送,所以我只能写:

public void setBackgroundcolor(Color color){
    jtf.setBackground(color);
}