簡體   English   中英

單擊按鈕時如何更改背景顏色

[英]How to change Background color when i click a button

我的問題只是改變顏色的一小部分。當我單擊這些按鈕時,我想更改整個背景。我已經在Google中搜索了,什么也沒發生。

我使用面板,但它似乎可以更改的不僅只有一小部分,我需要整個背景。

import java.awt.event.MouseListener;
import javax.swing.JOptionPane;
import java.awt.event.*;
/**
 *
 * 
 * @author Christopher Porras
 * @Version 0.1
 * @Doing GUI
 */
public class Button extends JFrame {

   private JButton bred;
   private JButton bblue;
   private JButton bgreen;
   private JPanel mousepanel; 


    public Button()
    {
        super("ChangeColor");
        setLayout(new FlowLayout());
        setSize(200,200);

        mousepanel = new JPanel();
        mousepanel.setBackground(Color.white);
        add(mousepanel);

        bred = new JButton("REd");
        add(bred);

        bblue = new JButton("Blue");
        add(bblue);

        bgreen = new JButton("Green");
        add(bgreen);

        thehandler handler = new thehandler();
        bred.addMouseListener(handler);
        bblue.addMouseListener(handler);
        bgreen.addMouseListener(handler);
    }

    private class thehandler implements MouseListener
    {


        public void mouseClicked(MouseEvent e)
        {
            if(e.getSource()==bred)
            {
                mousepanel.setBackground(Color.red);
            }

             else if(e.getSource()==bblue)
            {
                mousepanel.setBackground(Color.blue);
            }

             else if(e.getSource()==bgreen)
            {
                mousepanel.setBackground(Color.green);
            }
        }


        public void mousePressed(MouseEvent e) {

        }

        public void mouseReleased(MouseEvent e) {

        }


        public void mouseEntered(MouseEvent e) {

        }


        public void mouseExited(MouseEvent e) {
              //To change body of generated methods, choose Tools | Templates.
        }



    }

    public static void main(String[]args)
    {
        Button button = new Button();
        button.setVisible(true);
        button.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

您處在正確的軌道上,但是您需要將事件綁定到按鈕組件,而不是鼠標的中斷信號。

代替MouseListener,將theHandler更改為:

  public class TheActionHandler implements ActionListener {

      @Override
      public void actionPerformed(final ActionEvent e) {
           if(e.getSource()==bred)
        {
            mousepanel.setBackground(Color.red);
        }

         else if(e.getSource()==bblue)
        {
            mousepanel.setBackground(Color.blue);
        }

         else if(e.getSource()==bgreen)
        {
            mousepanel.setBackground(Color.green);
        }
      }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM