5

これJTextFieldは、マウスを本来あるべき場所に移動すると、マウスアイコンがカーソルに変わり、クリックすると表示されるためです。ただし、起動時には表示されません。私は何が欠けていますか?

public class JavaSwingTextfield extends JFrame {
    private static final long serialVersionUID = 1L;

    JTextField myTextField;

    public JavaSwingTextfield(){

        /***** JFrame setup *****/

        // Set the size of the window
        setSize(600,600);

        // Make the application close when the X is clicked on the window
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Makes the JFrame visible to the user
        setVisible(true);

        /***** JFrame setup END *****/


        /***** JButton setup *****/

        // Create a JLabel and set its label to "Start"
        myTextField = new JTextField("Start");

        // Set the label's size
        myTextField.setSize(100, 50);

        // Put the label in a certain spot
        myTextField.setLocation(200, 50);

        // Set a font type for the label
        //Font myFont = new Font("Serif", Font.BOLD, 24);
        //myTextField.setFont(myFont);

        // Add the label to the JFrame
        add(myTextField);

        /***** JButton setup END *****/

    }


    /***** The main method *****/
    public static void main(String[] args){ 

        new JavaSwingTextfield();

    }

}
4

2 に答える 2

12
  • Event Dispatch ThreadGUIコンポーネントの作成に使用
  • setVisible(..)すべてのコンポーネントが追加される前に呼び出さないでくださいJFrame(これは上記のコードスニペットの実際のエラー+1から@Clarkです)
  • JFrame不必要にクラスを拡張しないでください
  • 電話しないでください。表示を設定する前にsetSize(..)電話してください。JFrame#pack()JFrame
  • むしろそのコンストラクターを見るように要求setSize()しないでください:JTextFieldJTextField(String text,int columns)
  • 適切なを使用してくださいLayoutManager。いくつかの例については、こちらを参照してください:レイアウトマネージャーのビジュアルガイド

これが私が作った例です(基本的には修正を加えたコード):

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class JavaSwingTextfield {

    private JTextField myTextField;

    public JavaSwingTextfield() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        myTextField = new JTextField("Start");
        
        // Add the label to the JFrame
        frame.add(myTextField);
        
        //pack frame to component preferred sizes
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Create UI on EDT
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JavaSwingTextfield();
            }
        });
    }
}
于 2012-11-05T05:00:44.900 に答える
4

を表示JTextfieldした後、を追加しJFrame ます。事前に追加するだけです。JFrame JTextField

于 2012-11-05T04:38:42.130 に答える