buttontest.java

来自「this is my java buttonTest」· Java 代码 · 共 71 行

JAVA
71 行
字号
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonTest {
public static void main(String[] args)
{
	ButtonFrame frame=new ButtonFrame();
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.setVisible(true);
	}
}
class ButtonFrame extends JFrame
{
	public ButtonFrame()
	{
		setTitle("ButtonTest");
		 Toolkit kit=Toolkit.getDefaultToolkit();
		 Dimension screenSize=kit.getScreenSize();
		 int screenHeight=screenSize.height;
		 int screenWidth=screenSize.width;
		 setSize(screenWidth/2,screenHeight/2);
		 setLocation(screenWidth/4,screenHeight/4);
		 //Image img=kit.getImage("icon.gif");
		// setIconImage(img);
		 //setTitle("CenteredFrame");
	 
		
		//setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
		
		ButtonPanel panel=new ButtonPanel();
		add(panel);
		
	}
	public static final int DEFAULT_WIDTH=300;
	public static final int DEFAULT_HEIGHT=200;
	}
class ButtonPanel extends JPanel
{
	public ButtonPanel()
	{
		JButton yellowButton=new JButton("Yellow");
		JButton blueButton=new JButton("Blue");
		JButton redButton=new JButton("Red");
		
		add(yellowButton);
		add(blueButton);
		add(redButton);
		
		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
	{
		public ColorAction(Color c)
		{
			backgroundColor=c;
		}
	public void actionPerformed(ActionEvent event)
	{
		setBackground(backgroundColor);
	}
	private Color backgroundColor;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?