Java图形界面,实现菜单选项下拉功能

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class IsMenuItem extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;
	JMenuItem miBlue = new JMenuItem("Blue");
	JMenuItem miGreen = new JMenuItem("Green");
	JMenuItem miRed = new JMenuItem("Red");
	JTextField tfMain = new JTextField(20);

	public IsMenuItem() {
		this.setSize(600, 400);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JMenuBar menuBar = new JMenuBar();
		JMenu menuColor = new JMenu("Color");
		menuBar.add(menuColor);
		menuColor.add(miBlue);
		menuColor.add(miGreen);
		menuColor.add(miRed);
		this.getContentPane().add(menuBar, BorderLayout.NORTH);
		JPanel panel = new JPanel();
		this.getContentPane().add(panel, BorderLayout.CENTER);
		panel.add(tfMain);
		tfMain.setBorder(BorderFactory.createLoweredBevelBorder());
		miBlue.addActionListener(this);
		miGreen.addActionListener(this);
		miRed.addActionListener(this);
		this.setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == miBlue) {
			tfMain.setBackground(Color.BLUE);
		} else if (e.getSource() == miGreen) {
			tfMain.setBackground(Color.GREEN);
		} else if (e.getSource() == miRed) {
			tfMain.setBackground(Color.RED);
		}
	}

	public static void main(String[] args) {
		new IsMenuItem();
	}

}

 

你可能感兴趣的:(Swing)