繁体   English   中英

为什么我的JButton根本不显示但仍然可以工作? (我知道它在哪里,所以我可以单击它)

[英]Why does my JButton not show up at all but still work? (I know where it is so I can click it)

在此JPanel中,我的JButton“ BackToTheMenu”位于面板的顶部,我知道它在哪里,因此可以单击它,但看不到它。 当我单击它时,它将带我到下一个面板。 我如何显示它? 非常感谢您的帮助!

public class GridPanel extends JPanel implements ActionListener
{
    Ball ball = new Ball();
    Timer timer = new Timer(14, this);

    JButton backToTheMenu = new JButton("To the Menu");

    public GridPanel()
    {
        setBackground(Color.WHITE);
        setPreferredSize(new Dimension(900, 710));
        add(ball);

        backToTheMenu.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {       
                ProjectileGame.gridButtonPressed();
            }
        });
    }

    public void paintComponent(Graphics g)
    {   
        super.paintComponent(g);

        g.setColor(Color.RED);
        g.fillRect(0,  649,  30,  33);

        g.setColor(Color.BLUE);

        for (int i = 0; i < 35; i++)
        {
            g.setColor(Color.GREEN);
            g.drawLine(0, (20+(30*i)),  900,  (20+(30*i)));
            g.drawLine((30+(30*i)), 0, (30+(30*i)), 1000);
        }

        ball.paintComponent(g);

        g.setColor(Color.RED);
        g.drawLine(0, 650, 900, 650);
        g.drawLine(30, 0, 30, 1000);

        Graphics2D g2d1 = (Graphics2D)g;

        g.setColor(Color.BLACK);
        g2d1.drawString("X Displacement (metres)", 400, 667);
        AffineTransform at = new AffineTransform();
        at.setToRotation(Math.PI / -1.97);
        g2d1.setTransform(at);
        g2d1.drawString("Y Displacement (metres)", -380, 8);    

        setOpaque(false);

        for (Component child : getComponents()) 
        {
            child.repaint();
        }

    }                  

    public void actionPerformed(ActionEvent e)
    {
        ball.ballPhysics();
        repaint();
        timer.restart();
    }
}

您的许多代码不正确。

绘画方法仅用于绘画。 你不应该:

  1. 调用ball.paintComponent()。 面板将自动绘制添加到其中的任何组件。

  2. 获取子组件并在其上调用repaint()。 同样,面板将绘制所有子组件。

  3. 调用setOpaque(...) opaque属性应在类的构造函数中设置。

不应在此类中定义“返回菜单”按钮。 它应该在父类中定义。

因此,代码应类似于:

JButton back = new JButton("Back to the Menu");
back.addActionListener(...);
frame.add(back, BorderLayout.PAGE_START);
JPanel grid = new GridPanel();
frame.add(grid, BorderLayout.CENTER);

我不确定代码中是否有其他代码,但看不到您添加backToTheMenu。 如果这是您的代码:

public GridPanel()
{
    setBackground(Color.WHITE);
    setPreferredSize(new Dimension(900, 710));
    add(ball);

    backToTheMenu.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent arg0)
        {       
            ProjectileGame.gridButtonPressed();
        }
    });
}

你需要这个:

add(backToTheMenu);

但是,如果您将其添加到其他位置,则无需理会。

暂无
暂无

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

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