JPanel占用了整个JFrame [英] JPanel taking up the whole JFrame

查看:130
本文介绍了JPanel占用了整个JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,当我将JPanel包含在我的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);

    }
}

但是,当我改变

Panel.setLocation(null)

Panel.setLocation(80, 250)

它覆盖了整个屏幕.

有人可以帮我把它放在屏幕上的正确位置吗?

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

更新

我按照我在评论中所说的进行了修改,代码如下:

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);

}
}

它将输入txt放置在屏幕底部,但屏幕其余部分保持灰色.

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

但是我根本不理解您发布的第二组代码;这远远超出了我的技能范围(最近6星期我才一直在学习Java).我在此阶段所要寻找的就是使面板不会在屏幕的其余部分变黑.

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?

推荐答案

默认情况下,JFrame的contentPane使用BorderLayout,您可以利用它来发挥自己的优势:

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

  • 将TestFrameExample对象BorderLayout.CENTER添加到JFrame
  • BorderLayout.PAGE_END位置的JFrame中添加其他JPanel,或者只是一个JTextField.这会将组件添加到GUI的底部.
  • 请勿在组件上调用setLocation(...),因为这会导致使用null布局,这种布局会导致难以调试和升级的刚性GUI.
  • 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.

有关更多详细信息,请在教程中阅读BorderLayout.

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

例如

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 ***

}


请注意,我会尽可能避免直接绘画,而应使用组件和布局管理器.这应该使显示不同类型的问题变得更加容易.例如,运行以下程序,然后反复按<enter>键,滚动问题以查看我的意思:


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;
   }
}

这篇关于JPanel占用了整个JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