这是我的 JPanel. 。第一个按钮始终可见,但第二个按钮仅当您将光标放在其上时才可见。问题可能出在哪里?

附:如果可以的话,请使用简单的英语,因为我英语说得不好

public class GamePanel extends JPanel implements KeyListener{


GamePanel(){
    setLayout(null);
}

public void paint(Graphics g){

    JButton buttonShip1 = new JButton();
    buttonShip1.setLocation(10, 45);
    buttonShip1.setSize(40, 40);
    buttonShip1.setVisible(true);
    add(buttonShip1);

    JButton buttonShip2 = new JButton();
    buttonShip2.setLocation(110, 145);
    buttonShip2.setSize(440, 440);
    buttonShip2.setVisible(true);
    add(buttonShip2);
    }
}
有帮助吗?

解决方案

如果你想避免问题并正确学习 Java Swing,请查看他们的教程 这里.

这里要讨论的问题太多了,所以我会尽量保持简单。

  1. 您正在使用一个 null 布局。 null 大多数情况下会避免使用布局,因为通常有一种布局可以完全满足您的需求。需要一些时间才能使其正常工作,但有一些默认值 在本教程中 使用起来相当简单。那里还有一些漂亮的图片,向您展示了每种布局的用途。如果使用布局管理器,一般不需要使用 setLocation, setSize 或者 setVisible 在大多数组件(如 JButton)上。

  2. 您正在呼叫 paint Swing 应用程序中的方法。你想打电话 paintComponent 因为您使用的是 Swing 而不是 Awt。您还需要致电 super.paintComponent(g) 第一行的方法 paintComponent 方法以便正确覆盖其他方法 paintComponent 方法。

  3. paint/paintComponent 相关方法被频繁调用。您不想在其中创建/初始化对象。这 paint/paintComponent 方法并不像听起来那样是一次性方法。它们被不断地调用,你应该围绕它来设计你的 GUI。设计你的 paint- 相关方法 事件驱动 而不是 顺序的. 。换句话说, 编程 paintComponent 方法的思维方式是你的 GUI 不断地对事物做出反应,而不是像普通程序那样按顺序运行。 这是一个非常基本的方法,希望不会让您感到困惑,但是如果您查看该教程,您最终会明白我的意思。

Java 中有两种基本类型的 GUI。一是 Swing 另一个是 Awt. 。查看 stackoverflow 上的这个答案 对于两者的很好描述。

下面是 JPanel 上两个按钮的示例。

public class Test 
{
    public static void main(String[] args) 
    {
        JFrame jframe = new JFrame();
        GamePanel gp = new GamePanel();

        jframe.setContentPane(gp);
        jframe.setVisible(true);
        jframe.setSize(500,500);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }


    public static class GamePanel extends JPanel{

    GamePanel() {
        JButton buttonShip1 = new JButton("Button number 1");
        JButton buttonShip2 = new JButton("Button number 2");
        add(buttonShip1);
        add(buttonShip2);

        //setLayout(null);
        //if you don't use a layout manager and don't set it to null
        //it will automatically set it to a FlowLayout.
    }

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

        // ... add stuff here later
            // when you've read more about Swing and
            // painting in Swing applications

        }
    }

}

其他提示

  1. Don't use a null layout
  2. Don't create components in a painting method. The paint() method is for custom painting only. There is no need for you to override the paint() method.

Read the section from the Swing tutorial How to Use FlowLayout for a simple example that uses buttons and a layout manager.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top