简体   繁体   中英

JPanel taking up the whole JFrame

I have an issue where when I include the JPanel in my JFrame, it covers the entire screen. My code reads

import java.awt.*;

import javax.swing.*;

public class TestFrameExample extends JPanel {

    static String TheQuestion;
    static String QN1 = "Question 1: ";

    static String Q1 = "What is Lead's chemical symbol?";

    static String brk = "___________________";

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(new Color(135, 206, 250));

        g.setFont(new Font("Tahoma", Font.BOLD, 48));
        g.setColor(Color.WHITE);
        g.drawString(QN1, 80, 100);

        g.setFont(new Font("Tahoma", Font.BOLD, 48));
        g.setColor(Color.WHITE);
        g.drawString(brk, 60, 130);

        g.setFont(new Font("Tahoma", Font.PLAIN, 36));
        g.setColor(Color.WHITE);
        g.drawString(Q1, 80, 200);
    }



    public static void main(String[] args) {

        TestFrameExample graphics = new TestFrameExample();
        JFrame ThisFrame = new JFrame();

        TheQuestion = QN1;

        JTextField txt = new JTextField(10);
        JPanel Panel = new JPanel();

        ThisFrame.setTitle("Question 1");
        ThisFrame.setSize(720, 480);
        ThisFrame.setLocationRelativeTo(null);
        ThisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ThisFrame.setVisible(true);
        ThisFrame.add(graphics);

        Panel.setBackground(new Color(135, 206, 250));
        Panel.setSize(null);
        Panel.setLocation(null);
        Panel.add(txt);
        ThisFrame.add(Panel);

    }
}

However, when I change

Panel.setLocation(null)

to

Panel.setLocation(80, 250)

It covers the entire screen.

Could someone please help me put it in the right spot on the screen?

UPDATE

I made the modifications as I said in my comment, with the code reading

import java.awt.*;
import javax.swing.*;

public class TestFrameExample extends JPanel {

static String TheQuestion;
static String QN1 = "Question 1: ";

static String Q1 = "What is Lead's chemical symbol?";

static String brk = "___________________";

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    this.setBackground(new Color(135, 206, 250));

    g.setFont(new Font("Tahoma", Font.BOLD, 48));
    g.setColor(Color.WHITE);
    g.drawString(QN1, 80, 100);

    g.setFont(new Font("Tahoma", Font.BOLD, 48));
    g.setColor(Color.WHITE);
    g.drawString(brk, 60, 130);

    g.setFont(new Font("Tahoma", Font.PLAIN, 36));
    g.setColor(Color.WHITE);
    g.drawString(Q1, 80, 200);
}



public static void main(String[] args) {

    TestFrameExample graphics = new TestFrameExample();
    JFrame ThisFrame = new JFrame();

    TheQuestion = QN1;

    JTextField txt = new JTextField(20);
    JPanel panel = new JPanel();

    ThisFrame.setTitle("Question 1");
    ThisFrame.setSize(720, 480);
    ThisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ThisFrame.add(graphics);

    panel.setBackground(new Color(135, 206, 250));
    panel.add(txt);
    ThisFrame.add(panel);
    ThisFrame.add(panel, BorderLayout.PAGE_END);

    ThisFrame.setLocationRelativeTo(null);
    ThisFrame.setVisible(true);

}
}

It places the input txt at the bottom of the screen, but the rest of the screen remains grey.

