2015-11-03 167 views
0

我有一个启动窗口,它使用下拉框,两个文本框和一个OK按钮创建一个jframe。选择下拉菜单项并输入两个文本框后,将调用另一个函数,它将用其他内容替换JFrame的内容。使用新项目替换Jframe的内容返回空白Jframe

一个下拉选择的是存款:

public void deposit(String customerID, String customerPIN) { 
    Customer customer = validate_info(customerID, customerPIN); 
    if (!found){ 
     if (pin == null) { 
      jf.notInDatabase(); 
     } else { 
      jf.invalidAccount(); // if the customer has not been found but the pin has been set that means the pin was invalid 
     } 
    } else { 
     if (customer != null) { 
      String result = customer.returnInfo(); 
      jf.depositScreen(result); 

上SO指导四处寻找后,这是我到目前为止有:

public void depositScreen(String phrase) { 
    getContentPane().removeAll(); 

    JLabel customerInfo = new JLabel(phrase); 
    customerInfo.setFont(new Font("Futura", Font.PLAIN, 12)); 
    getContentPane().add(customerInfo); 

    JTextField depositAmount = new JTextField("Please enter the amount you would like to deposit in 00.00 format"); 
    depositAmount.setFont(new Font("Futura", Font.PLAIN, 12)); 
    getContentPane().add(depositAmount); 

    repaint(); 
    validate(); 
    setVisible(true); 
} 

到目前为止,它的转向了没有标签的空白灰色框。我哪里错了?

+0

您不必再次设置可见性。验证应该重新绘制之前。您应该使您的内容窗格无效。你的内容窗格还有什么布局? – matt

+0

使用'revalidate'或'invalidate'后面跟着'validate','repaint'应该最后调用。不需要使用'setVisible'。更好的解决方案可能是使用'CardLayout' – MadProgrammer

+0

检查您使用的布局。另外,请尝试将“JPanel”设置为“contentPane”,并将您的组件添加到此面板。这将有所帮助。 –

回答

1

下面是一个做你想做的例子。注意验证和无效的顺序。

import javax.swing.*; 
import java.awt.*; 
public class SwingSwap{ 
    public static void main(String[] args){ 
     EventQueue.invokeLater(()->buildGui()); 
    } 
    public static void buildGui(){ 
     JFrame frame = new JFrame("swapping"); 
     final JButton a = new JButton("->B"); 
     final JLabel aLabel = new JLabel("A"); 

     final JButton b = new JButton("->A"); 
     final JLabel bLabel = new JLabel("B"); 

     a.addActionListener(evt->{ 
      EventQueue.invokeLater(()->{ 
       Container cont = frame.getContentPane(); 
       cont.removeAll(); 
       cont.add(b); 
       cont.add(bLabel); 
       cont.invalidate(); 
       frame.validate(); 
       frame.repaint(); 
      }); 
     }); 

     b.addActionListener(evt->{ 
      EventQueue.invokeLater(()->{ 
       Container cont = frame.getContentPane(); 
       cont.removeAll(); 
       cont.add(a); 
       cont.add(aLabel); 
       cont.invalidate(); 
       frame.validate(); 
       frame.repaint(); 
      }); 
     }); 

     Container cont = frame.getContentPane(); 
     cont.setLayout(new BoxLayout(cont, BoxLayout.PAGE_AXIS)); 
     cont.add(a); 
     cont.add(aLabel); 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setVisible(true);  
    } 
} 
+0

仍然无法使用;显示一个空的灰色框。如果它有帮助,我正在使用网格布局,并且此函数未附加到ActionListener。 – Drivebyluna

+0

@Drivebyluna你编译了我提供的例子吗? – matt

+0

是的,它编译。我将添加一个编辑来显示我的重绘如何被调用。 – Drivebyluna