How to Use swing to create a BeatBox and swing to create a beatbox

Source: Internet
Author: User

How to Use swing to create a BeatBox and swing to create a beatbox
First, we need to review some content (14:32:14): 1. Swing component

Swing components (component, or component) are more accurate terms than Widgets. They are things placed on the GUI (Graphical User Interface, these components are visible to some users and interact with them, such as Text Field, Button, scrollable, list, and radio button. These components are inherited from java. swing. JComponent;

In Swing, almost all components are placed in other components.

2. Create a GUI in four steps:

  • Create window (JFrame)

1 JFrame frame = new JFrame ();

  • Create component

1 JButton button = new JButton ("click me ");

  • Add component to frame

1 frame. getContentPane. add (BorderLayout. EAST, button );

  • Displayed

1 frame. setSize (300,300 );

2 frame. setVisible (true );

3. layout Managers)

First, the layout manager is a java object associated with a specific component, most of which are background components.

Second, the layout manager is used to control other components carried on the associated components. In other words, if a framework has a panel and a button on the panel, the panel layout manager controls the size and position of the buttons, while the layout manager controls the Panel size and position.

You can add the corresponding buttons to the corresponding panel as follows:

1 JPanel jpanel = new JPanel ();

2 JButton button = new JButton ("click me ");

3 jpanel. add (button );

4. Three major head managers:
  • Border
  • Flow
  • Box

1) BorderLayout: The manager divides the component into five regions, and each region can only be placed with one component. The default size of the component placed by the Administrator is not obtained. This is also the default layout manager of the framework;

2) FlowLayout: the manager's behavior is similar to the layout configuration method of the file handler. This component will be displayed according to the ideal size, and Hu will be arranged in the order from left to right (line breaks may be arranged in the middle). Therefore, if the component cannot fit a row, it will automatically wrap the line. This is the default layout manager for the panel.

3) BoxLayout: Like FlowLayout, each component is arranged in the order of addition according to the default size. It is arranged vertically (or horizontally, but usually we only care about the vertical method ). Unlike FlowLayout, it requires inserting a line feed mechanism to force components to be arranged from a new column.

Next let's take a look at the dry goods:

