2015-07-06 3 views
0

Я пытаюсь добавить кнопку в рамку gui.
Я попытался сделать панель и добавить ее к ней, но она не работает. , пожалуйста, помогите!Как добавить кнопку в JFrame Gui

вот мой код:

import javax.swing.*; 

public class Agui extends JFrame { 
    public Agui() { 
     setTitle("My Gui"); 
     setSize(400, 400); 
     setVisible(true); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 

     JButton button; 
     JPanel panel; 

     // my error lines are under the "panel" and "button" 
     // it says i must implement the variables. what does that mean??? 
     panel.add(button); 
    } 
    public static void main(String[] args) { 
     Agui a = new Agui(); 
    } 
} 
+1

вы должны инициализировать его –

+3

Вы отсутствуете 'Кнопка JButton = новый JButton («click me»); 'и' JPanel panel = new JPanel(); ' –

ответ

1

Пример кода:

import javax.swing.*; 

public class Agui extends JFrame { 

    public Agui() { 

     setTitle("My Gui"); 
     setSize(400, 400); 

     // Create JButton and JPanel 
     JButton button = new JButton("Click here!"); 
     JPanel panel = new JPanel(); 

     // Add button to JPanel 
     panel.add(button); 
     // And JPanel needs to be added to the JFrame itself! 
     this.getContentPane().add(panel); 

     setVisible(true); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 

    public static void main(String[] args) { 

     Agui a = new Agui(); 
    } 
} 

Выход:

Image

Примечание:

  • Создайте JButton и JPanel с помощью new JButton("..."); и new JPanel()
  • Добавьте JPanel в панель контента JFrame, используя getContentPane().add(...);
+0

спасибо! это работает! –

4

Изменение:

JButton button; 
JPanel panel; 

к:

JButton button = new JButton(); 
JPanel panel = new JPanel(); 

Вы также можете передать значение String в JButton() конструктор для этого значение строки показанном на JButton.

Пример:JButton button = new JButton("I am a JButton");

Смежные вопросы