ddd*_*dkk 1 java swing jpanel jbutton null-layout-manager
这是我的JPanel.第一个按钮始终可见,但仅当您在其上放置一个光标时,才能看到该条纹.问题出在哪里?
PS如果可以,请使用简单的英语,因为我不会说英语
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);
}
}
Run Code Online (Sandbox Code Playgroud)
阅读Swing教程如何使用FlowLayout中的部分,以获取使用按钮和布局管理器的简单示例.
如果你想避免问题并正确学习Java Swing,请在这里查看他们的教程.
这里讨论的问题太多了,所以我会尽量保持简单.
你正在使用null布局.null大多数情况下都避免使用布局,因为通常会有一个布局完全符合您的要求.它需要一些时间才能正常工作,但本教程中有一些默认值非常简单易用.那里有一些漂亮的图片,向您展示您可以对每个布局做些什么.如果您使用的布局管理器,你一般不需要使用setLocation, setSize或setVisible像Jbutton将大部分部件.
您正在paintSwing应用程序中调用该方法.你想打电话paintComponent是因为你使用的是Swing而不是Awt.您还需要在super.paintComponent(g)方法的第一行调用paintComponent方法,以便正确覆盖其他paintComponent方法.
该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
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1112 次 |
| 最近记录: |