【问题标题】:Java components from different class来自不同类的 Java 组件
【发布时间】:2026-01-09 03:20:03
【问题描述】:

我正在尝试从我的程序中的不同类创建组件并将它们实现到我的 JFrame 中。

我创建了一个 JTabbedPane,每个选项卡代表一个类。每个选项卡的所有组件都放置在它们各自的选项卡中。

//creates the JTabbedPane, and the panels. object creation.
//panelx corisponds to the tab number as well. tabbs are counted from left to right. 
tabpane1 = new JTabbedPane();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();

JLabel searchlabel1 = new JLabel("hey");
JLabel searchlabel2 = new JLabel("hi");

panel1.add(searchlabel1);
panel1.add(searchlabel2); 

//SearchFlight searchflightComp = new SearchFlight();

 tabpane1.addTab("Search Flight", panel1);
 tabpane1.addTab("Select Flight", panel2);
 tabpane1.addTab("Flight Price", new JLabel("This is tab 1ffff")); 
 tabpane1.addTab("Book Ticket", new JLabel("This is tab 1fff"));
 tabpane1.addTab("Book Ticket", new JLabel("This is tab fs1"));
 tabpane1.addTab("Payment", new JLabel("This is tabgf 1"));
 tabpane1.addTab("Booking Summary", new JLabel("This is tabgf 1"));
 //added the JTabbedPane to JFrame. 
 frame.getContentPane().add(tabpane1);

这行得通。我现在只真正使用第一个选项卡来了解它的工作原理等。但我什至不知道如何开始。我会在另一个类中创建一个面板然后返回它吗?或扩展JFrame?

谢谢大家!

【问题讨论】:

  • 不清楚你在问什么,你想只使用 one 包含所有组件的标签吗?
  • 如果您不需要其他选项卡,为什么不简单地将最后一行更改为frame.getContentPane().add(panel1);

标签: java user-interface components


【解决方案1】:

也许你可以从 JComponent 扩展?并像他们here那样做吗?

【讨论】:

    【解决方案2】:

    我假设你指的是这个注释行:

    //SearchFlight searchflightComp = new SearchFlight();
    

    您可以使 SearchFlight 成为 JPanel 的子类,或者更好地创建一个控制器,为该选项卡创建一个 JPanel 并返回它,例如

    SearchFlight searchflightComp = new SearchFlight();
    tabpane1.addTab( searchflightComp.getName(), searchflightComp.buildPanel() );
    

    作为一般提示,您应该阅读 MVC 模式。 这可能会在一定程度上帮助您:The MVC pattern and SWING

    【讨论】:

      最近更新 更多