我会写一个自定义PianoLayoutManager
并将黑键放置在比白色按钮更高的 z 顺序上。创建您自己的“约束”类,允许您添加如下组件:
add(new WhiteKey(), new PianoLayoutConstraint(WHITE, 1);
add(new WhiteKey(), new PianoLayoutConstraint(WHITE, 2);
...
add(new WhiteKey(), new PianoLayoutConstraint(WHITE, n);
add(new BlackKey(), new PianoLayoutConstraint(BLACK, 1);
add(new BlackKey(), new PianoLayoutConstraint(BLACK, 2);
...
add(new BlackKey(), new PianoLayoutConstraint(BLACK, m);
From 使用 Swing 组件教程 http://download.oracle.com/javase/tutorial/uiswing/components/jcomponent.html
Note:z 顺序决定了组件绘制的顺序。 z 顺序最高的组件首先绘制,z 顺序最低的组件最后绘制。当组件重叠时,具有较低 z 顺序的组件将绘制在具有较高 z 顺序的组件之上。
这是一个丑陋的黑客,它使用空布局来帮助您入门。
import java.awt.Color;
import javax.swing.*;
class PianoComponent extends JPanel {
PianoComponent() {
setLayout(null);
for (int i = 0; i < 20; i++) {
JButton key = new JButton();
key.setBackground(Color.WHITE);
key.setLocation(i * 20, 0);
key.setSize(20, 120);
add(key);
setComponentZOrder(key, i);
}
for (int i = 0; i < 20; i++) {
int j = i % 7;
if (j == 2 || j == 6)
continue;
JButton key = new JButton();
key.setBackground(Color.BLACK);
key.setLocation(i * 20 + 12, 0);
key.setSize(16, 80);
add(key);
setComponentZOrder(key, 0);
}
}
}
public class Test {
public static void main(String[] args) {
JFrame jf = new JFrame("Piano!");
jf.setSize(400, 200);
jf.add(new PianoComponent());
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}