[英]How can I add new jpanel on already existing in this example?
Stupid question, but I cant seem to find answer, and when I do it doesn't work. 愚蠢的问题,但我似乎找不到答案,而且当我这样做时不起作用。 So i want to add new JPanel on already existing JPanel.
所以我想在已经存在的JPanel上添加新的JPanel。 Sometimes when i add it it just opens a new window when I run it, other times nothing happens.
有时,当我添加它时,它会在我运行它时打开一个新窗口,有时则什么也没有发生。 Anyways here is the code:
无论如何,这里是代码:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args)
{
new Main().setVisible(true);
}
private Main()
{
super("Vending machine");
JPanel p = new JPanel();
JLabel title = new JLabel("Vending machine: ");
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("5");
JLabel label1 = new JLabel("Enter code: ");
JTextField text1= new JTextField(3);
JButton ok= new JButton("OK");
JButton button4 = new JButton("Return change");
JLabel label2 = new JLabel("Result is: ");
JTextField text2= new JTextField(3);
JLabel label3 = new JLabel("Current: ");
JTextField text3= new JTextField(3);
title.setBounds(200,5,250,80);
title.setFont (title.getFont ().deriveFont (22.0f));
p.add(title);
p.setLayout(null);
button1.setBounds(530,46,120,60);
p.add(button1);
button2.setBounds(530,172,120,60);
p.add(button2);
button3.setBounds(530,298,120,60);
p.add(button3);
label1.setBounds(555,414,120,60);
p.add(label1);
text1.setBounds(530,454,120,30);
p.add(text1);
ok.setBounds(530,550,120,60);
p.add(ok);
button4.setBounds(360,550,120,60);
p.add(button4);
label2.setBounds(230,530,120,60);
p.add(label2);
text2.setBounds(200,575,120,30);
p.add(text2);
label3.setBounds(50,530,120,60);
p.add(label3);
text3.setBounds(38,575,120,30);
p.add(text3);
getContentPane().add(p);
setSize(700,700);
setVisible(true);
}
}
I want to add new JPanel on this place: vending machine: 我想在这个地方添加新的JPanel:自动售货机:
Thank you! 谢谢!
Even if you could do this, it will give you harm for every time you want another changes on this frame. 即使您可以这样做,每次您想对此框架进行其他更改时,也会给您带来伤害。
Instead of locating a JPanel into another JPanel, use layouts. 代替使用一个JPanel放置到另一个JPanel中,而使用布局。
You shouldnt use static variables and a null layout. 您不应该使用静态变量和null布局。
Use appropriate layout managers. 使用适当的布局管理器。 Maybe the main panel uses a BorderLayout.
也许主面板使用BorderLayout。 Then you add your main component to the CENTER and a second panel to the EAST.
然后,将主要组件添加到CENTER,将第二个面板添加到EAST。 The second panel can also use a BorderLayout.
第二个面板也可以使用BorderLayout。 You can then add the two components to the NORTH, CENTER or SOUTH as you require.
然后,您可以根据需要将这两个组件添加到NORTH,CENTER或SOUTH中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.