在Java中,可以通过以下几种方法在不调用main
方法的情况下运行paint()
方法:
Swing
库创建一个简单的GUI应用程序,并在其中重写paint()
方法。import javax.swing.*;
import java.awt.*;
public class MyApp extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 在这里编写paint()方法的内容
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("MyApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MyApp());
frame.pack();
frame.setVisible(true);
}
}
JavaFX
库创建一个应用程序,并在其中重写paint()
方法。import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class MyApp extends Application {
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 275);
primaryStage.setTitle("MyApp");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
AWT
库创建一个简单的应用程序,并在其中重写paint()
方法。import java.awt.*;
import java.awt.event.*;
public class MyApp extends Frame implements WindowListener {
public MyApp() {
setSize(300, 200);
setTitle("MyApp");
addWindowListener(this);
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
// 在这里编写paint()方法的内容
}
public static void main(String[] args) {
MyApp app = new MyApp();
}
// 实现WindowListener接口的其他方法
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {System.exit(0);}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
}
以上三种方法都可以在不调用main
方法的情况下运行paint()
方法。具体选择哪种方法取决于您的应用程序需求和使用的库。
领取专属 10元无门槛券
手把手带您无忧上云