如何在Java中为方法添加图形?请看我的计划

时间:2016-06-01 02:40:35

标签: java swing graphics

我正在创建一个短语模板文字游戏,也称为疯狂文库。 到目前为止,我能够创建一个控制台来显示基于输入放在一起的故事。我也能够创建一个背景颜色,但是当我想添加一些图形,如矩形和正方形时,我卡住了。您如何建议我可以将其纳入我的计划?

提前谢谢!!

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

public class MadLibs {

 public static void Action1 () 
  {
    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();

    JLabel label = new JLabel("<html>Last summer, my friend "+ maleFriend + " got a job at the " + adjective1 +" Pastry Shop. For the first few<br>"
            + "weeks, he" + pastTenseVerb1 + " the floors, " + pastTenseVerb2 + " on the shelves, and unloaded " + largeNumber + " pound sacks <br>"
            +"of flour from the delivery trucks."
            + "</html>"
            , JLabel.CENTER);
    JFrame window = new JFrame("Please print this");        
    window.setSize(600, 800);
    window.add(label);
    window.getContentPane().setBackground(Color.CYAN);
    window.setVisible(true);

  }

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

}

1 个答案:

答案 0 :(得分:3)

您需要创建 JPanel 类的扩展名。

class drawPanel extends JPanel {
    drawPanel() {
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //Put your graphics code here
    }
}

然后在主类中创建drawPanel,向其添加标签,并将drawPanel添加到JFrame。

JFrame window = new JFrame("Please print this"); 
//Create your custom JPanel class here
drawPanel content = new drawPanel();
//Add the label to the drawPanel instead of the JFrame
content.add(label);       
window.setSize(600, 800);
//Add the drawPanel to the JFrame
window.add(content);
window.getContentPane().setBackground(Color.CYAN);
window.setVisible(true);