java中GUI出現的問題及解決方案

來源:互聯網
上載者:User

   記錄學習過程中經曆的點點滴滴,只為以後不犯重複的錯誤。
   好多次做完GUI介面時,發現一個很有趣的問題,要先調整視窗大小才會顯示出組件,而不是立馬顯示出組件,於是乎google,才發現是在組件還未添加到面板前就將視窗(JFrame)設為可見(setVisible()),控制項並不會引發重繪。解決方案很簡單,只需要等所有組件都準備好以後才將JFrame的setVisible()設定為true。亦或是你很倔,非要在調用setVisible()之後添加組件,那麼你也可以這樣做:getContentPane().invalidate(); 
   順便說另一個遇到的問題,在java.swing的JFrame中添加密碼框和文字框組件沒有全部顯示。理由是JFrame的預設布局是BorderLayout,它會在BorderLayout.center位置以布滿整個地區的形式顯示最後一個添加上去的組件。不信用getLayout()看看JFrame的布局方式,一切將會真相大白。
   本次實驗用到的原始碼:


public class Xiaozujian extends JFrame {private JLabel loginl;private JLabel passwordl;private JTextField  login;private Container containter;private JTextArea  textarea;private JPasswordField  password;public Xiaozujian(){ initFrame();init();//login.setText(""+getLayout());setVisible(true);//將這個方法放在後面,以至於所有組件立馬能顯示,是關鍵}public void initFrame(){setTitle("小工具");setSize(400,400);containter=getContentPane();//setBackground(Color.BLUE);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public void init(){loginl=new JLabel("登入名稱:");login=new JTextField(10);containter.add(loginl);containter.add(login);passwordl=new JLabel("密碼:");password=new JPasswordField(10);containter.setLayout(new FlowLayout());//必須設定布局方式,否則不顯示containter.add(passwordl);containter.add(password);textarea=new JTextArea(8,20);containter.add(new JScrollPane(textarea));password.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){textarea.append("登入名稱:"+login.getText()+"    "+"密碼:"+password.getSelectedText());//getSelectedText()顯示選中的textarea.append("\n");   }});}public static void main(String[] args) {// TODO Auto-generated method stubXiaozujian   x=new Xiaozujian ();}}

尼瑪,文字部分調整了後還是多出一條灰色的地區,灰常不理解,這讓處女座的我怎麼辦

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.