But I simply don't understand the second set of code that you posted; it's far beyond my skill set (I've only been learning Java for the last 6 weeks). All I'm looking for at this stage is make the panel not blank out the rest of the screen.

Is this possible just by modifying the current set of code, or would I have to completely rewrite the code?

A JFrame's contentPane uses BorderLayout by default, and you can use that to your advantage:

  • Add your TestFrameExample object BorderLayout.CENTER to your JFrame
  • Add your other JPanel, or perhaps just a JTextField to the JFrame in the BorderLayout.PAGE_END position. This will add the component to the bottom of the GUI.
  • Don't call setLocation(...) on your components as that's inviting use of null layouts, a layout that leads to rigid GUI's that are hard to debug and upgrade.

For more details, read up on the BorderLayout in the tutorials.

eg,

public static void main(String[] args) {
    TestFrameExample graphics = new TestFrameExample();
    JFrame thisFrame = new JFrame();

    TheQuestion = QN1;

    JTextField txt = new JTextField(10);
    JPanel panel = new JPanel();

    thisFrame.setTitle("Question 1");
    thisFrame.setSize(720, 480); // better to not do this, but to pack instead
    // thisFrame.setLocationRelativeTo(null);
    thisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // thisFrame.setVisible(true); // *** not yet ***
    thisFrame.add(graphics, BorderLayout.CENTER);

    panel.setBackground(new Color(135, 206, 250));
    // panel.setSize(null); // *** don't do this ***
    // panel.setLocation(null); // *** don't do this ***
    panel.add(txt);
    thisFrame.add(panel, BorderLayout.PAGE_END);

    thisFrame.setLocationRelativeTo(null);
    thisFrame.setVisible(true); // *** HERE ***

}

Note that myself, I'd avoid direct painting if possible and instead would use components and layout managers. This should make it easier to display different kinds of questions. For example, run the following program and by pressing the <enter> key repeatedly, scroll the questions to see just what I mean:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

public class TestQuestion2 extends JPanel {
   private static final Color BACKGROUND = new Color(135, 206, 250);
   private static final Color LABEL_FOREGROUND = Color.white;
   private static final int EB_GAP = 60;
   private static final int PREF_W = 720;
   private static final int PREF_H = 480;
   private static final Font TITLE_FONT = new Font("Tahoma", Font.BOLD, 48);
   private static final Font Q_FONT = TITLE_FONT.deriveFont(Font.PLAIN, 36f);
   private JLabel questionTitleLabel = new JLabel();
   private JTextArea questionArea = new JTextArea(4, 10);
   private JTextField answerField = new JTextField(20);
   private Question question;
   private List<Question> questionList;
   private int questionListIndex = 0;

   public TestQuestion2(List<Question> questionList) {
      this.questionList = questionList;
      questionTitleLabel.setFont(TITLE_FONT);
      questionTitleLabel.setForeground(LABEL_FOREGROUND);
      JSeparator separator = new JSeparator();
      separator.setForeground(LABEL_FOREGROUND);

      questionArea.setFont(Q_FONT);
      questionArea.setForeground(LABEL_FOREGROUND);
      questionArea.setWrapStyleWord(true);
      questionArea.setLineWrap(true);
      questionArea.setBorder(null);
      questionArea.setOpaque(false);
      questionArea.setFocusable(false);
      JScrollPane scrollPane = new JScrollPane(questionArea);
      scrollPane.setBorder(null);
      scrollPane.setOpaque(false);
      scrollPane.getViewport().setOpaque(false);

      JPanel answerPanel = new JPanel();
      answerPanel.add(answerField);
      answerPanel.setOpaque(false);

      setBackground(BACKGROUND);
      setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
      setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
      add(questionTitleLabel);
      add(Box.createHorizontalStrut(10));
      add(separator);
      add(Box.createHorizontalStrut(5));
      add(scrollPane);
      add(Box.createHorizontalGlue());
      add(answerPanel);

      setQuestion(questionList.get(questionListIndex));

      answerField.addActionListener(new AnswerListener());
   }

   public void setQuestion(Question question) {
      this.question = question;
      questionTitleLabel.setText("Question " + question.getNumber() + ":");
      questionArea.setText(question.getQuestion());
   }

   @Override
   public Dimension getPreferredSize() {
      Dimension superSz = super.getPreferredSize();
      if (isPreferredSizeSet()) {
         return superSz;
      }
      int prefW = Math.max(superSz.width, PREF_W);
      int prefH = Math.max(superSz.height, PREF_H);
      return new Dimension(prefW, prefH);
   }

   private class AnswerListener implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent e) {
         questionListIndex++;
         questionListIndex %= questionList.size();
         setQuestion(questionList.get(questionListIndex));
      }
   }

   private static void createAndShowGui() {
      List<Question> questionList = new ArrayList<>();
      questionList.add(new Question(1, "What is Lead's chemical symbol?"));
      questionList.add(new Question(2, "Who is buried in Grant's tomb?"));
      questionList.add(new Question(3, "What ..... is your quest?"));
      questionList.add(new Question(4, "What ..... is your favorite color?"));
      questionList.add(new Question(5, "What is the capital of Assyria?"));
      questionList.add(new Question(6, "What is the airspeed velocity of the unladen laden swallow?"));
      questionList.add(new Question(7, "This will be a very long question, one that shows the display "
            + "of multiple lines, and a JTextArea that looks like a JLabel. "
            + "What do you think of it?"));

      TestQuestion2 testQuestion2Panel = new TestQuestion2(questionList);

      JFrame frame = new JFrame("Question");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(testQuestion2Panel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class Question {
   private int number;
   private String question;
   private List<String> possibleAnswers;

   public Question(int number, String question) {
      this.number = number;
      this.question = question;
   }
   public int getNumber() {
      return number;
   }
   public void setNumber(int number) {
      this.number = number;
   }
   public String getQuestion() {
      return question;
   }
   public void setQuestion(String question) {
      this.question = question;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM