jbuttondemo.java

来自「Swing入门必看 Swing Demo」· Java 代码 · 共 82 行

JAVA
82
字号
package components;

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;

public class JButtonDemo extends JFrame implements ItemListener {

	private static final long serialVersionUID = 1L;

	private AbstractButton abs;

	JToggleButton enableButton;

	public JButtonDemo() {

		JButton[] buttons = new JButton[4];
		Icon image = new ImageIcon("image\\1.gif");
		buttons[0] = new JButton();
		buttons[1] = new JButton(image);
		buttons[2] = new JButton("OK");
		buttons[3] = new JButton("OK", image);
		buttons[3].setBackground(Color.RED);
		buttons[3].setHorizontalTextPosition(SwingConstants.LEFT);
		buttons[3].setVerticalTextPosition(SwingConstants.TOP);
		JPanel panel = new JPanel();
		enableButton = new JToggleButton("Enable", true);
		enableButton.addItemListener(this);
		abs = new JRadioButton("OK", image);
		abs.setIcon(new ImageIcon("image\\1.gif"));
		abs.setRolloverIcon(new ImageIcon("image\\2.gif"));
		abs.setPressedIcon(new ImageIcon("image\\3.gif"));
		abs.setSelectedIcon(new ImageIcon("image\\4.gif"));
		abs.setRolloverSelectedIcon(new ImageIcon("image\\5.gif"));
		abs.setDisabledIcon(new ImageIcon("image\\6.gif"));
		abs.setDisabledSelectedIcon(new ImageIcon("image\\7.gif"));
		Container container = getContentPane();
		container.setLayout(new FlowLayout());
		for (JButton button : buttons) {
			container.add(button);
		}
		JLabel displayLabel = new JLabel("Click game:");
		displayLabel.setHorizontalTextPosition(SwingConstants.LEADING);
		displayLabel.setVerticalTextPosition(SwingConstants.TOP);
		panel.add(displayLabel);
		panel.add(enableButton);
		panel.add(abs);
		panel.setBorder(LineBorder.createBlackLineBorder());

		container.add(panel);
		setSize(400, 300);
		setVisible(true);
	}

	public void itemStateChanged(ItemEvent e) {

		abs.setEnabled(enableButton.isSelected());

	}

	public static void main(String[] args) {
		JButtonDemo application = new JButtonDemo();
		application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}

}

⌨️ 快捷键说明

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