0

我正在使用 Swing 在 Java 中构建 GUI。制作按钮并添加它的代码如下:

    //Create a button
    JButton exitButton = new JButton("Exit");
    exitButton.setSize(90, 40);
    exitButton.setLocation(800, 450);
    exitButton.setVisible(true);

    //Adding components
    window.getContentPane().add(exitButton);

当我运行该应用程序时,该按钮出现在整个窗口中,有时会按预期显示,有时不会出现。这是某种 java 错误还是我的sdk. 如果您想知道它是什么类型的窗口,

//Create a window
JFrame window = new JFrame("First Window");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
window.setVisible(true);
window.setSize(1000, 550);
window.setLocation(150, 150);

这一切都在 static void main 之内。顺便说一句,我如何获得关闭窗口的按钮System.exit(0);(我是初学者,这是我的第一个自写 GUI)

4

3 回答 3

1

你需要一个布局。请参阅布局管理器的视觉指南

也请在这里查看我的教程。

于 2013-04-04T13:42:27.330 回答
0

我得到了这个示例代码。这可能会有所帮助 简单的摆动按钮

package com.ack.gui.swing.simple;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

public class SimpleSwingButtons extends JFrame {
  public static void main( String[] argv ) {
    SimpleSwingButtons myExample = new SimpleSwingButtons( "Simple Swing Buttons" );
  }

  public SimpleSwingButtons( String title ) {
    super( title );
    setSize( 150, 150 );
    addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent we ) {
        dispose();
        System.exit( 0 );
      }
    } );
    init();
    setVisible( true );
  }

  private void init() {
    JPanel my_panel = new JPanel();
    my_panel.setLayout( new GridLayout( 3, 3 ) );
    for( int i = 1; i < 10; i++ ) {
      ImageIcon icon = new ImageIcon( i + ".gif" );
      JButton jb = new JButton( icon );
      jb.setToolTipText( i + ".gif" );
      my_panel.add( jb );
    }
    getContentPane().add( my_panel );
    my_panel.setBorder( BorderFactory.createEtchedBorder() );
  }
}

礼貌的 Java.happycodings

于 2013-04-04T13:44:34.113 回答
-2

您必须检查您的布局,如果您想为组件使用自定义位置,请将 Layout 设置为 null 并使用该setBounds(x,y,weight,height)方法。

JFrame window = new JFrame("First Window");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
window.setLayout(null);

JButton exitButton = new JButton("Exit");
exitButton.setBounds(15,45,150,30);//This is just an example
exitButton.setVisible(true);

最好的祝福。

于 2013-04-04T13:44:09.057 回答