简体   繁体   English

在JFrame上调用JPanel

[英]Calling a JPanel onto a JFrame

I'm having troubles calling a JPanel I made into a JFrame. 我在调用我制作为JFrame的JPanel时遇到麻烦。

The JPanel is called "SubnetPanel" ==> JPanel称为“ SubnetPanel” ==>

SubnetPanel panel = new SubnetPanel(String a, String b, String c);

In my JFrame, I made a button. 在我的JFrame中,我做了一个按钮。

private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    String a = JOptionPane.showInputDialog(null, "Geef de naam in : ", 
    "Naam", 1);
    String b = JOptionPane.showInputDialog(null, "Geef het netwerkadres in : ", 
    "Netwerkadres", 1);
    String c = JOptionPane.showInputDialog(null, "Geef het subnetmask in : ", 
    "Subnetmask", 1);

    this.add(new SubnetPanel(a,b,c) {
             @Override
             public void paintComponent( Graphics g ) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;

                Line2D line = new Line2D.Double(10, 10, 40, 40);
                g2.setColor(Color.blue);
                g2.setStroke(new BasicStroke(10));
                g2.draw(line);
             }
        });
        this.setVisible( true );

} 

But when I execute my JFrame and click the button, the JFrame does not appear. 但是,当我执行JFrame并单击按钮时,JFrame不会出现。 Can anyone help me with this? 谁能帮我这个?

Thanks! 谢谢!

The basic code for adding (or removing) a component from a visible frame is: 从可见框中添加(或删除)组件的基本代码是:

panel.add(...);
panel.revalidate();
panel.repaint();

In your case the "panel" would be the content pane of your JFrame. 在您的情况下,“面板”将是JFrame的内容面板。

Also, when you do custom painting, you also need to override the getPreferredSize() method of the panel, so the layout manager can use this information to set the size/location of the panel. 另外,在进行自定义绘画时,还需要覆盖面板的getPreferredSize()方法,因此布局管理器可以使用此信息来设置面板的大小/位置。

Although you've added the panel to the frame, it will initially be located at (0,0) with a size of 0×0, so you won't be able to see it. 尽管已将面板添加到框架,但面板最初将位于(0,0),大小为0×0,因此您将无法看到它。 You'll need to size and position it, such as by calling pack() on the frame. 您需要调整大小和位置,例如通过在框架上调用pack()

May be you forget to add the ActionListner on the JButton . 可能是您忘记在JButton上添加ActionListner了。

Try in this way 尝试这种方式

    JButton jButton = new JButton("Click"); // Your actual button is here
    jButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {                
            jButtonActionPerformed(e);
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM