java - 我无法在屏幕上显示 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);
}
}
解决方案
不确定 MyButton 类。但是要在屏幕上显示框架,请在末尾添加 setVisible:
frame.add(new MyPanel());
frame.setVisible(true);
本教程可能会有所帮助https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html
推荐阅读
- bash - 如何仅获取 bash ssh 版本号?
- javascript - 如何将数据从 api 推送到数据集中
- react-native - 如何使 createMaterialTopTabNavigator tabBar 背景颜色为线性渐变
- flutter - 如何在颤振中使用 Navigator.pop() 方法传递多个值?
- javascript - 如何在 Visual Studio 中以所有形式更新 javascript 文件的版本
- c# - 从 Chocolatey 生成的 exe 有他们的 Logo 和描述。有没有办法改变这个?
- amazon-web-services - 每日数据加载的 AWS API Gateway POST 请求
- swift - 复制 iPhone 故事板并直接粘贴到 iPad 故事板上,但并非每个视图控制器都能在 iPad 上正确显示
- javascript - onOpen 状态“失败”是什么意思?
- javascript - 来自类的 JSPDF 自动表格自定义样式