我目前正在构建一个GUI,可以让人们选择购买/出售(基本上是发送/接收)。我想要实现的是让用户点击买入/卖出,当他们点击该按钮时,它会显示新信息。
例如。用户点击购买,它会将它们带到一个带有新标签新按钮等的新面板。我不想要一个新窗口,但要更换当前窗口。
public class GuiTest {
private JButton btnpurchase;
private JPanel panelMain;
private JButton btnrefund;
public GuiTest() {
btnpurchase.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null,"Buying stuff.");
purchasecontent();
}
});
btnrefund.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null,"Refunding stuff.");
refundcontent();
}
});
}
public static void purchasecontent(){
//enter the amount of the purchase
}
public static void refundcontent(){
}
public static void main(String[] args){
JFrame frame = new JFrame("GuiTest");
frame.setContentPane(new GuiTest().panelMain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(480,320);
frame.setVisible(true);
}
}
正如您在purchasecontent()函数中看到的那样,我试图让它在同一个窗口中执行。
我目前正在使用IntelliJ IDE并正在使用表单设计器。
答案 0 :(得分:0)
首先,你必须避免从你的监听器调用静态方法:)这是一个不好的做法。
为了轻松实现,GuiTest必须继承JPanel,将其视为主要面板。
要替换内容,请使用以下方式获取框架:
JFrame frame = (JFrame) SwingUtilities.getRoot(component);
并设置新内容,例如:
btnrefund.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
JFrame frame = (JFrame) SwingUtilities.getRoot(component);
frame.setContentPane(new RefundPanel());
}
});
RefundPanel应该是您想要在框架中设置的面板......