对于某些人来说,这可能是一个非常明显的问题,但我无法弄清楚。我是Eclipse的新手,仅使用Dr.Java进行编程。
我正在创建一个疯狂的libs程序,用户必须在其中输入名词,形容词,名称,数字,最后将其显示在故事中。

用户输入所有必需的信息后,我希望完成的故事在jPanel中打开。我无法弄清楚如何将文本添加到jPanel。(我希望在用户输入所有信息后,将以c。代码开头的文本显示在窗口中)
这是代码:

import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MadLibs{

 public static void Action1 ()
  {

    JFrame frame = new JFrame("Mad Libs");
    // Add a window listener for close button
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
        }
    });

    Scanner input = new Scanner(System.in);

    System.out.println("Male Friend:");
    String maleFriend = input.nextLine();
    System.out.println("Adjective:");
    String adjective1 = input.nextLine();
    System.out.println("Past Tense Verb:");
    String pastTenseVerb1 = input.nextLine();
    System.out.println("Past Tense Verb 2:");
    String pastTenseVerb2 = input.nextLine();
    System.out.println("Large Number:");
    String largeNumber = input.nextLine();
    System.out.println("Famous Female:");
    String famousFemale = input.nextLine();
    System.out.println("Adverb:");
    String adverb = input.nextLine();
    System.out.println("Place:");
    String place = input.nextLine();
    System.out.println("Body Part(singular):");
    String bodyPart = input.nextLine();
    System.out.println("Large Number:");
    String largeNumber2 = input.nextLine();
    System.out.println("Verb ending with -ing");
    String ingEnding1 = input.nextLine();
    System.out.println("Singular noun:");
    String singularNoun = input.nextLine();
    System.out.println("Plural Noun:");
    String pluralNoun = input.nextLine();



    // This is an empty content area in the frame
    JLabel jlbempty = new JLabel("");
    jlbempty.setPreferredSize(new Dimension(600, 800));
    frame.getContentPane().add(jlbempty, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);

    //The story I want displayed on the jPanel:
    /*
     c.println("The Great Dough Disaster");
        c.println("\nLast summer, my friend "+ maleFriend + " got a job at the " + adjective1 +" Pastry Shop. For the first few");
        c.println("weeks, he " + pastTenseVerb1 + " the floors, " + pastTenseVerb2 + " on the shelves, and unloaded " + largeNumber + " pound sacks");
        c.println("of flour from the delivery trucks.\n");
        c.println("Finally, "+famousFemale+", the owner, told "+maleFriend+" that she would teach him to make bread. Now,");
        c.println("pay attention, "+maleFriend+",” she said every day. “I'll make the first batch of dough. Then you");
        c.println("can make the next batch while I go to "+place+".\n");
        c.println("Poor "+maleFriend+"! He had a habit of letting his "+bodyPart+" wander. When "  +famousFemale+ " left for "+place);
        c.println("he started to mix the ingredients. “Let me see,” he said. “I think she put in "+largeNumber2);
        c.println("packages of yeast.”\n");
        c.println("A short while later, the dough started "+ingEnding1+". It kept on "+ingEnding1+". "+maleFriend+" tried to");
        c.println("cover it with a(n) "+singularNoun+", but the dough wouldn't stop "+ingEnding1+". It was everywhere! ");
        c.println("“What can I do?” thought "+maleFriend+".\n");
        c.println("Just then, Tyana returned from toronto. “"+maleFriend+"” she screamed. “What have you done?”");
        c.println("“It's not my fault,” cried "+maleFriend+". “The dough just started "+ingEnding1+" and wouldn't stop.”");
        c.println(famousFemale + " had to let him go. Now "+maleFriend+" has a job making "+singularNoun+". I don't think he'll ever");
        c.print("eat bread again, let alone make it.");
      */


  }

 public static void main(String []args){
     Action1();
 }

}


另外,我对jPanel的工作方式有些困惑。我发现了许多在jPanel上显示内容的方法,但我不知道应该使用哪种方法。

最佳答案

我立即想到了两种方法。

第一种更为简单,那就是使用paintComponent(Graphics)方法。每当程序认为需要重新粉刷对象时,都会自动调用此方法,例如,最小化和ermmm最小化保存jpanel的窗口。

这是一个简单的例子...

import javax.swing.JPanel;

