簡體   English   中英

每次我最小化Java中的窗口時,如何放置JTextField而不使其生成更多字段?

[英]How to place a JTextField without it generating more fields every time I minimize the window in Java?

我的代碼在特定的隨機位置放置了一個JTextField ,但它還在Frame的頂部創建了一個通用的JTextField ,我不希望這樣做。 當我最小化它,然后重新最大化它時,它會在第一個JTextField旁邊並一次又一次地創建第二個JTextField 它還會刪除在該字段中鍵入的任何內容。 請注意,當我將JTextField放置在隨機位置時,我希望在最小化窗口時將其保留在該位置。 碼:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.Random;

@SuppressWarnings("serial")
public class AC extends JPanel implements ActionListener {

    JTextField text = new JTextField(10);
    int x;
    int y;

    public AC() {
        Random r = new Random();
        x = r.nextInt(500);
        y = r.nextInt(500);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        JTextField text = new JTextField(10);
        text.setBounds(x, y, 150, 20);
        this.add(text);
    }

    static void createandshowGUI() {
        JFrame frame = new JFrame("AC");
        frame.getContentPane().setBackground(Color.white);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setSize(dim.width, dim.height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new AC());
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createandshowGUI();
            }
        });
    }

    public void actionPerformed(ActionEvent e) {
    }

}

繪畫方法僅用於繪畫,而不用於創建組件。

您永遠不要在paintComponent()方法中創建組件。 每次Swing確定需要重繪組件時,都會調用paintComponent()方法,以便創建一個新組件。

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(dim.width, dim.height);   

由於您正在使用setExtendedState(...)方法來設置框架的大小,因此不需要上面的代碼。

為什么要在隨機位置放置文本字段? 聽起來像一個奇怪的設計。 Swing旨在與布局管理器一起使用。 閱讀有關布局管理器的Swing教程中的部分,以獲取更多信息。

每當您最小化和重新最大化窗口時,都會調用paintComponent()方法。 您正在內部paintComponent()方法中創建new JTextField ,因此,只要您最大化窗口,就會創建一個新的JTextField

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM