【发布时间】:2015-06-01 14:39:06
【问题描述】:
我需要使用 JScrollPane 中的 JLayeredPane 创建一个包含四个八度音阶的虚拟钢琴,以便最初显示一个八度音阶,并且可以水平滚动以查看其他八度音阶。我的代码只显示一个八度音程,不显示滚动条和其他八度音程。以下代码有什么问题?
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);
}
【问题讨论】:
-
不要从
JScrollPane扩展,这不是该组件的工作方式,而是从JPanel之类的东西扩展,然后将其应用于JScrollPane。更多详情请见How to Use Scroll Panes -
JScrollPane将使用组件 preferredSize 来确定它是否需要显示滚动条。默认情况下,JLayeredPane不使用布局管理器,这意味着它无法提供JScrollPane需要的信息 -
另见 this keyboard implementation 使用自定义渲染。
-
@MadProgrammer 我尝试从 JPanel 扩展它并将其应用于 JScrollPane。但是我还是有同样的问题
-
正如我所说,JLayeredPane 没有提供 JScrollPane 所需的信息来确定组件需要多少空间才能知道何时应该显示滚动条
标签: java swing jscrollpane jlayeredpane piano