2012-10-05 31 views
3

我其中我想用卡layout.Here在中心位置,以顯示我的NEWUSER類的對象的主框架是我的主類定位部件

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



public class CardLayoutDemo implements ItemListener { 
JPanel cards; //a panel that uses CardLayout 
final static String BUTTONPANEL = "Card with JButtons"; 
final static String TEXTPANEL = "Card with JTextField"; 

public void addComponentToPane(Container pane) { 
    //Put the JComboBox in a JPanel to get a nicer look. 
    JPanel comboBoxPane = new JPanel(); //use FlowLayout 
    String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL }; 
    JComboBox cb = new JComboBox(comboBoxItems); 
    cb.setEditable(false); 
    cb.addItemListener(this); 
    comboBoxPane.add(cb); 

    //Create the "cards". 
    NewUser newUser = new NewUser(); 

    JPanel card1 = new JPanel(); 
    card1.add(new JButton("Button 1")); 
    card1.add(new JButton("Button 2")); 
    card1.add(new JButton("Button 3")); 

    JPanel card2 = new NewUser(); 


    //Create the panel that contains the "cards". 
    cards = new JPanel(new CardLayout()); 
    cards.add(card1, BUTTONPANEL); 
    cards.add(card2, TEXTPANEL); 

    pane.add(comboBoxPane, BorderLayout.PAGE_START); 
    pane.add(cards, BorderLayout.CENTER); 
} 

public void itemStateChanged(ItemEvent evt) { 
    CardLayout cl = (CardLayout)(cards.getLayout()); 
    cl.show(cards, (String)evt.getItem()); 
} 

/** 
* Create the GUI and show it. For thread safety, 
* this method should be invoked from the 
* event dispatch thread. 
*/ 
private static void createAndShowGUI() { 
    //Create and set up the window. 
    JFrame frame = new JFrame("CardLayoutDemo"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    //Create and set up the content pane. 
    CardLayoutDemo demo = new CardLayoutDemo(); 
    demo.addComponentToPane(frame.getContentPane()); 

    //Display the window. 
    frame.pack(); 
    frame.setVisible(true); 
} 

public static void main(String[] args) { 
    /* Use an appropriate Look and Feel */ 
    try { 
     //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
     UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
    } catch (UnsupportedLookAndFeelException ex) { 
     ex.printStackTrace(); 
    } catch (IllegalAccessException ex) { 
     ex.printStackTrace(); 
    } catch (InstantiationException ex) { 
     ex.printStackTrace(); 
    } catch (ClassNotFoundException ex) { 
     ex.printStackTrace(); 
    } 
    /* Turn off metal's use of bold fonts */ 
    UIManager.put("swing.boldMetal", Boolean.FALSE); 

    //Schedule a job for the event dispatch thread: 
    //creating and showing this application's GUI. 
    javax.swing.SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGUI(); 
     } 
    }); 
} 
} 

這是我的NEWUSER類

import java.awt.Dimension; 
import java.awt.Toolkit; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 

import javax.swing.JButton; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JPasswordField; 
import javax.swing.JTextField; 

public class NewUser extends JPanel { 

private static final long serialVersionUID = 1L; 
private JLabel lblUsername, lblPassword, lblConfirmMsg; 
private JPasswordField txtPassword, txtCPassword; 
private JTextField txtUsername, txtName; 
private JButton btnSave, btnCancel; 
JPanel panelNewUser; 

Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); 

