我现在刚刚学习 java,我试图找出问题所在,但每次运行代码时,我都会得到不同的结果。这是我正在编写的一个程序,或多或少是为了弄清楚如何使用 java,但有些对象没有按应有的方式出现。
package main;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
//import java.awt.event.*;
public class Main extends JFrame {
JButton button = new JButton();
JTextField textField = new JTextField();
JTextArea textArea = new JTextArea();
int buttonClicked;
public Main() {
Toolkit tk = Toolkit.getDefaultToolkit(); // creates toolkit
Dimension screenSize = tk.getScreenSize(); // sets screen dimensions
Dimension frameDim = new Dimension(400, 400); // sets frame dimensions
int xPos = (screenSize.width / 2) - (frameDim.width / 2); // sets xPos
int yPos = (screenSize.height / 2) - (frameDim.height / 2); // sets yPos
this.setSize(frameDim); // sets jframe size
this.setVisible(true); // sets jframe visible
this.setLocation(xPos, yPos); // sets jframe location to xPos and yPos
this.setResizable(false); // sets Resizable to false
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // exits on close
this.setTitle("This is a Frame");
JPanel panel = new JPanel(); // creates a panel
this.add(panel); //adds panel to JFrame
JLabel label = new JLabel("I'm a label"); // creates a label with text
label.setText("I say something"); // changes the text in the label
label.setToolTipText("this is a label"); // sets the tool-tip
panel.add(label); // adds the label to the panel
JButton button = new JButton("I am a button"); // creates a button
button.setText("I am still a button"); // changes text on the button
button.setBorderPainted(true); // adds border (default)
button.setContentAreaFilled(true); // adds area inside border (default)
button.setToolTipText("It's a button"); // sets the tool-tip
panel.add(button); // adds the button to the panel
JTextField textField = new JTextField("words", 15); // creates textField
textField.setColumns(10); // sets textField size
textField.setText(""); //changes textField text
textField.setToolTipText("this is a textField"); // sets the tool-tip
panel.add(textField); //adds textField to the panel
JTextArea textArea = new JTextArea(15, 20);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
panel.add(textArea);
JScrollPane scrollBar = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scrollBar);
this.add(panel);
}
public static void main(String[] args) {
new Main();
// new TestTextArea();
}
}
问题是,当我运行时,textArea 和 textField 是否会出现在窗口中,这几乎是一个黑暗的镜头。有时,但很少见,按钮和标签甚至都没有出现...我想不出解决方案。
如果这有帮助,我正在运行 java 7 update 60,它也不适用于 update 55
最佳答案
这在每个 Swing 教程中都有解释,但我会再重复一遍。在添加所有元素之前,您不应该调用 setVisible(true)
。这应该是你做的最后一件事,就在调用 this.pack()
之后。
此外,Swing 组件不应该在事件调度线程之外使用。您正在主线程中执行所有操作。阅读http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
最后,面板应该被添加到框架中一次,而不是两次。
关于java - JTextField 和 JTextArea 在程序运行时随机不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24478296/