java - JDesktopPane.setOpaque(false) 加上 JInternalFrame 的使用会抑制包含 JFrame 的关闭

标签 java swing

Linux 上的 Java 1.8.0_60。创建一个 JFrame,设置一个 JDesktopPane 作为其内容 Pane ,并用于在任意位置显示一些线条图形和 JInternalFrame。似乎某些调用或调用位置会导致无法通过单击“x”来销毁 JFrame 的状态。

这些是类(class);不是注释“X1”和“X2”。

import java.awt.*;
import javax.swing.*;

public class InternalFrameEventDemo extends JFrame {
  public InternalFrameEventDemo(String title) {
    super(title);
    JDesktopPane desktop = new MyDesktop();
    this.setContentPane(desktop);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    this.setVisible(true);
  }

  private class MyDesktop extends JDesktopPane {
    public MyDesktop(){
        this.setPreferredSize(new Dimension(500,300));
    }
    public void paintComponent( Graphics sg ) {
        super.paintComponent( sg );
        new StarLabel( this, 100, 100, "Here at 100" );  // X1
        new StarLabel( this, 200, 200, "Here at 200" );
    }
  }

  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new InternalFrameEventDemo("InternalFrameEventDemo");
        }
    });
  }
}

星标

import java.awt.*;
import javax.swing.*;

public class StarLabel extends JInternalFrame {
  public StarLabel( JComponent panel, int x, int y, String text ) {
    super( null, false, true, false, false );
    this.setBorder( null );
    ((javax.swing.plaf.basic.BasicInternalFrameUI) this.getUI()).setNorthPane(null);
    this.setVisible( true );
    this.setOpaque( false );  // X2
    this.add( new JLabel( text ) );
    this.pack();
    this.setLocation( x, y );
    panel.add( this );
  }
}

X1:如果未在 paintComponent 中调用 StarLabel 构造函数,则效果仍然不存在。

X2:如果 setOpaque 未设置为 false,也不会出现该效果。

现在我可以将 setOpaque 与 true 一起使用 - false 纯粹是偶然。但我仍然想知道我是否违反了小字中的其中一项规则?或者...?

最佳答案

But I'd still like to know whether I an violating one of the rules in the small print?

是的。

The effect remains absent if the StarLabel constructor calls aren't made in paintComponent.

绘画方法仅用于绘画。

永远不要在绘画方法中创建 Swing 组件。您无法控制何时调用绘画方法,因此每次 Swing 确定需要创建组件时您都将创建新组件。

组件应该在类的构造函数中创建。

关于java - JDesktopPane.setOpaque(false) 加上 JInternalFrame 的使用会抑制包含 JFrame 的关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40562760/

相关文章:

java - 静态和非静态同步,为什么输出结果不同?

java - 在 appengine 上维护开发和实时站点

java - 我如何实现新的 JFrame 功能

java - JFrame 多次使用一个组件

java - 将数据发送回 Intent

java - 我们如何删除 arrayList 中的多个值?

java - 数组方法有问题

java - Swing:带标题行的表格

java - 从文件读取到 JTextArea

java - 将数组从一个类调用到另一个类