可以添加到容器中的一种简单组件是JButton对象,JButton对象是一个可单击的按钮
创建JButton组件:JButton button = new JButton("Button");
调用add()方法将其加入容器中:add(button);
在容器中添加组件时,不需要指明组件在容器中的位置,组件的布局由布局管理器决定,最简单的布局管理器是FLowLayout类
创建FlowLayout对象:FlowLayout flo = new FlowLayout();
调用setLayout()方法将容器与管理器关联:setLayout(flo);
Demo:
1 package com.swingdemo.demo; 2 3 import java.awt.FlowLayout; 4 5 import javax.swing.JButton; 6 import javax.swing.JFrame; 7 import javax.swing.UIManager; 8 import javax.swing.UnsupportedLookAndFeelException; 9 10 public class Playback extends JFrame { 11 12 private static final long serialVersionUID = 1L; 13 14 public Playback() { 15 16 super("Playback"); 17 setLookAndFeel(); 18 setSize(225, 80); 19 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 20 FlowLayout flo = new FlowLayout(); 21 setLayout(flo); 22 JButton play = new JButton("Play"); 23 JButton stop = new JButton("Stop"); 24 JButton pause = new JButton("Pause"); 25 add(play); 26 add(stop); 27 add(pause); 28 setVisible(true); 29 30 } 31 32 private void setLookAndFeel() { 33 34 try { 35 UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } 39 } 40 41 public static void main(String[] args) { 42 43 Playback pb = new Playback(); 44 45 } 46 47 }
时间: 2024-10-13 02:01:23