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

时间:2016-05-31 21:31:12

标签: java swing jframe jpanel

对某些人来说,这可能是一个非常明显的问题,但我无法弄明白。我是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上展示东西的方法,但我不知道应该使用哪一种。

1 个答案:

答案 0 :(得分:3)

我立即想到两种方法。

第一个更简单,就是使用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是坐标,我的y是10,因为根据我的经验,该方法按以下方式工作:从坐标(x,y)(这是相对于JPanel),绘制到左,向上。因此,如果y为0,则您的文本将从JPanel中删除。这意味着你无法看到它,因为在JPanel之外的任何东西都不会出现。 (我不知道具体原因)

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

下一个解决方案是使用布局。如果你想逐行绘制每一行,每次都是一行,我会推荐gridLayout(行,列)。如果你有20行文本,该方法将需要新的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);
    }
}

这个例子确实:

enter image description here

使用布局时,所有内容都与其父级相关。

请注意,我们无法再访问前两个JLabel,如果您想在使用类实例时访问它们,则必须存储从您那里获取它们的实例。存储它们的最佳位置是阵列。一个简单的例子......     YourJLabel [] aryJLabel = new YourJLabel [3];

[3]确定数组的大小,一旦完成就不能改变它。 YourJLabel上的[]表示您正在创建YourJLabel数组。