Java6学习笔记28——使用Swing创建工具栏

import javax.swing.JFrame;
import javax.swing.JToolBar;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.Image;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ToolBarDemo extends JFrame implements ActionListener {
TextArea textarea;
public static void main(String arg[]) {
ToolBarDemo tbd = new ToolBarDemo();
}
public ToolBarDemo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildFrame();
setLocation(250,150);
setSize(300,200);
setVisible(true);
}
private void buildFrame() {
Container pane = getContentPane();
pane.setLayout(new BorderLayout());

textarea = new TextArea(4,20);
textarea.setEditable(false);
JScrollPane scroll = new JScrollPane(textarea);
pane.add(scroll,BorderLayout.CENTER);

JToolBar toolbar = new JToolBar();//建立工具栏
toolbar.add(makeToolButton("anchor.png","anchor"));
toolbar.add(makeToolButton("hammer.png","hammer"));
toolbar.add(makeToolButton("file.png","file"));
toolbar.add(makeToolButton("spinner.png","spinner"));
pane.add(toolbar,BorderLayout.NORTH);

pack();
}
private JButton makeToolButton(String filename,String command) {//创建按钮
ImageIcon imageicon = new ImageIcon(filename);
Image image = imageicon.getImage();
image = image.getScaledInstance(18,18,Image.SCALE_DEFAULT);
imageicon.setImage(image);
JButton button = new JButton(imageicon);
button.setActionCommand(command);
button.addActionListener(this);
return(button);
}
public void actionPerformed(ActionEvent e) {
String selection = e.getActionCommand();
textarea.append("\n" + selection);
textarea.repaint();
}
}

你可能感兴趣的:(java,swing)