【问题标题】:How to change Background color when i click a button单击按钮时如何更改背景颜色
【发布时间】:2015-12-04 15:24:57
【问题描述】:

我的问题只是改变颜色的一小部分。当我点击这些按钮时,我想改变整个背景。我已经在谷歌搜索没有任何反应。

我使用面板,但它似乎不仅可以改变一小部分,我想要一个完整的背景。

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

【问题讨论】:

  • 您可能会查看 ActionListener 而不是 MouseListener。

标签: java swing jframe jpanel jbutton


【解决方案1】:

您在正确的轨道上,但您需要将事件绑定到按钮组件而不是鼠标的中断信号。

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

【讨论】:

  • 当然@Cypher。如果我回答了您的问题,请在论坛上为其他开发者标记为已解决
猜你喜欢
  • 2014-10-09
  • 2017-08-02
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多