在Java中,要实现一个带有工具栏的JFrame,你需要遵循以下步骤:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
JFrame frame = new JFrame("带有工具栏的JFrame示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLayout(new BorderLayout());
JToolBar toolBar = new JToolBar();
JButton button1 = new JButton("按钮1");
JButton button2 = new JButton("按钮2");
toolBar.add(button1);
toolBar.add(button2);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "你点击了按钮1");
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "你点击了按钮2");
}
});
frame.add(toolBar, BorderLayout.NORTH);
frame.setVisible(true);
将以上代码整合到一个完整的Java程序中:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ToolBarExample {
public static void main(String[] args) {
JFrame frame = new JFrame("带有工具栏的JFrame示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLayout(new BorderLayout());
JToolBar toolBar = new JToolBar();
JButton button1 = new JButton("按钮1");
JButton button2 = new JButton("按钮2");
toolBar.add(button1);
toolBar.add(button2);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "你点击了按钮1");
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "你点击了按钮2");
}
});
frame.add(toolBar, BorderLayout.NORTH);
frame.setVisible(true);
}
}
运行这个程序,你将看到一个带有两个按钮的工具栏。点击这些按钮将显示一个消息对话框。