我正在使用Java swing构建GUI的项目中。目前,我在Jpanel
中有一个JFrame
,其中应包含一个标签(问题)和一组按钮/文本字段(答案),可以根据所提出的问题进行更改。我想将问题集中在顶部的某个地方,将答案适当地放在中间的一个中心。目前,我使用GridBagLayout
设置JLabel
和JButton
,但仍然没有成功。
public class QuestionPanel extends MoviePanel{
private String question;
public QuestionPanel(String type, Application app, String question) throws Exception{
super(type, app);
this.question = question;
JLabel lab = new JLabel(this.question);
this.getGbc().anchor = GridBagConstraints.PAGE_START;
this.getGbc().fill = GridBagConstraints.HORIZONTAL;
this.getGbc().weighty = 0.5;
this.getGbc().gridx = 2;
this.getGbc().gridy = 0;
lab.setFont(new Font("Helvetica", Font.BOLD, 40));
lab.setForeground(new Color(189, 189, 189, 255));
add(lab, this.getGbc());
getAnswers(type);
}
private void getAnswers(String type){
if(type.equals("AgeRestriction")){
this.getGbc().gridx=0;
this.getGbc().gridy=1;
add(new YesButton(this.getApp()),this.getGbc());
this.getGbc().gridx = 3;
this.getGbc().gridy = 1;
add(new NoButton(this.getApp()),this.getGbc());
}
}
}
GridBagLayout
被设置为super MoviePanel
,this.getGbc()
返回适当的GridBagConstraints
。目前,我的布局如下所示:
这个想法是使yes和no按钮彼此靠近,将来的按钮动态地位于中心。
我最终通过组合angushjoshi和c0der的答案来解决,因此在带有GridBagLayout的questionPanel中添加了一个answerPanel。我的代码现在看起来像这样:
public class QuestionPanel extends MoviePanel {
private String question;
private JPanel answerPanel = new JPanel();
public QuestionPanel(String type, Application app, String question) throws Exception {
super(type, app);
this.question = question;
JLabel lab = new JLabel(this.question);
answerPanel.setOpaque(false);
this.getGbc().anchor = GridBagConstraints.PAGE_START;
this.getGbc().weighty = 1;
this.getGbc().gridy = 0;
this.getGbc().gridx = 2;
this.getGbc().gridwidth = 3;
lab.setFont(new Font("Helvetica", Font.BOLD, 40));
lab.setForeground(new Color(189, 189, 189, 255));
add(lab, this.getGbc());
getAnswers(type);
}
public void getAnswers(String type) {
if (type.equals("AgeRestriction")) {
createYesNoButtons();
}
if (type.equals("Age")) {
createAgeField();
}
if (type.equals("Genre")){
createGenreButtons();
}
if (type.equals("Actor")){
createActorField();
}
}
private void createYesNoButtons() {
this.getGbc().weighty = 0.5;
this.getGbc().anchor = GridBagConstraints.CENTER;
answerPanel.add(new YesButton(this.getApp()));
answerPanel.add(new NoButton(this.getApp()));
this.add(answerPanel,this.getGbc());
}
private void createAgeField() {
this.getGbc().weighty = 0.5;
this.getGbc().anchor = GridBagConstraints.CENTER;
answerPanel.add(new AgeField(this.getApp()));
this.add(answerPanel,this.getGbc());
}
private void createGenreButtons(){
}
private void createActorField(){
}
}
现在面板看起来像这样:
感谢您的帮助!
我建议将布局分解为更小,更易于布局的部分。在这种情况下,请使用3个JPanel
,并通过以下MRE进行演示:
很难为您提供解决问题的确切方法,但是我可以告诉您您可能想使用GridBagConstraints.insets
和GridBagConstraints.anchor
。