簡體   English   中英

如何在此示例中已存在的新jpanel上添加?

[英]How can I add new jpanel on already existing in this example?

愚蠢的問題,但我似乎找不到答案,而且當我這樣做時不起作用。 所以我想在已經存在的JPanel上添加新的JPanel。 有時,當我添加它時,它會在我運行它時打開一個新窗口,有時則什么也沒有發生。 無論如何,這里是代碼:

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); 


}
}

我想在這個地方添加新的JPanel:自動售貨機:

https://i.stack.imgur.com/nkrpp.png

謝謝!

即使您可以這樣做,每次您想對此框架進行其他更改時,也會給您帶來傷害。

代替使用一個JPanel放置到另一個JPanel中,而使用布局。

您不應該使用靜態變量和null布局。

使用適當的布局管理器。 也許主面板使用BorderLayout。 然后,將主要組件添加到CENTER,將第二個面板添加到EAST。 第二個面板也可以使用BorderLayout。 然后,您可以根據需要將這兩個組件添加到NORTH,CENTER或SOUTH中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM