首页 > 解决方案 > 我无法在屏幕上显示 JTextFields 和 JButton

问题描述

为什么我不能在屏幕上显示“loginField”、“passwordField”和“loginButton”?除非我注释掉“loginScreen();”,否则背景颜色也不会变为红色

主.java

import gui.*;

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


public class Main {
    static class MyThread implements Runnable {
        public void run() {
            createGUI();
        }
    }

    static class Thread2 implements Runnable {
        public void run() {
            for(int i = 0; i < 10; i++) {
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    return;
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread());
        Thread thread1 = new Thread(new Thread2());

        thread.start();
        thread1.start();
        //createGUI();
    }

    public static void createGUI() {
        JFrame frame = new JFrame("Title");
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        int width = 800;
        int height = 500;

        frame.setVisible(true);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setBounds(d.width/2 - width/2, d.height/2 - height/2, width, height);

        frame.add(new MyPanel());
    }
}

MyPanel.java:

package gui;

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

public class MyPanel extends JPanel {


    public MyPanel() {

        setLayout(null);
        setBackground(Color.RED);
        loginScreen();
    }

    public void loginScreen() {
        JTextField loginField = new JTextField();
        JTextField passwordField = new JTextField();
        loginField.setBounds(800/2 - 200/2, 170, 200, 20);
        passwordField.setBounds(800/2 - 200/2, 200, 200, 20);
        MyButton loginButton = new MyButton(800/2 - 100/2, 230, 100, 20, "Login");

        add(loginButton);
        add(loginField);
        add(passwordField);
    }
}

标签: java

解决方案


不确定 MyButton 类。但是要在屏幕上显示框架,请在末尾添加 setVisible:

frame.add(new MyPanel());
frame.setVisible(true);

本教程可能会有所帮助https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html


推荐阅读