3 import java. awt. borderLayout; 4 import java. awt. gridLayout; 5 import java. awt. label; 6 import java. awt. event. actionEvent; 7 import java. awt. event. actionListener; 8 import java. util. arrayList; 9 10 import javax. sound. midi. *; 11 import javax. swing. *; 12 13 public class BeatBox {14 JPanel mainJPanel; 15 ArrayList <JCheckBox> checkboxslist; 16 Sequencer sequencer; 17 Sequence sequence; 18 Track track; 19 JFrame theFrame; 20 String [] instrumentNames = {21 "Bass Drum", "closed Hi-Hat", "open Hi-Hat", "Acoustic Snare ", 22 "Crash Cymbal", "Hand Clap", "High Tome", "Hi Bongo", "Maracas", 23 "Whistal", "Low Conga", "Cowbell ", "Vibraslap", "Low_mid Tom", 24 "High ago go", "open High Coga" 25}; // name of the instrument, use a String array to maintain 26 int [] instruments = {35, 42, 38, 50, 60, 47,}; // The keyword of the actual instrument, for example, 35 is a Bass Drum, 4 2 is closed Hi-Hat 27 public static void main (String [] args) {28 // TODO Auto-generated method stub 29 new BeatBox (). buildGUI (); 30} 31 public void buildGUI () {32 theFrame = new JFrame ("Cyber BeatBox"); 33 theFrame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE); // closes the program 34 when the window is closed. BorderLayout = new BorderLayout (); // defines a BorderLayout panel object 35 JPanel background = new JPanel (layout ); // instantiate the Panel object as a JPanel object 36 background. setBorder (BorderFactory. createEmptyBorder (10, 10, 10, 10); // used to set the edge space size 37 38 checkboxslist = new ArrayList <JCheckBox> (); 39 Box buttonBox = new Box (BoxLayout. y_AXIS); 40 41 JButton start = new JButton ("start"); 42 start. addActionListener (new MyStartlistener (); 43 buttonBox. add (start); 44 45 JButton stop = new JButton ("stop"); 46 start. addActionListener (new MyStoplistener (); 47 butto NBox. add (stop); 48 49 JButton upTempo = new JButton ("Tempo up"); 50 start. addActionListener (new MyupTempolistener (); 51 buttonBox. add (upTempo); 52 53 JButton downTempo = new JButton ("Tempo down"); 54 start. addActionListener (new MydownTempolistener (); 55 buttonBox. add (downTempo); 56 57 Box nameBox = new Box (BoxLayout. y_AXIS); 58 for (int I = 0; I <16; I ++) {59 nameBox. add (new Label (instrumentNames [I]); 60} 61 62 background. add (BorderLayout. EAST, buttonBox); 63 background. add (BorderLayout. WEST, nameBox); 64 65 theFrame. getContentPane (). add (background); 66 67 GridLayout gridLayout = new GridLayout (16, 16); // create a grid layout with the specified number of rows and columns. All components in the layout have equal sizes. 68 // One (but not both) in the row and column can be zero, which means that any number of objects can be placed in one row or column. 69 gridLayout. setVgap (1); // set the Vertical spacing between components to the specified value. 70 gridLayout. setHgap (2); // set the horizontal spacing between components to the specified value. 71 mainJPanel = new JPanel (gridLayout); 72 background. add (BorderLayout. CENTER, mainJPanel); 73 74 for (int I = 0; I <256; I ++) {75 JCheckBox checkBox = new JCheckBox (); 76 checkBox. setSelected (false); 77 checkbow.ist. add (checkBox); 78 mainJPanel. add (checkBox); 79} // end loop 80 // create a checkBox group and set it to false if not checked, add it to the arraylist and the Panel 81 82 setUpMidi (); 83 84 theFrame. setBounds (50, 50,300,300); 85 theFrame. pack (); // pa Ck () function: Make the window size suitable for the preferred size and layout of its child components. If any dimension is smaller than the minimum size specified by the last call of the setMinimumSize method, the final width and height of the window are automatically enlarged. 86 // if the window and/or its owner cannot be displayed, make both display before calculating the preferred size. The window takes effect after calculating its size. 87 theFrame. setVisible (true); 88} // close buildGUI () method 89 90 public void setUpMidi () {91 try {92 93 sequencer = MidiSystem. getSequencer (); // This method is equivalent to calling getSequencer (true) to create sequencer 94 sequencer. open (); 95 // create and open the queue 96 97 sequence = new Sequence (Sequence. PPQ, 4); 98 track = sequence. createTrack (); 99 // create a queue and track100 101 sequencer. setTempoInBPM (120); 102 103} catch (Exception e) {104 e. printStackTrace (); 105} 106} // Disable setUpMidi () method 107 108 public void buildTrackAndStart () {109 110 int [] trackList = null; // create an array of 16 elements to store a musical instrument value, if this play is performed, the value will be a keyword value; otherwise, the value will be 0 111 sequence. deleteTrack (track); 113 track = sequence. createTrack (); // clear the old track and create a new 114 115 for (int I = 0; I <16; I ++) {// each instrument executes 116 trackList = new int [16]; 117 118 int key = instrument [I]; // set the keyword 119 120 for (int j = 0; j <16; j ++) {// execute 121 JCheckBox jc = (JChe CkBox) checkbow.ist. get (j + 16 * I); 122 if (jc. isSelected () {// If this option is selected, place the value of the keyword in the array. Otherwise, add 123 trackList [j] = key; 124} else {125 trackList [j] = 0; 126} 127} // close loop 128 129 makeTracks (trackList); 130 track. add (makeEvent (176,1, 127,0, 16); // create this event and add it to the track; 131} // close the External Loop 132 133 134 track. add (makeEvent (135, 136, 137, 15); try {sequencer. setSequence (sequence); 138 sequencer. setLoopCount (sequencer. LOOP_CONTI NUOUSLY); 139 sequencer. start (); 140 sequencer. setTempoInBPM (120); // set the speed by the number of beats per minute. The actual playback speed is the product of the specified value and the speed factor. 141} catch (Exception e) {142 e. printStackTrace (); 143} 144} // end buildTrackAndStart method 145 146 public class MyStartlistener implements ActionListener {147 // The Listener of the button 148 @ Override149 public void actionreceivmed (ActionEvent e) {150 // TODO Auto-generated method stub151 buildTrackAndStart (); 152} 153 154} // internal class close 155 public class MyStoplistener implements ActionListener {156 // The Listener of the button 157 @ Override158 public void Actionreceivmed (ActionEvent e) {159 // TODO Auto-generated method stub160 sequencer. stop (); 161} 162 163} // internal class close 164 public class MyupTempolistener implements ActionListener {165 // The Listener of the button 166 @ Override167 public void actionreceivmed (ActionEvent e) {168 // TODO Auto-generated method stub169 float tempoFactor = sequencer. getTempoFactor (); 170 sequencer. setTempoFactor (float) (tempoFactor * 1.03); // rhythm factor, preset to 1. 0, adjust 3% 171} 172 173} // The internal class closes 174 public class MydownTempolistener implements ActionListener {175 // The Listener of the button 176 @ Override177 public void actionreceivmed (ActionEvent e) {178 // TODO Auto-generated method stub179 float tempoFactor = sequencer. getTempoFactor (); 180 sequencer. setTempoFactor (float) (tempoFactor *. 97); // rhythm factor. The preset value is 1.0. Each adjustment is 3% 181} 182 183}. // The internal class closes 184 public void makeTracks (int [] list) {185 186 (Int I = 0; I <16; I ++) {187 int key = list [I]; 188 if (key! = 0) {189 track. add (makeEvent (100, key, 190, I); track. add (makeEvent (100, 9, key, I + 1); // create Note on and Note off, and add to track 191} 192} 193} // close makeTracks method 194 public MidiEvent makeEvent (int comd, int chan, int one, int two, int tick) {195 MidiEvent event = null; 196 try {197 receive message = new receive message (); // create a message instance 198 receive message. setMessage (comd, chan, one, two); // call setMessage199 event = new MidiEvent (publish message, tick); // create a message's MidiEvent instance 200} catch (Exception e) {201 e. printStackTrace (); 202} 203 return event; 204} // disable the makeEvent method, which is used to create messages and events 205}

 

The corresponding interface is displayed as follows:

Q: Why can't I add components directly like a panel?

A: JFrame is so special because it allows no contacts to be displayed on the screen.

Because Swing components are purely composed of Java, JFrame must be connected to the underlying operating system to facilitate the storage of display devices. We can either place the panel on the java layer of 100% on the JFrame, or use the JFrame as the frame supporting the panel, he can even change the frame panel in a custom way:

1  nyframe.setContentpane(myPanel);

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.