I am creating a piano-like virtual program in Java Swing. My area for piano keys right now is a JPanel with a horizontal BoxLayout containing white JButtons in the form of white keys. I also want to add black keys and overlay them on white keys.
There are two different approaches I've tried. One uses OverlayLayout. Unfortunately, there is not much documentation for the OverlayLayout manager, and it is not available in the NetBeans GUI builder. I do not know how to make it work. Secondly, I tried to use JLayeredPanes. I can't seem to understand that he is either, even after he was messing with him at Netbeans.
So, I think my question is pretty simple. What is the best approach, if any, to add JButtons on top of other JButtons? Or maybe there is an alternative to using JButtons for piano keys?
EDIT
I combined the aioobe and dacwe code to get the result I wanted. I mainly used dacwe z-ordering with the main aioobe sizes (slightly increased) and part of mod 7. I also added some variables to make things clearer. 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 somehow attach the listener and text to these buttons.
source
share