-1

I'm having this really frustrating problem with my code. In my main class I call a method in another class which should show me a question and 4 possible answers. These different questions don't have the same length as each other. The problem is that if the question gets longer than the previous one, the buttons drift away from each other without me changing anything in the code. So I started searching for some solutions and found something. I've put the question on a different panel than the buttons.

Panel 1:

public JPanel getPanel(){
    code
}

Panel 2:

public JPanel getPanel1(){
   code
}

Then in my main I wrote the following:

private void initializeAnswer(String jsonFileName, int questionNumber) {

   JPanel panel = new Answer(json.getCorrectAnswer(questionNumber, 
   jsonFileName)).getPanel();
   JPanel panel1 = new Answer(json.getCorrectAnswer(questionNumber, 
   jsonFileName)).getPanel1();
   frame.setContentPane(panel);
   frame.setContentPane(panel1);

}

Well I thought that this would display both of the panels on to the frame at the same time, but I was wrong. I even changed the background color of the panel1 to Transparent with the following code but it didn't work:

panel1.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.5f));
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • A frame can't have two content panes. Are you looking for something like [layered panes](https://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html) perhaps? – khelwood Mar 29 '19 at 10:25
  • @khelwoodto be honest.. I don't know. I just read that and had to try it out! –  Mar 29 '19 at 10:26
  • @khelwood https://stackoverflow.com/questions/9297630/two-different-panels-in-one-frame-java –  Mar 29 '19 at 10:27
  • I said a frame can't have two **content panes**, not that you can't add two panels in a frame. – khelwood Mar 29 '19 at 10:37
  • I guess you want `frame.setLayout(new GridLayout(0, 1)); frame.add(panel); frame.add(panel1);` but it is only a guess. Post [mcve] – c0der Mar 29 '19 at 11:39

1 Answers1

1

You could use a Root-JPanel.

JPanel root = new JPanel();
root.add(panel1);
root.add(panel2);
frame.setContentPane(root);

Additional use a Layout...

oracle Tutorial

Wulf
  • 712
  • 5
  • 25