2017-07-07 28 views
1

我有一個簡單的java程序,當我運行它時,使用eclipse,它顯示我已設置爲佈局的3個JButton。按鈕設置爲更改佈局的對齊方式。所以你按左邊對齊左邊和右邊對齊右邊和中心對齊中心。Java程序不會反應,直到窗口被調整大小

雖然這些按鈕可以做到這一點,但在調整窗口大小之前,窗口中的對齊方式不會改變。

我試着更新jdk和eclipse,並沒有做出改變,我不能看到代碼本身的問題。

任何人都知道這是爲什麼?

import javax.swing.JFrame;

public class Main { 
    public static void main(String []args){ 

     Layout_buttonsAndActionEvents layout = new Layout_buttonsAndActionEvents(); 

     layout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     layout.setSize(300,300); 
     layout.setVisible(true); 



    } 

} 



import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 

public class Layout_buttonsAndActionEvents extends JFrame { 

    private static final long serialVersionUID = 1L; 
    private JButton leftButton; 
    private JButton rightButton; 
    private JButton centerButton; 

    private FlowLayout layout; 
    private Container container; 

    public Layout_buttonsAndActionEvents(){ 
     super("The Title"); 
     layout = new FlowLayout(); 
     container = new Container(); 
     setLayout(layout); 


     leftButton = new JButton("Left"); 
     add(leftButton); 
    //Align to the left 
     leftButton.addActionListener(new ActionListener(){ 

      public void actionPerformed(ActionEvent event){ 
       layout.setAlignment(FlowLayout.LEFT); 
       layout.layoutContainer(container); 
      } 
     }); 


    centerButton = new JButton("Center"); 
    add(centerButton); 

    //Align to the right 
     centerButton.addActionListener(new ActionListener(){ 

       public void actionPerformed(ActionEvent event){ 
        layout.setAlignment(FlowLayout.CENTER); 
        layout.layoutContainer(container); 
       } 
      }); 

     rightButton = new JButton("Right"); 
     add(rightButton); 

     //Align to the right 
      rightButton.addActionListener(new ActionListener(){ 

       public void actionPerformed(ActionEvent event){ 
        layout.setAlignment(FlowLayout.RIGHT); 
        layout.layoutContainer(container); 
       } 
      }); 



    } 


} 
+1

您是否在更改對齊後重新包裝窗口? –

+2

你能發佈你的代碼嗎? –

+1

請勿發表評論。您可以編輯您的問題並將其添加到那裏。 – byxor

回答

1

因爲你要添加的按鈕到JFrame的內容 窗格(通過這實在是一個調用add()方法 getContentPane()。add())你需要調用 內容窗格上的revalidate()。

在這三個動作偵聽器,更改:

layout.setAlignment(FlowLayout.XXX); 
    layout.layoutContainer(container); 

到:

layout.setAlignment(FlowLayout.XXX); 
    getContentPane().revalidate(); 

此外,您還可以刪除所有引用到名爲「容器」,因爲它什麼也不做你的榜樣變量。

+1

謝謝,這固定它 – Yzma

0

當您調整JFrame的大小時,將重新驗證其大小和佈局。同樣,在添加已更改的佈局以應用視覺差異之後,您必須驗證並重新繪製框架。

確保改變佈局之後調用順序這些方法:

setLayout(layout); 
repaint(); 
revalidate(); 
+0

並且這會被添加到主類或佈局類中? – Yzma

+0

@Yzma它會進入動作監聽器。確保用「JFrame」對象的名稱替換「frame」。 –

+0

它仍然只是改變窗口調整後的路線,我確定我改變了它,你說的做 – Yzma

相關問題