【发布时间】:2019-02-26 01:23:40
【问题描述】:
我正在尝试通过在另一个类中调用的方法将新的 JLabel 添加到 JPanel。
第 1 类:
public class AppFrame extends JFrame {
// CardGame
//Making private objects to access?\
private MainPanel mainPanel = new MainPanel();
public AppFrame() {
super("BlackJack Cardgame");
setBounds(100, 100, 640, 640);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(new StatusBar(), BorderLayout.SOUTH);
add(new MainPanel(), BorderLayout.CENTER);
add(new StatusBar(), BorderLayout.NORTH);
setVisible(true);
//Does not correctly add label
mainPanel.testMethod();
}
public MainPanel getMainPanel() {
return mainPanel;
}
第 2 类:
public class MainPanel extends JPanel {
Border blackBorder = BorderFactory.createLineBorder(Color.BLACK);
GridBagConstraints gbc = new GridBagConstraints();
public void testMethod() {
System.out.println("test method");
this.add(new JLabel("test"));
}
public MainPanel() {
setLayout(new GridBagLayout());
ImageIcon icon = new ImageIcon(getClass().getResource("/images/ACE_CLUBS.jpg"));
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel(icon),gbc);
ImageIcon icon2 = new ImageIcon(getClass().getResource("/images/TWO_CLUBS.jpg"));
gbc.gridx = 1;
gbc.gridy = 0;
add(new JLabel(icon2),gbc);
gbc.gridx=0;
gbc.gridy=1;
//correctly adds label.
testMethod();
}
如果从第 2 类(我想从中添加内容的框架)调用该方法,它将按预期工作。但是,如果我尝试从类 1 调用该方法,它将不会添加标签。 我确信该方法在 sysout 发生时被调用。我对添加东西的理解不正确吗?
【问题讨论】: