2015-03-31 148 views
0

我正在尝试制作其他仪器选项卡制造商的键盘。 我设置钢琴的方式是使用分层面板。我遇到的问题是现在每当我尝试添加与钢琴本身不同的其他东西时,它就不会显示出来,或者钢琴不显示出来,它会? 所以我问的是如何在屏幕的右侧添加图像,同时保持一切完好? 谢谢。 P.s我知道黑色按钮很乱,请忽略它。分层面板图形用户界面

enter image description here

class Piano extends JPanel 
{ 

    public static void main(String[] args) 
    { 

     JFrame frame = new JFrame("Test"); 
     JLayeredPane panel = new JLayeredPane(); 
     frame.add(panel); 

     for (int i = 0; i < 13; i++) 
     { 
      JButton b = new JButton(); 
      b.setBackground(Color.WHITE); 
      b.setLocation(i * 20, 0); 
      b.setSize(20, 100); 
      panel.add(b, 0, -1); 
     } 
     JButton b = new JButton(); 
     b.setBackground(Color.BLACK); 
     b.setLocation(16, 0); 
     b.setSize(12, 80); 
     panel.add(b, 1, -1); 
     // 
     JButton b1 = new JButton(); 
     b1.setBackground(Color.BLACK); 
     b1.setLocation(52, 0); 
     b1.setSize(12, 80); 
     panel.add(b1, 1, -1); 
     JButton b2 = new JButton(); 
     b2.setBackground(Color.BLACK); 
     b2.setLocation(76, 0); 
     b2.setSize(12, 80); 
     panel.add(b2, 1, -1); 
     // 
     JButton b3 = new JButton(); 
     b3.setBackground(Color.BLACK); 
     b3.setLocation(112, 0); 
     b3.setSize(12, 80); 
     panel.add(b3, 1, -1); 
     JButton b4 = new JButton(); 
     b4.setBackground(Color.BLACK); 
     b4.setLocation(134, 0); 
     b4.setSize(12, 80); 
     panel.add(b4, 1, -1); 
     JButton b5 = new JButton(); 
     b5.setBackground(Color.BLACK); 
     b5.setLocation(157, 0); 
     b5.setSize(12, 80); 
     panel.add(b5, 1, -1); 
     // 
     JButton b6 = new JButton(); 
     b6.setBackground(Color.BLACK); 
     b6.setLocation(192, 0); 
     b6.setSize(12, 80); 
     panel.add(b6, 1, -1); 
     JButton b7 = new JButton(); 
     b7.setBackground(Color.BLACK); 
     b7.setLocation(216, 0); 
     b7.setSize(12, 80); 
     panel.add(b7, 1, -1); 
     // 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(600, 400); 
     frame.setVisible(true); 
    } 
} 
+0

为什么不在JFrame中放入带有BorderLayout的JPanel。然后将中间的LayeredPane和右侧的图像添加到另一个Jpanel中。 – keuleJ 2015-03-31 15:16:38

回答

0

你基本上要使用LayoutJPanel例如一个GridLayout

例如不便。这样

JPanel mainPanel = new JPanel(); 
mainPanel.setLayout(new GridLayout(0,2)); 

Here is a example in the oracle doc

0

默认情况下,一个JFrame使用BorderLayout

frame.add(panel); 

当你不指定约束,那么“中心”使用,所以要添加的分层窗格到画面中央。

如果你想另一个面板添加到框架右侧,那么你做这样的事情:

JPanel right = new JPanel(); 
right.add(...); 
frame.add(right, BorderLayout.EAST); 

阅读从Layout Managers Swing的教程部分获取更多信息。

您可能还想查看Midi Piano以获得完整的带有声音的钢琴键盘的实现,只是为了好玩。