我有一个GridBagLayout GUI,在其0 0单元格中添加Board类obj,在其0 0单元格中添加RightPanel obj。我想要做的是让我的GUI类可以访问RightPanel的字符串和按钮。对于初学者,我目前正在尝试更改String wName,但没有成功。请帮助我确定我做错了什么。 注意:我知道这个问题可能听起来很奇怪,但我真的需要知道如何。
在我的GUI中我这样做:
public class TheraGUI extends JFrame {
public RightPanel rpref;
//I add this so I can call right panel
public TheraGUI(RightPanel rpref){
this.rpref = rpref;
}
public TheraGUI(){
Board board = new Board();
Board bref = new Board(this);
RightPanel rp = new RightPanel();
this.rpref.wName = "Gel"
this.setLayout(new GridBagLayout());
this.setTitle("Thera");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.add(board);
this.add(rp);
this.pack();
}
}
在我的RightPanel中,我有这个:
public class RightPanel extends JPanel {
private static final String imageFolderPath = "src/resources/images/";
private Dimension dimension = new Dimension(200, 500);
private static final String defaultImgPiece = "demigod.png";
public JLabel wImgPic;
public String wName;
//And here I instantiate the constructor
public TheraGUI guiref = new TheraGUI(this);
public RightPanel(){
this.setPreferredSize(dimension);
this.setLayout(new GridBagLayout());
GridBagConstraints rpc = new GridBagConstraints();
//White's Panel
JPanel wpanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
rpc.gridx = 0;
rpc.gridy = 0;
this.add(wpanel, rpc);
// Piece Name Info //
wName = "Helios, the Demigod";
JLabel wNamePiece = new JLabel(wName);
wNamePiece.setFont(new Font("Georgia", Font.BOLD, 16));
wNamePiece.setForeground(Color.BLACK);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 20, 0, 20);
wpanel.add(wNamePiece, gbc);
}
}
答案 0 :(得分:0)
你的代码肯定需要有一些结构来消除不受控制的耦合。
除此之外,更改wName没有帮助,您需要调用wNamePiece.setText()。为此,您需要将其作为成员变量。
此外,您需要在Event Dispatcher Thread中进行此调用。如果你不是在一个单独的线程中进行此调用,那么你是安全的。