我正在使用以下调用从我的主类创建另一个类的对象:
JSplash splash = new JSplash();
但是,当我创建这个对象时,它会执行JSplash类的构造函数并给出我的窗口和我的按钮。但它不会在画框上画画。你可以帮我解决这个问题吗?
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* @author Curtis
*/
public class JSplash extends DFrame implements ActionListener {
//declaration of variable objects
Font myFont = new Font("Arial", Font.BOLD, 20);
JButton myButton = new JButton("Click Me!");
Color bgColor = new Color(0, 0, 255);
Color firstColor = new Color(255, 255, 255);
String first = "Welcome to DaemoDynamics!";
String last = "Click the Button";
String middle = "";
String middle2 = "";
private static int count = 1;
DFrame splash = new DFrame();
//Constructor
public JSplash() {
setDefaultLookAndFeelDecorated(true);
System.out.println("Hello");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
splash.add(myButton);
getContentPane().setBackground(bgColor);
//adds action listener
myButton.addActionListener(this);
splash.setVisible(true);
}
//Paint method
@Override
public void paint(Graphics e) {
System.out.println("paint is being reached");
super.paint(e);
e.setFont(myFont);
e.setColor(firstColor);
e.drawString(first, 14, 80);
e.drawString(last, 70, 240);
e.drawString(middle, 75, 150);
e.drawString(middle2, 60, 175);
}
//Listener Method
@Override
public void actionPerformed(ActionEvent e) {
//First Time button hit
if (count == 1) {
middle = "Brighter Business";
middle2 = "for A Brighter Future";
last = "Click Again to Begin";
repaint();
//increases button count
count++;
} else//if button count is not 1
{
splash.setVisible(false);
FinalProject app = new FinalProject();
}
}
}
答案 0 :(得分:1)
您在DFrame
构建器中创建了一个新的JSplash
,然后将您的组件添加到IT。这根本不是必需的。删除要引用的引用,只需使用您已扩展的DFrame
。虽然我正在看,但是没有布局管理器,这对我们没有帮助。永远不会调用paint方法,因为屏幕上显示的窗口绝不是JSplash
,而是你创建的DFrame
(称为splash)
答案 1 :(得分:0)
创建一个扩展JPanel的新类。确保您的按钮已添加到该面板,并使用您的逻辑覆盖该面板的paintComponent()方法。这应该工作。
自定义绘画应该在paintComponent方法中完成。理想情况下,您不应该覆盖JFrame的paint方法。