有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带有setUndergrated true的java JFrame

使用setUndercorated = true,如何使用退出按钮退出窗口

public static void main(String[] args) {
    JLabel label = new JLabel("My label");
    label.setText("Wello!");

    JFrame f = new JFrame();
    f.setUndecorated(true);
    f.setAlwaysOnTop(true);
    f.setResizable(false);
    try {
        f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("file")))));
    } catch (IOException e) {
        e.printStackTrace();**strong text**
    }
    f.pack();
    f.setVisible(true);
}

}


共 (1) 个答案

  1. # 1 楼答案

    您需要将自己的退出按钮添加到面板:

    import javax.swing.*;
    import javax.swing.border.LineBorder;
    import java.awt.*;
    
    public class Example extends JFrame {
    
        public Example() {
    
            setUndecorated(true);
            setAlwaysOnTop(true);
            setResizable(false);
            setMinimumSize(new Dimension(300, 300));
            setLocationRelativeTo(null);
    
            setLayout(null);
    
            JButton closeButton = new JButton("X");
            closeButton.setFocusPainted(false);
            closeButton.setBorder(new LineBorder(Color.black, 1));
            closeButton.setBounds(0, 0, 30, 30);
            closeButton.addActionListener(e -> dispose());
            add(closeButton);
    
            pack();
            setVisible(true);
        }
    
        public static void main(String[] args) {
            new Example();
        }
    }
    

    这将导致JFrame看起来像:

    enter image description here

    当您单击该按钮时,它将关闭JFrame