栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在主窗口中切换JPanel

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在主窗口中切换JPanel

更好的方法是转向CardLayout。但是如果您想坚持自己的方法,请尝试在行后添加

if (c != null) { contentPane.remove(c);        }        c = new AddBookInterface(theLibrary);        contentPane.add(c);        contentPane.revalidate();        contentPane.repaint();         frame.validate();        frame.repaint();        break;

否则您可能忘记了为事件调度程序线程安排作业。一个示例程序可以帮助您实现目标:

import java.awt.event.*;import javax.swing.*;public class TwoPanelTest implements ActionListener{    private Jframe frame;    private JPanel panel1;    private JPanel panel2;    private JButton button1;    private JButton button2;    private JLabel label1;    private JLabel label2;    private JTextField tfield1;    private JTextField tfield2;    public TwoPanelTest()    {        frame = new Jframe();        frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);        panel1 = new JPanel();        panel2 = new JPanel();        label1 = new JLabel("This is Label 1");        label2 = new JLabel("This is Label 2");        button1 = new JButton("BUTTON 1");        button2 = new JButton("BUTTON 2");        button1.addActionListener(this);        button2.addActionListener(this);        tfield1 = new JTextField(20);        tfield2 = new JTextField(20);        panel1.add(label1);        panel1.add(button1);        panel1.add(tfield1);        panel2.add(label2);        panel2.add(button2);        panel2.add(tfield2);        tfield1.setText("MY TEXT WILL CHANGE.");        frame.setContentPane(panel1);        frame.pack();        frame.setVisible(true);    }    public void actionPerformed(ActionEvent ae)    {        JButton button = (JButton)ae.getSource();        if (button == button1)        { frame.remove(panel1); frame.setContentPane(panel2); tfield2.setText("TEXTFIELD 2"); frame.validate(); frame.repaint();        }        else if (button == button2)        { frame.remove(panel2); frame.setContentPane(panel1); tfield1.setText("TEXTFIELD 1"); frame.validate(); frame.repaint();        }    }    public static void main(String[] args)    {     // Here Event Dispatcher thread is responsible for      // calling the function which creates and displays your GUI     // or it itself contains the pre for creating and displaying     // the GUI, to remove hickups experienced while updating the      // GUI on the run.        SwingUtilities.invokeLater(new Runnable() {     public void run()     {         new TwoPanelTest();     } });    }}

希望这会有所帮助。

问候。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/431087.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号