Adding label and text box control to GUI

旧时模样 提交于 2019-12-04 06:17:01

问题


I would like to know what code to insert and where to add a simple label that can just say the word "Label" and a input text box that I can enter a number.

public CalculateDimensions() {

    JTabbedPane Tab = new JTabbedPane();
    JPanel jplInnerPanel1 = createInnerPanel("First Tab");
    Tab.addTab("One", jplInnerPanel1);
    Tab.setSelectedIndex(0);
    JPanel jplInnerPanel2 = createInnerPanel("Second Tab");
    Tab.addTab("Two", jplInnerPanel2);
    JPanel jplInnerPanel3 = createInnerPanel("Third Tab");
    Tab.addTab("Three", jplInnerPanel3);
    JPanel jplInnerPanel4 = createInnerPanel("Fourth Tab");
    Tab.addTab("Four", jplInnerPanel4);
    JPanel jplInnerPanel5 = createInnerPanel("Fifth Tab");
    Tab.addTab("Five", jplInnerPanel5);

    setLayout(new GridLayout(1, 1));
    add(Tab);
}
protected JPanel createInnerPanel(String text) {
    JPanel jplPanel = new JPanel();
    JLabel jlbDisplay = new JLabel(text);
    jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
    jplPanel.setLayout(new GridLayout(1, 1));
    jplPanel.add(jlbDisplay);
    return jplPanel;
}
public static void main(String[] args) {
    JFrame frame = new JFrame("Calculations");
    frame.addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    frame.getContentPane().add(new CalculateDimensions(),
            BorderLayout.CENTER);
    frame.setSize(400, 400);
    frame.setVisible(true);
}

}


回答1:


The Swing tutorial is an excellent resource for building GUIs.

Take a look at the visual guide and click on the components you want for detailed how to guides for creating text boxes, and other items.

http://download.oracle.com/javase/tutorial/ui/features/components.html




回答2:


in your public static void main() method you should not instantiate JFrame frame = new JFrame("Calculations");

This is where you are going wrong!

That line should read:

CalculateDimensions frame = new CalculateDimensions("Calculations");

You will also need to change the line says

public class CalculateDimensions {

(it's near the top) says

public class CalculateDimensions extends JFrame {

then inside the method called public class CalculateDimensions { you need to add a line after JPanel jplInnerPanel1 = createInnerPanel("First Tab"); which says

jplInnerPanel1.add(new JLabel("Label");


来源:https://stackoverflow.com/questions/5236575/adding-label-and-text-box-control-to-gui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!