我正在创建一个短语模板文字游戏,也称为 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/