package Jai;
import javax.swing.*;
import java.awt.*;
public class tuna extends JFrame{
tuna(){
super("Title");
setLayout(new FlowLayout());
getContentPane().setBackground(Color.white);
}
public void paint(Graphics g){
super.paint(g);
g.fillOval(50, 100, 100, 155);
}
public static void main(String[] arg){
JFrame.setDefaultLookAndFeelDecorated(true);
tuna obj = new tuna();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(500,500);
obj.setVisible(true);
}
}
我有JFrame
,我使用paint方法在框架上绘制椭圆。
每当我尝试最大化或最小化窗口时,通过paint()
方法绘制的椭圆消失。我希望绘制的图形即使在我最大化或最小化帧时也能保持不变。
答案 0 :(得分:1)
您的问题是覆盖了错误对象的错误方法。您必须覆盖主面板的paintComponent
方法。这是正确的代码:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class tuna extends JFrame {
tuna() {
super("Title");
// you need to override the method paintComponent for the main panel
setContentPane(new JPanel(new FlowLayout()) {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(50, 100, 100, 155);
}
});
getContentPane().setBackground(Color.white);
}
public static void main(String[] arg) {
JFrame.setDefaultLookAndFeelDecorated(true);
tuna obj = new tuna();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(500, 500);
obj.setVisible(true);
}
}