【问题标题】:Why the textfield is taking whole screen of a window in Java awt [duplicate]为什么文本字段在Java awt中占据整个窗口的屏幕[重复]
【发布时间】:2016-11-25 18:27:02
【问题描述】:
import java.awt.*;
public class myFrame extends Frame {

  myFrame(){
    TextField tf=new TextField(10);

    setVisible(true);
    setSize(400,400);
    setTitle("myFrame");
    setBackground(Color.red);
    add(tf);

  }
public static void main(String[] args){
  myFrame f=new myFrame();

 }  
}

output image

【问题讨论】:

    标签: java


    【解决方案1】:

    一个Frame默认使用BorderLayout,如果你以“默认”方式(没有BorderLayout约束)给它添加一个组件,它将被添加到BorderLayout.CENTER位置,占据整个Frame。

    可能的解决方案包括使用不同的布局(例如 FlowLayout 甚至更好),嵌套组件(例如使用自己的布局的面板)并将您的 TextField 添加到其中。

    附带问题:为什么要使用超过 2 代的 AWT GUI 库?

    例如,使用 Swing

    import java.awt.Dimension;
    import javax.swing.*;
    
    public class SwingExample extends JPanel {
        private JTextField textField = new JTextField(10);
    
        public SwingExample() {
            // this is a JPanel that uses FlowLayout by default
            setPreferredSize(new Dimension(400, 400));
            add(textField);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    
        private static void createAndShowGui() {
            SwingExample mainPanel = new SwingExample();
            JFrame frame = new JFrame("SwingExample"); // uses borderlayout
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.add(mainPanel, BorderLayout.CENTER); // add jpanel to center position
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2019-11-21
      相关资源
      最近更新 更多