gpt4 book ai didi

java - 如何将paintComponent()添加到JPanel

转载 作者:行者123 更新时间:2023-12-01 14:35:51 25 4
gpt4 key购买 nike

我有 2 个类(class),Class2 和 Class4。我希望使用 p4.add(c2o) 和 f.add(p4) 方法将 Class2 中的绘画从 Class4 添加到 Class4 中的 JPanel 上。添加 GUI 没有任何问题,但我就是无法添加图形。

4级:

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Class4 {


public void mainMethod(int event){
JFrame f = new JFrame("Love Test");
if(event == 0){

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,200);
f.setLayout(null);

JPanel p = new JPanel(new BorderLayout());
p.setBounds(150, 0, 350, 75);
Class3 c3o = new Class3();
p.add(c3o);
f.add(p);

JPanel p2 = new JPanel();
Class7 c7o = new Class7();
p2.add(c7o);
p2.setBounds(0, 75, 500, 40);
f.add(p2);

JPanel p3 = new JPanel();
p3.setBounds(0, 0, 150, 75);
Class5 c5o = new Class5();
p3.add(c5o);
f.add(p3);

f.setVisible(true);

}

if(event == 5){

JPanel p4 = new JPanel();
Class2 c2o = new Class2();
p4.add(c2o);
p4.setBounds(0,115,500,55);
f.add(p4);
}

}


}

2级:

import javax.swing.JOptionPane;
import javax.swing.JPanel;

import java.util.Random;
import java.awt.*;



public class Class2 extends JPanel{

public void paint(Graphics g){
super.paint(g);
this.setBackground(Color.WHITE);
g.setColor(new Color(0,0,0));
String str = "";
String str2 = "";
Random rlove = new Random();
int love = rlove.nextInt(101);
Class3 c3o = new Class3();
str = c3o.boy.getText() + " and " + c3o.girl.getText() + "'s amount of love is " + love + "%.";
if(love >= 0 && love < 10){
str2 = "Stop thinking about that person anymore!";
}
if(love >= 10 && love < 20){
str2 = "1/100 percent chance...";
}
if(love >= 20 && love < 30){
str2 = "Little hope...";
}
if(love >= 30 && love < 40){
str2 = "Not even a kiss, stop talking about French kisses! (wise words of Rubesh)";
}
if(love >= 40 && love < 50){
str2 = "Near passing";
}
if(love >= 50 && love < 60){
str2 = "Just Pass";
}
if(love >= 60 && love < 70){
str2 = "Some effort needed.";
}
if(love >= 70 && love < 80){
str2 = "Grade A. A good chance.";
}
if(love >= 80 && love < 90){
str2 = "Good pair. Very good relationship!";
}
if(love >= 90 && love < 100){
str2 = "Perfect pair. Lost for words.";
}
if(love == 100){
str2 = "OH MY GOD!!!!!";
}
g.drawString(str,10,10);
g.drawString(str2,10,30);
}


}

如何将paintComponent添加到JPanel p4?谢谢!

最佳答案

  1. 不要使用JPanel#paint,建议使用JPanel#paintComponent,查看Performing Custom Painting
  2. 使用适当的布局管理器。您遇到的问题来自两个问题。首先,您的面板没有首选尺寸。重写 Class2getPreferredSize 方法并返回布局管理器的适当大小。

...

JPanel p4 = new JPanel(); // Default layout manager is FlowLayout
Class2 c2o = new Class2();
// c2o has not size (0x0 by default)...
p4.add(c2o);
p4.setBounds(0,115,500,55);
f.add(p4);

关于java - 如何将paintComponent()添加到JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16496041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com