java创建下拉菜单并显示文件
鼠标移上去后显示下拉菜单内容↓
保存
另存为
你们自己知道啥意思,有功能的
office一样的
下拉菜单创建代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MenuTest extends JFrame implements ActionListener
{
private JButton redBt,greenBt,blueBt;
//定义菜单有关的一些对象
JMenuBar menuBar;//菜单栏
JMenu colorMenu;//设置窗体背景颜色的菜单
JMenuItem[] colorMenuItems;//设置窗体背景颜色的菜单项数组
private void initButton()
//初始化按钮的方法
{
this.setLayout(null);
redBt = new JButton("红色");
redBt.setSize(60, 30);
redBt.setLocation(30, 30);
this.add(redBt);
greenBt = new JButton("绿色");
greenBt.setSize(60, 30);
greenBt.setLocation(120, 30);
this.add(greenBt);
blueBt = new JButton("蓝色");
blueBt.setSize(60, 30);
blueBt.setLocation(210, 30);
this.add(blueBt);
redBt.addActionListener(this);
greenBt.addActionListener(this);
blueBt.addActionListener(this);
}
//初始化菜单的方法
private void initMenu()
{
colorMenu=new JMenu("设置窗体背景");
String[] colors={"红色","绿色","蓝色"};
colorMenuItems=new JMenuItem[3];
//定义一个包含3个菜单项的数组
for(int i=0;i<3;i++)
{
colorMenuItems[i]=new JMenuItem(colors[i]);
//初始化每个菜单项,给菜单项进行文本的赋值
colorMenuItems[i].addActionListener(this);
//注册事件源菜单项和事件处理对象
colorMenu.add(colorMenuItems[i]);
//以菜单为对象,调用方法来添加菜单所包含的菜单项
}
menuBar=new JMenuBar();//初始化菜单栏
menuBar.add(colorMenu);//将菜单添加到菜单栏上
this.setJMenuBar(menuBar);
//以窗体为对象,调用方法来设置窗体的菜单栏
}
public MenuTest()
{
this.setSize(300, 300);
this.setTitle("菜单实例");
initMenu();
initButton();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
AbstractButton item=(AbstractButton)e.getSource();
//将动作事件的事件源强制转换为抽象的按钮对象
if(item.getText().equals("红色"))
{
this.getContentPane().setBackground(Color.red);
}
else
{
if(item.getText().equals("绿色"))
{
this.getContentPane().setBackground(Color.green);
}
else
{
this.getContentPane().setBackground(Color.blue);
}
}
}
}
或翻译一下下面的代码
import javax.swing.*;
public class Newframe extends JFrame {
public Newframe(){
this.setSize(300,200);
this.setLocation(300,400);
this.setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
还有
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Menu extends JFrame implements ActionListener {
//定义两个按钮
private JButton Game_Start;
private JButton Game_Over;
public Menu(){
//定义按钮的排列方式
setLayout(new FlowLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(300,200);
this.setLocation(300,400);
Game_Start = new JButton("开启编辑器");
Game_Over = new JButton("结束");
this.add(Game_Start);
this.add(Game_Over);
Game_Start.addActionListener(this);
Game_Over.addActionListener(this);
this.setVisible(true);
}
public static void main(String[] args) {
Menu menu = new Menu();
}
/**
* Invoked when an action occurs.
*
* @param e
*/
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == Game_Start){
this.dispose();
new Newframe();
}
if(e.getSource() == Game_Over){
this.dispose();
System.exit(0);
}
}
}
不对的地方告诉我