Put a JTextfield on a JPanel?

試著忘記壹切 提交于 2019-12-01 11:18:45

问题


Why the textfield is not appearing on my panel which is inside my frame? I mean is there some additional action necessary to make the components of the panel visible?

I hope somebody can help me....

public class example1  {

    public static void main(String[] args) {

    JFrame tt=new TT();
    }
}
class TT extends JFrame {

    JTextField textField;
    JPanel panel;
    JButton button1;
    JButton button2;

    public TT() {
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setTitle("Bla Blubb");
        setResizable(false);
        setLayout(null);

        panel=new JPanel();
        panel.setBounds(5, 5, 290, 290);
        add(panel);

        textField=new JTextField();
        textField.setBounds(5, 5, 280, 50);
        panel.add(textField);

            setVisible(true);

      }
}

回答1:


import java.awt.FlowLayout;
import javax.swing.*;

class TT extends JFrame {

    JTextField textField;
    JPanel panel;
    JButton button1;
    JButton button2;

    public TT() {
        //setSize(300, 300);  // better to use pack() (after components added)
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // better to use
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        //setLocationRelativeTo(null);  // better to use..
        setLocationByPlatform(true);
        setTitle("Bla Blubb");
        setResizable(false);
        //setLayout(null); // better to use layouts with padding & borders

        // set a flow layout with large hgap and vgap.
        panel = new JPanel(new FlowLayout(SwingConstants.LEADING, 10, 10));
        // panel.setBounds(5, 5, 290, 290); // better to pack()
        add(panel);

        //textField = new JTextField(); // suggest a size in columns
        textField = new JTextField(8);
        //textField.setBounds(5, 5, 280, 50); // to get height, set large font
        textField.setFont(textField.getFont().deriveFont(50f));
        panel.add(textField);

        pack(); // make the GUI the minimum size needed to display the content
        setVisible(true);
    }

    public static void main(String[] args) {
        // GUIS should be constructed on the EDT.
        JFrame tt = new TT();
    }
}


来源:https://stackoverflow.com/questions/22240066/put-a-jtextfield-on-a-jpanel

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