I'm creating a virtual piano type program in Java Swing. My area for the piano keys right now is a JPanel with a horizontal BoxLayout containing white JButtons as white keys. I want to add black keys as well, and have them overlap the white keys.
There are two different approaches I've tried. One is using the OverlayLayout. Unfortunately there isn't much documentation online for the OverlayLayout manager, and it's not available in the NetBeans GUI builder. I don't have a clue how to make it work. The second thing I've tried is using JLayeredPanes. I can't seem to figure that one out either, even after messing with it in Netbeans.
So I think my question is pretty simple. What is the best approach, if there is one, to add JButtons on top of other JButtons? Or maybe there is an alternative to using JButtons for piano keys?
EDIT
I've combined aioobe's and dacwe's code to get the result I wanted. I basically used dacwe's z-ordering with aioobe's basic dimensions (scaled up a bit) and the mod 7 part too. I also added some variables to make things more clear. This is what I have now.
import javax.swing.*;
import java.awt.Color;
public class Test2 {
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
JLayeredPane panel = new JLayeredPane();
frame.add(panel);
int maxKeys = 8;
int width = 60;
int height = 240;
for (int i = 0; i < maxKeys; i++) {
JButton b = new JButton();
b.setBackground(Color.WHITE);
b.setLocation(i * width, 0);
b.setSize(width, height);
panel.add(b, 0, -1);
}
int width2 = 48;
int height2 = 140;
for (int i = 0; i < maxKeys; i++) {
int j = i % 7;
if (j == 2 || j == 6)
continue;
JButton b = new JButton();
b.setBackground(Color.BLACK);
b.setLocation(i*(width) + (width2*3/4), 0);
b.setSize(width2, height2);
panel.add(b, 1, -1);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,280);
frame.setVisible(true);
}
}
Thanks guys! Now I need to attach the listener and text to these buttons somehow.