I need to create a virtual piano containing four octaves using JLayeredPane inside a JScrollPane such that one octave is shown initially, and can be scrolled horizontally to see the other octaves. My code displays only one octave and does not show the scrollbar and the other octaves. What is the problem with the following code?
class PianoLayout extends JScrollPane
{
public PianoLayout()
{
initComponents();
}
private void initComponents()
{
JLayeredPane layer = new JLayeredPane();
//ScrollableLayeredPane layer = new ScrollableLayeredPane();
layer.setSize(1120,150);
JButton[] keys = new JButton[48];
int keyIndex = 0, i;
for(i=0;i<28;i++)
{
keys[keyIndex] = createWhiteKey(i);
layer.add(keys[keyIndex], 0, -1);
keyIndex+=1;
if(i%7!=2 && i%7!=6)
{
keys[keyIndex] = createBlackKey(i);
layer.add(keys[keyIndex], 1, -1);
keyIndex+=1;
}
}
this.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
this.setViewportView(layer);
setSize(280, 150);
setLocation(110,100);
}
private JButton createWhiteKey(int i)
{
JButton whiteKey = new JButton();
whiteKey.setBackground(Color.WHITE);
whiteKey.setLocation(i*40,0);
whiteKey.setSize(40, 150);
return whiteKey;
}
private JButton createBlackKey(int i)
{
JButton blackKey = new JButton();
blackKey.setBackground(Color.BLACK);
blackKey.setLocation(25 + i*40,0);
blackKey.setSize(30, 90);
return blackKey;
}
}
public class VirtualPiano
{
public static void main(String[] args)
{
JPanel panel = new JPanel(null);
JFrame mainFrame = new JFrame();
PianoLayout pianoLayout = new PianoLayout();
mainFrame.add(panel);
panel.add(pianoLayout);
mainFrame.setSize(500,500);
mainFrame.setVisible(true);
}
Here is an example I found on a forum a long time ago. I know nothing about music so I don't understand how the logic works to create the sounds and keys.
But I did just change the code to implement the
getPreferredSize()
method so that the scrollpane will work properly:This is not a pure solution, because a custom layout manager really should be used to lay out the components and determine a preferred size.