
2、创建菜单项(如新建、打开、保存)
3、将菜单项添加到菜单(如将新建、打开、保存菜单项添加到文件菜单)
4、创建菜单栏,将菜单添加到菜单栏
5、设置窗口的菜单栏
核心代码:
//创建窗口
JFrame w=new JFrame("包含菜单栏的窗口")
//创建文件菜单
JMenu file=new JMenu("文件")
//创建新建菜单项
JMenuItem n=new JMenuItem("新建")
//创建打开菜单项
JMenuItem o=new JMenuItem("打开")
//创建保存菜单项
JMenuItem s=new JMenuItem("保存")
//将新建菜单项添加到文件菜单
file.add(n)
//将打开菜单项添加到文件菜单
file.add(o)
//将保存菜单项添加到文件菜单
file.add(s)
//创建菜单栏
JMenuBar br=new JMenuBar()
//将文件菜单添加到菜单栏
br.add(file)
//为窗口设置菜单栏
w.setJMenuBar(br)
import java.awt.BorderLayoutimport java.awt.Color
import java.awt.Container
import java.awt.Dimension
import java.awt.FlowLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JMenu
import javax.swing.JMenuBar
import javax.swing.JMenuItem
import javax.swing.JPanel
public class jiemian extends JFrame
{
private JLabel jl = new JLabel ("第一关")
private Container container = new JPanel ()
private static Thread t
int time = 0
public jiemian ()
{
JMenuBar menuBar = new JMenuBar ()
setJMenuBar (menuBar)
JMenu[] menu = new JMenu[] { new JMenu ("游戏"), new JMenu ("帮助") }
JMenuItem[] menuItem =
new JMenuItem[] { new JMenuItem ("新游戏"), new JMenuItem ("重新开始"), new JMenuItem ("记录"),
new JMenuItem ("退出"), new JMenuItem (" *** 作方法") }
for ( int i = 0 i < 2 i++ )
{
menuBar.add (menu[i])
}
for ( int i = 0 i < 4 i++ )
{
menu[0].add (menuItem[i])
}
menu[1].add (menuItem[4])
menuItem[3].addActionListener (new ActionListener ()
{
public void actionPerformed ( ActionEvent e )
{
System.exit (0)
}
})
t = new Thread (new Runnable ()
{
public void run ()
{
while (time <= 200)
{
if (time % 2 == 0)
{
container.add (jl)
jl.setBounds (200, 200, 80, 80)
}
else
jl.setBounds (0, 0, 0, 0)
try
{
Thread.sleep (1000)
}
catch (Exception e)
{
e.printStackTrace ()
}
time++
if (time == 200)
{
time = 0
}
}
}
})
t.start ()
this.setLayout (null)
container.setLayout (null)
container.setSize (500, 500)
container.setBackground (Color.BLUE)
this.add (container)
this.setTitle ("坦克大战")
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE)
this.setSize (700, 600)
this.setLocationRelativeTo (null)
this.setVisible (true)
}
public static void main ( String[] args )
{
new jiemian ()
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)