【发布时间】:2016-11-19 08:10:45
【问题描述】:
public class Create_JFrame extends JFrame{
public Create_JFrame(){
//Create a Frame
JFrame Frame = new JFrame("Bla-Bla");
JPanel Panel_1 = new JPanel();
JPanel Panel_2 = new JPanel();
JButton Option_1 = new JButton("Option-1");
//Layout management for Panels
Frame.getContentPane().add(BorderLayout.WEST, Panel_1);
//Add button to Panel
Panel_1.add(Option_1);
//Registering Listeners for all my buttons
Option_1.addActionListener(new ListenerForRadioButton(Panel_2));
//Make the frame visible
Frame.setSize(500, 300);
Frame.setVisible(true);
}//end of Main
}//end of Class
public class ListenerForRadioButton implements ActionListener{
JPanel Panel_2;
JButton browse = new JButton("Browse");
//Constructor, will be used to get parameters from Parent methods
public ListenerForRadioButton(JPanel Panel){
Panel_2 = Panel;
}
//Overridden function, will be used for calling my 'core code' when user clicks on button.
public void actionPerformed(ActionEvent event){
Panel_2.add(browse);
System.out.println("My listener is called");
}//end of method
}//end of class
问题陈述:
我在给定的JFrame 中有 2 个JPanel 组件。 Panel_1 有一个 Option_1 JButton。当用户点击它时,我希望我的代码在运行时在Panel_2 中添加JButton“浏览”。
运行时输出:
系统没有在Panel_2 中添加任何JButton。但是,我在输出中看到我的调试消息,表明系统已成功识别用户对“option-1”的点击操作。
问题:
为什么JPanel 没有在运行时添加任何组件?
【问题讨论】:
-
" 在运行时在 JPanel-2 中添加一个 Jbutton 'browse'。" 1) 使用
CardLayout,如this answer 所示。该按钮应在启动时添加到其中一张卡,但用户会看到没有组件的第二张卡。应用程序的任何条件。将添加按钮,更改卡片以显示已添加的按钮。 2) 为了尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。 -
.. 3) 请学习常见的 Java 命名法(命名约定 - 例如
EachWordUpperCaseClass、firstWordLowerCaseMethod()、firstWordLowerCaseAttribute,除非它是UPPER_CASE_CONSTANT)并始终如一地使用它。 -
谢谢安德鲁!你能告诉我为什么现有代码不起作用。我将 Jpanel 的引用传递给我的 actionPerfored 方法,我也应该被允许从那里添加一个 Jbutton。
标签: java swing jpanel awt jbutton