这是我的第一个问题,所以请耐心等待:) 我正在研究GUI的动态部分,并且由于某种原因它取笑我。 登录后,该课程将在新窗口中打开。 我想要的是,每次点击“添加播放器”按钮时,都会构建一个新的JPanel并添加到“容器”中。它应该把它们放在彼此之下,但它只是在第一次点击时添加一个按钮,之后其余的点击什么都不做。
感谢任何帮助:)
package Gui;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
//import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
@SuppressWarnings("serial")
public class TeamManagerGUI extends JFrame implements ActionListener
{
// private JLabel pNameLabel = new JLabel("Player Name: "),
// pSchoolLabel = new JLabel("School: ");
// private JTextField pNameField = new JTextField(),
// pSchoolField = new JTextField();
private JButton addButton = new JButton("Add Player"),
removeButton = new JButton("Remove player");
private JPanel container = new JPanel(),
playerContainer = new JPanel();
int frameCounter = 1;
public TeamManagerGUI()
{
super("Team Manager User Interface");
setSize(1200,800);
setDefaultCloseOperation(EXIT_ON_CLOSE);
container.setLayout(new GridBagLayout());
playerContainer.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(3,3,3,3);
addButton.addActionListener(this);
container.add(addButton,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.insets = new Insets(3,3,3,3);
container.add(removeButton,gbc);
this.add(container);
}
public void playerFrame()
{
GridBagConstraints gbc = new GridBagConstraints();
playerFrameArr.add(new JPanel());
gbc.gridx = 0;
gbc.gridy = 0;
playerContainer.add(new JButton("LABEL"),gbc);
gbc.gridx = 1;
gbc.gridy = 0;
playerContainer.add(new JButton("BUTTON"),gbc);
gbc.gridx = 0;
gbc.gridy = frameCounter+1;
container.add(playerContainer,gbc);
System.out.println(frameCounter);
frameCounter++;
}
public void addPlayerRow()
{
playerFrame();
container.revalidate();
container.repaint();
}
public void removePlayerRow()
{
//Not yet implemented
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == addButton)
{
addPlayerRow();
}
if(ae.getSource() == removeButton)
{
//Not yet implemented
}
}
}
答案 0 :(得分:1)
您正在反复添加playerContainer
。我认为你应该使用新创建的JPanel
。应该填充这个并将其添加到主容器中。
多次添加单个面板将无法正确渲染,因为这会搞砸布局。我认为您需要保留对新JPanel
的引用,并使用您的布局和按钮填充此内容。
我在想这样的事情:
public void playerFrame()
{
GridBagConstraints gbc = new GridBagConstraints();
JPanel newPanel = new JPanel(new GridBagLayout());
playerFrameArr.add(newPanel);
gbc.gridx = 0;
gbc.gridy = 0;
newPanel.add(new JButton("LABEL"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
newPanel.add(new JButton("BUTTON"), gbc);
gbc.gridx = 0;
gbc.gridy = frameCounter + 1;
container.add(newPanel, gbc);
System.out.println(frameCounter);
frameCounter++;
}