注意:我正在使用 jFugue。
public class Piano extends JFrame implements KeyListener {
ArrayList<Keys> keys = new ArrayList<Keys>();
Player playNote = new Player();
public Piano() {
drawGrid();
this.addKeyListener(this);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
public void drawGrid() {
pane = new JLayeredPane();
this.setLayout(null);
keys.add(new Key(new Rectangle(0, 0, 50, 300), new Pattern("V0 I[Piano] C5q"), Color.white));
keys.add(new Key(new Rectangle(25, 0, 25, 180), new Pattern("V0 I[Piano] C#5q"), Color.white));
keys.add(new Key(new Rectangle(50, 0, 50, 300), new Pattern("V0 I[Piano] D5q"), Color.white));
keys.add(new Key(new Rectangle(75, 0, 25, 180), new Pattern("V0 I[Piano] D#5q"), Color.white));
keys.add(new Key(new Rectangle(100, 0, 50, 300), new Pattern("V0 I[Piano] E5q"), Color.white));
keys.add(new Key(new Rectangle(150, 0, 50, 300), new Pattern("V0 I[Piano] F5q"), Color.white));
keys.add(new Key(new Rectangle(175, 0, 25, 180), new Pattern("V0 I[Piano] F#5q"), Color.white));
keys.add(new Key(new Rectangle(200, 0, 50, 300), new Pattern("V0 I[Piano] G5q"), Color.white));
keys.add(new Key(new Rectangle(225, 0, 25, 180), new Pattern("V0 I[Piano] G#5q"), Color.white));
keys.add(new Key(new Rectangle(250, 0, 50, 300), new Pattern("V0 I[Piano] A5q"), Color.white));
keys.add(new Key(new Rectangle(275, 0, 25, 180), new Pattern("V0 I[Piano] A#5q"), Color.white));
keys.add(new Key(new Rectangle(300, 0, 50, 300), new Pattern("V0 I[Piano] B5q"), Color.white));
this.add(keys.get(0));
for (Key w: keys) {
w.setBounds(w.getRectangle());
this.getContentPane().add(w);
w.addMouseListener(w);
w.setPlayer(playNote);
}
}
public static void main(String[] args) {
Piano yamaha = new Piano();
yamaha.setSize(1000, 500);
}
}
这是关键类的一部分:
public class Key extends JLayeredPane implements MouseListener {
Player player;
Rectangle rectangle;
Pattern pattern;
Color color;
public Key(Rectangle r, Pattern p, Color c) {
rectangle = r;
pattern = p;
color = c;
}
public void paintComponent(Graphics g) {
g.setColor(color);
g.fillRect((int) rectangle.getX() - 1, (int) rectangle.getY() - 1, (int) rectangle.getWidth() - 1, (int) rectangle.getHeight() - 1);
g.setColor(Color.BLACK);
g.drawRect((int) rectangle.getX(), (int) rectangle.getY(), (int) rectangle.getWidth() - 1, (int) rectangle.getHeight() - 1);
repaint();
}
public Rectangle getRectangle() {
return rectangle;
}
public void setRectangle(Rectangle rectangle) {
this.rectangle = rectangle;
}
}
第一个白键将出现在框架中,但其他白键都没有。我尝试过 JLayeredPane、OverlayLayout、GridLayout 等等。
谁能给我一些帮助?