Kevin Zhang Kevin Zhang - 28 days ago 16
Java Question

Why my Jtextfield and jmenubar doesnt work

Q1: MY JTextFeild and JMenuBar does not show up, and I don't know why
there is an picture of the program.

Q2: I have seen a lot of ways to write a program of interface, I don't know which way is better. Is this way or this way: https://www.youtube.com/watch?v=706Ye4ubtEY

import javax.swing.*;
import java.awt.*;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Real_Interface extends JFrame implements ActionListener {

public Real_Interface(){
JFrame window = new JFrame();
window.add(new JLabel("Rocket Data Visualization Tool"));
window.setTitle("Rocket Data Visualization Tool");
window.setSize(640, 480);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);

JTextField tf = new JTextField();
tf.setText("New Text");
String str = tf.getText();
tf.setVisible(true);

JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem menuItem = new JMenuItem("haha");
JMenuItem menuItem2 = new JMenuItem("haha2");
file.add(menuItem);
file.addSeparator();
file.add(menuItem2);
bar.add(file);


JButton button = new JButton("OK");
window.add(button);
button.setBounds(250, 400, 150, 40);
button.addActionListener(this);
}
public static void main(String[] args){
new Real_Interface();
}

public void actionPerformed(ActionEvent e) {
System.out.println("The Button Works!");
Plot.main(null);
}

}

Answer

A few reasons

The menubar has not been assigned to the frame

window.setJMenuBar(bar);

The textfield has not been added

window.add(textfield, BorderLayout.PAGE_START);

This component is visible by default so calling setVisible is unnecessary.

The frame needs to be made visible after all components have been added to the frame rather than beforehand

window.setVisible(true);