我正在使用 Swing,试图学习如何使用它。我正在我的书中做一个练习,我应该像 dvd 播放器那样制作按钮 (JButtons)。此时我没有向按钮添加任何功能。该程序在我第一次运行时运行良好。然后我想我会通过使用相同的按钮制作第二个面板 (JPanel) 来扩展它。然而,当我运行我的代码时,我只得到一组按钮(而不是两个区域有两组按钮)。 我是否误解了面板的概念?我将面板理解为我的框架中的一个区域(容器),我可以在其中显示不同的输出,并且我可以在一个框架中有多个面板。
这是我的代码:
import javax.swing.*;
public class Oppgave91 extends JFrame
{
public Oppgave91()
{
super ("We make buttons");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton play = new JButton("Play");
JButton stopeject = new JButton("Stop/Eject");
JButton rewind = new JButton("Rewind");
JButton fastforward = new JButton("FastForward");
JButton pause = new JButton("Pause");
JPanel panel = new JPanel();
panel.add(play);
panel.add(stopeject);
panel.add(rewind);
panel.add(fastforward);
panel.add(pause);
JPanel panel2 = new JPanel();
panel2.add(play);
panel2.add(stopeject);
panel2.add(rewind);
panel2.add(fastforward);
panel2.add(pause);
add(panel);
add(panel2);
setVisible(true);
}
public static void main(String[] args)
{
Oppgave91 showbuttons = new Oppgave91();
showbuttons.pack();
}
}
最佳答案
一个组件只能有一个父组件。查看我的代码片段的最后一行,了解应该如何完成
JPanel panel = new JPanel();
panel.add(play);
panel.add(stopeject);
panel.add(rewind);
panel.add(fastforward);
panel.add(pause);
//right now panel is the parent component of play, stop, eject
JPanel panel2 = new JPanel();
panel2.add(play); //play is now owned by panel2, not panel
panel2.add(stopeject); //stopeject is now owned by panel2, not panel
panel2.add(new JButton("Rewind")); // this is how you should do this
关于java - JPanel的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26099338/