因此,我制作了一个程序,其中有一个GUI,用户可以在那里输入烟花发射的参数,在屏幕中央有一个面板,当按下按钮时,启动应该被绘制出来。然而,在我的程序中,JPanel没有更新,也没有绘制任何内容。代码如下
//This is the method that build the JPanel in the center for the launch
public JPanel buildCenter() {
JPanel center=new JPanel();
center.setBackground(Color.black);
center.setVisible(true);
return center;
}
//This is the method the build the GUI, the buttons and such are in the other panels labeled top, west, east, etc.
public void buildGUI(){
configureSliders();
configureRadioButtons();
JFrame frame=new JFrame();
JPanel panel=new JPanel();
JPanel top=new JPanel();
panel.setLayout(new BorderLayout());
Fireworks.setFont(new Font("Helvetica", Font.BOLD, 30));
frame.setLayout(new BorderLayout());
top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS));
top.add(Box.createHorizontalGlue());
top.add(Fireworks);
top.add(Box.createHorizontalGlue());
frame.add(top, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(1920,1080);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
panel.add(buildCenterTop(),BorderLayout.NORTH);
panel.add(buildCenter(), BorderLayout.CENTER);
panel.add(buildwest(), BorderLayout.WEST);
panel.add(buildeast(),BorderLayout.EAST);
panel.add(Launch, BorderLayout.SOUTH);
Launch.addActionListener(this);
}
//this is the action performed method where repaint won't work. fire is my fireworks object with the paintcomponent method for the launch.
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(Launch)) {
setColor();
setTime();
setExplosion();
fire.setVelocity(veloslider.getValue());
fire.setTheta(thetaslider.getValue());
buildCenter().add(fire);
buildCenter().repaint();
buildCenter().validate();
}发布于 2018-11-14 20:08:08
buildCenter()方法所做的就是创建一个带有黑色背景的空面板。
然后将这个空面板添加到框架中:
panel.add(buildCenter(), BorderLayout.CENTER);那么在您的ActionListener中,您需要:
buildCenter().add(fire);
buildCenter().repaint();
buildCenter().validate();所做的就是再创建3个空面板。你不想再创建3个面板。要将组件添加到现有面板中。
您需要做的是创建“中心”面板的单个实例,然后保留一个引用该面板的变量,以便将来可以更新面板。
因此,需要在类中定义一个实例变量:
private JPanel centerPanel;然后在buildGui()方法中创建面板:
//panel.add(buildCenter(), BorderLayout.CENTER);
centerPanel = buildCenter();
panel.add(buildCenter, BorderLayout.CENTER);然后,在您的ActionListener中,您可以向中心面板添加组件:
//buildCenter().add(fire);
//buildCenter().repaint();
//buildCenter().validate();
centerPanel.add( fire );
centerPanel.revalidate();
centerPanel.repaint();https://stackoverflow.com/questions/53306855
复制相似问题