单击按钮时如何更改背景颜色 [英] How to change Background color when i click a button
本文介绍了单击按钮时如何更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题只是改变颜色的一小部分.当我单击这些按钮时,我想更改整个背景.我已经在Google中搜索了,什么也没发生.
My Problem is only just a little part that change color.I want to change the whole background when i click those buttons.I search already in google nothing happens.
我使用面板,但是似乎可以改变的只有一小部分,我想要整个背景.
I Use Panel but it seems not only a little part that it can changes i want a whole background.
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);
}
推荐答案
您处在正确的轨道上,但是您需要将事件绑定到按钮组件,而不是鼠标的中断信号.
You're on the right track, but you need to tie the events to the button components rather than the interrupt signals of the mouse.
而不是MouseListener,将theHandler
更改为此:
Instead of a MouseListener, change theHandler
to this:
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);
}
}
}
这篇关于单击按钮时如何更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文