public NewUser() { 

    this.setSize(350, 270); 
    this.setLocation((screen.width - 500)/2, ((screen.height - 350)/2)); 
    this.setLayout(null); 
    panelNewUser= this; 
    lblUsername = new JLabel("Username"); 
    lblPassword = new JLabel("Password"); 
    lblConfirmMsg = new JLabel("Re-enter Password"); 
    txtName = new JTextField(); 

    txtUsername = new JTextField(); 
    txtPassword = new JPasswordField(); 
    txtCPassword = new JPasswordField(); 
    btnSave = new JButton("Save"); 
    btnCancel = new JButton("Cancel"); 

    lblUsername.setBounds(30, 30, 100, 25); 
    this.add(lblUsername); 
    txtUsername.setBounds(150, 30, 150, 25); 
    this.add(txtUsername); 
    lblPassword.setBounds(30, 70, 100, 25); 
    this.add(lblPassword); 
    txtPassword.setBounds(150, 70, 150, 25); 
    this.add(txtPassword); 
    lblConfirmMsg.setBounds(30, 110, 110, 25); 
    this.add(lblConfirmMsg); 
    txtCPassword.setBounds(150, 110, 150, 25); 
    this.add(txtCPassword); 
    btnSave.setBounds(60, 155, 100, 25); 
    this.add(btnSave); 
    btnCancel.setBounds(180, 155, 100, 25); 
    this.add(btnCancel); 

    txtName.addKeyListener(new KeyAdapter() { 

     public void keyTyped(KeyEvent e) { 
      char c = e.getKeyChar(); 
      if (!(Character.isLetter(c) || (c == KeyEvent.VK_BACK_SPACE) 
        || (c == KeyEvent.VK_SPACE) || (c == KeyEvent.VK_DELETE))) { 
       getToolkit().beep(); 
       JOptionPane.showMessageDialog(null, "Invalid Character", 
         "ERROR", JOptionPane.ERROR_MESSAGE); 
       e.consume(); 
      } 
     } 
    }); 
    txtUsername.addKeyListener(new KeyAdapter() { 

     public void keyTyped(KeyEvent e) { 
      char c = e.getKeyChar(); 
      if (!(Character.isLetter(c) || (c == KeyEvent.VK_BACK_SPACE) 
        || (Character.isDigit(c)) || (c == KeyEvent.VK_DELETE))) { 
       getToolkit().beep(); 
       JOptionPane.showMessageDialog(null, "Invalid Character", 
         "ERROR", JOptionPane.ERROR_MESSAGE); 
       e.consume(); 
      } 
     } 
    }); 
    btnCancel.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      resetField(); 
      panelNewUser.setVisible(false); 
     System.out.println("hello"); 
     } 
    }); 
    btnSave.addActionListener(new java.awt.event.ActionListener() { 


     public void actionPerformed(ActionEvent e) { 

      //DatabaseHelper databaseHelper = new DatabaseHelper(); 
      if (txtUsername.getText() == null 
        || txtUsername.getText().equals("")) { 
       JOptionPane.showMessageDialog(null, "Enter Username", 
         "Missing fields", JOptionPane.DEFAULT_OPTION); 
       txtUsername.requestFocus(); 
       return; 
      } 
      if (txtPassword.getPassword() == null 
        || txtPassword.getPassword().equals("")) { 
       JOptionPane.showMessageDialog(null, "Enter Password", 
         "Missing fields", JOptionPane.DEFAULT_OPTION); 
       txtPassword.requestFocus(); 
       return; 
      } 
      if (txtCPassword.getPassword() == null 
        || txtCPassword.getPassword().equals("")) { 
       JOptionPane.showMessageDialog(null, 
         "Confirm your password", "Missing fields", 
         JOptionPane.DEFAULT_OPTION); 
       txtCPassword.requestFocus(); 
       return; 
      } 
      if (!txtPassword.getText() 
        .equals(txtPassword.getText())) { 
       JOptionPane.showMessageDialog(null, 
         "Passwords do not match.", "ERROR", 
         JOptionPane.DEFAULT_OPTION); 
       txtCPassword.requestFocus(); 
       return; 
      } 


       if (true) { 
        JOptionPane.showMessageDialog(null, 
          "A new user is created", "SUCCESS", 
          JOptionPane.DEFAULT_OPTION); 
        resetField(); 
       } 


     } 
    }); 

    }// constructor closed 

//action listener 


public void resetField() 
{ 

    txtUsername.setText(""); 
    txtCPassword.setText(""); 
    txtPassword.setText(""); 
} 
}// class closed 

我想在中心位置顯示在主類NEWUSER的對象

+0

通過*「中心位置」 * DYM縮小到中央位置,或者居中但佔用所有可用空間? –

+0

設置將處於佈局管理器控制下的組件大小和位置是一個靜音點。佈局管理器將簡單地覆蓋它們,這就是佈局管理器的要點。最好在另一個使用類似'GridBagLayout'的面板中添加面板,但看起來已經適合取消子窗格的佈局管理器,那麼您也會遇到問題 – MadProgrammer

回答

6

歡迎圖形用戶界面設計,字體在該尺寸的wounderful世界中,SCR een分辨率和DPI,你開發你的頭腦吹噓真棒UI,將永遠不會匹配終端用戶...

現在,你有兩種選擇。花一輩子的時間試着去面對每一個奇怪的邊緣情況,在重新發明輪子的過程中,這個輪子已經在layout managers的幌子下提供給你了(對不起,如果聽起來虛構,但大多數人的通過理解佈局管理器可以解決Swing中的問題:P)。

你可能想通過Using Layout ManagersA Visual Guide to Layout Managers

