您的位置:首页 > 编程语言 > Java开发

Java处理按键事件

2014-12-12 15:10 253 查看
import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class ButtonFrameTest {

public static void main(String[] args) {

// TODO Auto-generated method stub

EventQueue.invokeLater(new Runnable()

{

public void run()

{

ButtonFrame bf=new ButtonFrame();

bf.setTitle("ButtonFrame");

bf.setDefaultCloseOperation(ButtonFrame.EXIT_ON_CLOSE);

bf.setVisible(true);

}

});

}

}

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class ButtonFrame extends JFrame{

private JPanel buttonPanel;

private static final int DEFAULT_WIDTH=300;

private static final int DEFAULT_HEIGHT=200;

public ButtonFrame()

{

setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);

JButton yellowButton=new JButton("Yellow");

JButton blueButton=new JButton("Blue");

JButton redButton=new JButton("Red");

buttonPanel=new JPanel();

buttonPanel.add(yellowButton);

buttonPanel.add(blueButton);

buttonPanel.add(redButton);

add(buttonPanel);

ColorAction yellowAction=new ColorAction(Color.YELLOW);

ColorAction blueAction=new ColorAction(Color.BLUE);

ColorAction redAction=new ColorAction(Color.red);

yellowButton.addActionListener(yellowAction);

blueButton.addActionListener(blueAction);

redButton.addActionListener(redAction);

}

private class ColorAction implements ActionListener

{

private Color backgroundColor;

public ColorAction(Color c)

{

backgroundColor=c;

}

public void actionPerformed(ActionEvent event)

{

buttonPanel.setBackground(backgroundColor);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: