Java6学习笔记29——使用Swing创建按钮悬停提示

import javax.swing.JFrame;
import javax.swing.JTextArea;
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.event.ActionListener;
import java.awt.event.ActionEvent;

public class ToolTips extends JFrame implements ActionListener {
JTextArea textarea;
public static void main(String arg[]) {
ToolTips mtb = new ToolTips();
}
public ToolTips() {
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 JTextArea(4,20);
textarea.setEditable(false);
textarea.setToolTipText("Displays action commands");
JScrollPane scroll = new JScrollPane(textarea);
pane.add(scroll,BorderLayout.CENTER);

JToolBar toolbar = new JToolBar();
toolbar.add(makeToolButton("anchor.png","anchor","Drop anchor"));
toolbar.add(makeToolButton("hammer.png","hammer","Pound the hammer"));
toolbar.add(makeToolButton("file.png","file","Save file"));
toolbar.add(makeToolButton("spinner.png","spinner","Rotate"));
pane.add(toolbar,BorderLayout.NORTH);

pack();
}
private JButton makeToolButton(String filename,String command,String tip) {
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);
button.setToolTipText(tip);
return(button);
}
public void actionPerformed(ActionEvent e) {
String selection = e.getActionCommand();
textarea.append("\n" + selection);
textarea.repaint();
}
}

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