How to add a JButton Button to the view

starter45 :

This is a minimalist example of my problem so, please do not tell me that the class is useless and that I can do it with only a JPannel in my main class. Thanks.

How do I add a JButton with text in the EcranAcceuil class below?

import java.awt.*;
import javax.swing.*;

public class jeu {
    public static void main(String[] args) {    
        // debut definition fenetre    
        JFrame fenetrejeu = new JFrame();    
        fenetrejeu.setTitle("QUEST");
        fenetrejeu.setSize(1000, 1000);
        fenetrejeu.setLocationRelativeTo(null);
        fenetrejeu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fenetrejeu.setContentPane(new EcranAcceuil());
        fenetrejeu.setVisible(true);
    }
}

EcranAcceuil

import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class EcranAcceuil extends JPanel {
    public void paintComponent(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
    }
}
Arvind Kumar Avinash :

Do it as follows:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

class EcranAcceuil extends JPanel implements ActionListener {
    JButton btnHello;
    JTextField txtHello;

    EcranAcceuil() {
        btnHello = new JButton("Hello");
        btnHello.addActionListener(this);
        txtHello = new JTextField(20);
        add(txtHello);
        add(btnHello);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        txtHello.setText("Hello");
    }
}

public class jeu {
    public static void main(String[] args) {
        // debut definition fenetre
        JFrame fenetrejeu = new JFrame();
        fenetrejeu.setTitle("QUEST");
        fenetrejeu.setSize(1000, 1000);
        fenetrejeu.setLocationRelativeTo(null);
        fenetrejeu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fenetrejeu.setContentPane(new EcranAcceuil());
        fenetrejeu.setVisible(true);
    }
}

I also recommend you follow Java naming convention e.g. class jeu should be class Jeu.

Feel free to comment in case of any issue/doubt.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=335292&siteId=1