import java.awt.Graphics;

import java.lang.Override; //for @Override

class yourClass extends JPanel { //yourClass is the JPanel
    @Override //if you aren't overriding correctly this makes the compiler tell you
    protected void paintComponent(Graphics gr){
        super.paintComponent(gr);
        gr.drawString("string literal or a string variable", 0,10);
    }
}


代码说明...

super.paintComponent(gr);覆盖时应始终使用super命令,在这种情况下,您将覆盖JPanel的paintComponent方法,因此请按照所示进行操作。这也启用了增量绘制(如我所说的那样),这意味着程序不会将屏幕绘制为白色,而是先绘制要执行的操作。因此,您可以绘制一个黑框,然后在一分钟后绘制一个红色框,并且该黑框不会消失。

gr.drawString(String strText,int x,int y);图形类的drawString方法。图形gr由程序通过一系列隐藏方法创建。因此,不必担心创建它,只需将它放在paintComponent参数中,然后让程序调用paintComponent。

对于drawString命令,x和y是坐标,我在10点是y,因为根据我的经验,该方法的工作方式如下:从坐标(x,y)(相对于JPanel)而言,向左绘制,和向上。因此,如果y为0,则将从JPanel中提取文本。这意味着您将无法看到它,因为在JPanel外部绘制的任何内容都不会出现。 (我不知道为什么会这样)

这是使用paintComponent的,如果使用循环绘制每条线,它将可以有效地工作。因为drawString画一条线。这比下一个解决方案简单得多。

下一个解决方案是使用布局。如果您想以1到1的比例绘制每条线,那么每次都向下一行,我建议您使用gridLayout(行,列)。如果要有20行文本,则该方法将需要new GridLayout(20,1);。

想法是要计算行和列的数量。

 .    Column 1


第1行

第2行

第3行

等等

GridLayout的缺点是您需要一个对象来容纳每个字符串(在这种情况下,我建议使用JLabel)。

您还需要启用增量绘画,(或者我非常怀疑),这意味着创建一个扩展JLabel的类。

最后,您还需要将JLabel作为子级添加到JPanel

JPanel.add(JLabel);


尽管您似乎已经使用了一些布局方面的东西,但这可能并不难。

举个例子...

import java.awt.GridLayout;
import java.awt.Graphics;

import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JFrame;

import java.lang.Override;

class YourMainClass {
    static JFrame mainFrame;
    static YourJLabel clsLabel;
    static JPanel pnlJPanel;
    public static void main(String[]args){
        mainFrame = new JFrame("Testing"); //initialize, and set size the frame
        mainFrame.setSize(500,500);
        pnlJPanel = new JPanel();//initialize our panel
        pnlJPanel.setLayout(new GridLayout(3,1));//set its layout to gridlayout, with grid of 3 rows and 1 column
        clsLabel = new YourJLabel(); //create a jlabel, add some text to it, then add it to the jpanel
        clsLabel.setText("some");
        pnlJPanel.add(clsLabel);
        clsLabel = new YourJLabel();
        clsLabel.setText("Text");
        pnlJPanel.add(clsLabel);
        clsLabel = new YourJLabel();
        clsLabel.setText("drawn");
        pnlJPanel.add(clsLabel);
        mainFrame.add(pnlJPanel);//add the jpanel to the frame
        mainFrame.pack();        //believe you already know these two lines
        mainFrame.setVisible(true);
    }
}
class YourJLabel extends JLabel {
    YourJLabel(){
        super();
        setOpaque(true); //going on memory, by default jlabels opaque is false, or transparent
    }
    protected void paintComponent(Graphics gr){
          super.paintComponent(gr);
    }
}


此示例执行以下操作:

java - 如何在Java jPanel上打印一些文本?-LMLPHP

使用布局时,所有内容都是相对于其父级的。

请注意,我们再也无法访问前两个JLabel,如果您想在使用类实例的同时访问它们,则必须将实例存储在可以从中获取它们的地方。存储它们的理想位置是数组。一个简单的例子...
    YourJLabel [] aryJLabel =新的YourJLabel [3];

[3]确定数组的大小,一旦创建就无法更改。 YourJLabel上的[]表示您正在创建YourJLabel的数组。

关于java - 如何在Java jPanel上打印一些文本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37555967/

10-13 05:58