【问题标题】:Why paint class is not working with setDefaultLookAndFeelDecorated(true)为什么油漆类不适用于 setDefaultLookAndFeelDecorated(true)
【发布时间】:2018-05-28 20:45:03
【问题描述】:
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() 方法绘制的椭圆就会消失。即使最大化或最小化框架,我也希望绘制的图形保持不变。

【问题讨论】:

  • 发生这种情况是因为没有调用 repaint。推理可能是 Windows 未发送 setDefaultLookAndFeelDecorated 设置为 true 的事件,而 Swing 需要触发 repaint。
  • 你不应该直接在 JFrame 上开始绘图。您应该在 JPanel 的 paintComponent 方法中进行绘制。

标签: java


【解决方案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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多