工具栏

package swing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import javax.swing.*;

public class ToolBarTest {
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   @Override
   public void run() {
    ToolBarFrame frame = new ToolBarFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
   }
  });
 }
}

class ToolBarFrame extends JFrame {
 public ToolBarFrame() {
  this.setTitle("ToolBar Test");
  this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  
  panel = new JPanel();
  this.add(panel, BorderLayout.CENTER);
  
  Action blueAction = new ColorAction("Blue", new ImageIcon("c:/picture/1.gif"), Color.BLUE);
  Action yellowAction = new ColorAction("Yellow", new ImageIcon("c:/picture/2.gif"), Color.YELLOW);
  Action redAction = new ColorAction("Red", new ImageIcon("c:/picture/3.gif"), Color.RED);
  Action exitAction = new AbstractAction("Exit", new ImageIcon("c:/picture/4.gif")) {
   @Override
   public void actionPerformed(ActionEvent event) {
    System.exit(0);
   }
  };
  exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
  
  //工具栏
  JToolBar toolBar = new JToolBar();
  toolBar.add(blueAction);
  toolBar.add(yellowAction);
  toolBar.add(redAction);
  toolBar.addSeparator();
  toolBar.add(exitAction);
  this.add(toolBar, BorderLayout.NORTH);
  
  //菜单栏
  JMenu menu = new JMenu("Color");
  menu.add(blueAction);
  menu.add(yellowAction);
  menu.add(redAction);
  menu.addSeparator();
  menu.add(exitAction);
  
  JMenuBar menuBar = new JMenuBar();
  menuBar.add(menu);
  this.setJMenuBar(menuBar);
 }
 
 public static final int DEFAULT_WIDTH = 300;
 public static final int DEFAULT_HEIGHT = 200;
 
 private JPanel panel;
 
 class ColorAction extends AbstractAction {
  public ColorAction(String name, Icon icon, Color c) {
   this.putValue(Action.NAME, name);
   this.putValue(Action.SMALL_ICON, icon);
   this.putValue(Action.SHORT_DESCRIPTION, name + " background");
   this.putValue("Color", c);
  }

  @Override
  public void actionPerformed(ActionEvent event) {
   Color c = (Color) this.getValue("Color");
   panel.setBackground(c);
  }
 }
}

阅读更多
个人分类: swing
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

工具栏

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