java - 如何向 Java 方法添加图形?请看我的程序

标签 java swing graphics

我正在创建一个短语模板文字游戏,也称为 mad libs。 到目前为止,我已经能够创建一个控制台来显示根据输入组合在一起的故事。我还可以创建背景颜色,但是当我想添加一些图形(例如矩形和正方形)时,我陷入了困境。您建议我如何将其合并到我的程序中?

提前谢谢您!!

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

}

最佳答案

您需要创建 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);

关于java - 如何向 Java 方法添加图形?请看我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37558537/

相关文章:

java - 为什么 UTF8 字符编码在我的项目中无法正常工作?

java - 判断一个数组是否可以形成一个图

java - RHEL 5 中带有 Files.createSymbolicLink (Java 7) 的符号链接(symbolic link)

值跳跃的Java for循环

java - 访问 ActionListener 类中的 Gui,使用计时器每 x 秒更新一次

用于等式 5((θ/β) - cos(2πθ/β)) 的 Java Swing GUI - 绘制连续图

java - 点不对齐

algorithm - 二维矢量图形的最佳数据存储算法

c - 表面和纹理的区别(SDL/通用)

java - 如何确定 JTextField 的大小?