enter image description here

public class TestLayout02 { 

    public static void main(String[] args) { 
     new TestLayout02(); 
    } 

    public TestLayout02() { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       /* Use an appropriate Look and Feel */ 
       try { 
        //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
       } catch (UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } catch (IllegalAccessException ex) { 
        ex.printStackTrace(); 
       } catch (InstantiationException ex) { 
        ex.printStackTrace(); 
       } catch (ClassNotFoundException ex) { 
        ex.printStackTrace(); 
       } 
       /* Turn off metal's use of bold fonts */ 
       UIManager.put("swing.boldMetal", Boolean.FALSE); 

       //Schedule a job for the event dispatch thread: 
       //creating and showing this application's GUI. 
       createAndShowGUI(); 
      } 
     }); 
    } 

    public class CardLayoutDemo implements ItemListener { 

     JPanel cards; //a panel that uses CardLayout 
     final static String BUTTONPANEL = "Card with JButtons"; 
     final static String TEXTPANEL = "Card with JTextField"; 

     public void addComponentToPane(Container pane) { 
      //Put the JComboBox in a JPanel to get a nicer look. 
      JPanel comboBoxPane = new JPanel(); //use FlowLayout 
      String comboBoxItems[] = {BUTTONPANEL, TEXTPANEL}; 
      JComboBox cb = new JComboBox(comboBoxItems); 
      cb.setEditable(false); 
      cb.addItemListener(this); 
      comboBoxPane.add(cb); 

      //Create the "cards". 
      NewUser newUser = new NewUser(); 

      JPanel card1 = new JPanel(); 
      card1.add(new JButton("Button 1")); 
      card1.add(new JButton("Button 2")); 
      card1.add(new JButton("Button 3")); 

      JPanel card2 = new NewUser(); 


      //Create the panel that contains the "cards". 
      cards = new JPanel(new CardLayout()); 
      cards.add(card1, BUTTONPANEL); 
      cards.add(card2, TEXTPANEL); 

      pane.add(comboBoxPane, BorderLayout.PAGE_START); 
      pane.add(cards, BorderLayout.CENTER); 
     } 

     public void itemStateChanged(ItemEvent evt) { 
      CardLayout cl = (CardLayout) (cards.getLayout()); 
      cl.show(cards, (String) evt.getItem()); 
     } 
    } 

    /** 
    * Create the GUI and show it. For thread safety, this method should be 
    * invoked from the event dispatch thread. 
    */ 
    protected void createAndShowGUI() { 
     //Create and set up the window. 
     JFrame frame = new JFrame("CardLayoutDemo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     //Create and set up the content pane. 
     CardLayoutDemo demo = new CardLayoutDemo(); 
     demo.addComponentToPane(frame.getContentPane()); 

     //Display the window. 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public class NewUser extends JPanel { 

     private static final long serialVersionUID = 1L; 
     private JLabel lblUsername, lblPassword, lblConfirmMsg; 
     private JPasswordField txtPassword, txtCPassword; 
     private JTextField txtUsername, txtName; 
     private JButton btnSave, btnCancel; 
     JPanel panelNewUser; 
     Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); 

     public NewUser() { 

//   this.setSize(350, 270); 
//   this.setLocation((screen.width - 500)/2, ((screen.height - 350)/2)); 
//   this.setLayout(null); 

      setLayout(new GridBagLayout()); 

      panelNewUser = this; 
      lblUsername = new JLabel("Username"); 
      lblPassword = new JLabel("Password"); 
      lblConfirmMsg = new JLabel("Re-enter Password"); 
      txtName = new JTextField(); 

      txtUsername = new JTextField(12); 
      txtPassword = new JPasswordField(12); 
      txtCPassword = new JPasswordField(12); 
      btnSave = new JButton("Save"); 
      btnCancel = new JButton("Cancel"); 

      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.gridx = 0; 
      gbc.gridy = 0; 
      gbc.insets = new Insets(2, 2, 2, 2); 
      gbc.anchor = GridBagConstraints.WEST; 

//   lblUsername.setBounds(30, 30, 100, 25); 
      this.add(lblUsername, gbc); 
//   txtUsername.setBounds(150, 30, 150, 25); 
      gbc.gridx++; 
      this.add(txtUsername, gbc); 
//   lblPassword.setBounds(30, 70, 100, 25); 
      gbc.gridx = 0; 
      gbc.gridy++; 
      this.add(lblPassword, gbc); 
//   txtPassword.setBounds(150, 70, 150, 25); 
      gbc.gridx++; 
      this.add(txtPassword, gbc); 
//   lblConfirmMsg.setBounds(30, 110, 110, 25); 
      gbc.gridx = 0; 
      gbc.gridy++; 
      this.add(lblConfirmMsg, gbc); 
//   txtCPassword.setBounds(150, 110, 150, 25); 
      gbc.gridx++; 
      this.add(txtCPassword, gbc); 
//   btnSave.setBounds(60, 155, 100, 25); 
      gbc.gridx = 0; 
      gbc.gridy++; 
      gbc.anchor = GridBagConstraints.CENTER; 
      this.add(btnSave, gbc); 
//   btnCancel.setBounds(180, 155, 100, 25); 
      gbc.gridx++; 
      this.add(btnCancel, gbc); 

      // This is a bad idea, use a DocumentFilter 
      txtName.addKeyListener(new KeyAdapter() { 
       public void keyTyped(KeyEvent e) { 
        char c = e.getKeyChar(); 
        if (!(Character.isLetter(c) || (c == KeyEvent.VK_BACK_SPACE) 
            || (c == KeyEvent.VK_SPACE) || (c == KeyEvent.VK_DELETE))) { 
         getToolkit().beep(); 
         JOptionPane.showMessageDialog(null, "Invalid Character", 
             "ERROR", JOptionPane.ERROR_MESSAGE); 
         e.consume(); 
        } 
       } 
      }); 
      // This is a bad idea, use a DocumentFilter 
      txtUsername.addKeyListener(new KeyAdapter() { 
       public void keyTyped(KeyEvent e) { 
        char c = e.getKeyChar(); 
        if (!(Character.isLetter(c) || (c == KeyEvent.VK_BACK_SPACE) 
            || (Character.isDigit(c)) || (c == KeyEvent.VK_DELETE))) { 
         getToolkit().beep(); 
         JOptionPane.showMessageDialog(null, "Invalid Character", 
             "ERROR", JOptionPane.ERROR_MESSAGE); 
         e.consume(); 
        } 
       } 
      }); 
      btnCancel.addActionListener(new java.awt.event.ActionListener() { 
       public void actionPerformed(ActionEvent e) { 
        resetField(); 
        panelNewUser.setVisible(false); 
        System.out.println("hello"); 
       } 
      }); 
      btnSave.addActionListener(new java.awt.event.ActionListener() { 
       public void actionPerformed(ActionEvent e) { 

        //DatabaseHelper databaseHelper = new DatabaseHelper(); 
        if (txtUsername.getText() == null 
            || txtUsername.getText().equals("")) { 
         JOptionPane.showMessageDialog(null, "Enter Username", 
             "Missing fields", JOptionPane.DEFAULT_OPTION); 
         txtUsername.requestFocus(); 
         return; 
        } 
        if (txtPassword.getPassword() == null 
            || txtPassword.getPassword().equals("")) { 
         JOptionPane.showMessageDialog(null, "Enter Password", 
             "Missing fields", JOptionPane.DEFAULT_OPTION); 
         txtPassword.requestFocus(); 
         return; 
        } 
        if (txtCPassword.getPassword() == null 
            || txtCPassword.getPassword().equals("")) { 
         JOptionPane.showMessageDialog(null, 
             "Confirm your password", "Missing fields", 
             JOptionPane.DEFAULT_OPTION); 
         txtCPassword.requestFocus(); 
         return; 
        } 
        if (!txtPassword.getText() 
            .equals(txtPassword.getText())) { 
         JOptionPane.showMessageDialog(null, 
             "Passwords do not match.", "ERROR", 
             JOptionPane.DEFAULT_OPTION); 
         txtCPassword.requestFocus(); 
         return; 
        } 


        if (true) { 
         JOptionPane.showMessageDialog(null, 
             "A new user is created", "SUCCESS", 
             JOptionPane.DEFAULT_OPTION); 
         resetField(); 
        } 


       } 
      }); 

     }// constructor closed 

//action listener 
     public void resetField() { 

      txtUsername.setText(""); 
      txtCPassword.setText(""); 
      txtPassword.setText(""); 
     } 
    }// class closed 
} 

您可能還喜歡有通過DocumentFilter讀有讀。

如果您希望手動執行此操作,則需要附加一個ComponentListener並監控componentResized事件並再次重新佈置所有組件。

您也想看看FontMetrics這樣你就可以正確地考慮到系統的字體大小的差異...

+0

@mkorbel +1 ,被其他所有人蒙上陰影 – MadProgrammer

+0

+1描述,圖像 – mKorbel