[[oktatas:programozás:java:java_komponensek|< Java komponensek]]
====== Java komponensek - Swing buttonpanel ======
* **Szerző:** Sallai András
* Copyright (c) 2023, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]]
* Web: https://szit.hu
===== Bevezetés =====
Java komponensek készítése.
===== Könyvtárszerkezet =====
app01/
|-lib/
|-src/
| |-controllers/
| | `-MainController.java
| |-models/
| |-views/
| | |-ButtonPanel.java
| | `-Mainwindow.java
| `-App.java
|-.gitignore
`-README.md
===== ButtonPanel =====
package views;
import java.util.HashMap;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class ButtonPanel extends JPanel{
public HashMap buttons;
public ButtonPanel() {
this.initPanel();
}
public void addButton(String text) {
JButton button = new JButton(text);
this.add(button);
this.buttons.put(text, button);
}
private void initPanel() {
this.buttons = new HashMap<>();
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
}
}
===== A ButtonPanel használata =====
import controllers.MainController;
public class App {
public static void main(String[] args) throws Exception {
new MainController();
}
}
package views;
import javax.swing.JFrame;
public class Mainwindow extends JFrame {
public ButtonPanel buttonPanel;
public Mainwindow() {
initApp();
}
private void initApp() {
this.initComponent();
this.setComponent();
this.addComponent();
this.initWindow();
}
private void initComponent() {
this.buttonPanel = new ButtonPanel();
}
private void setComponent() {
this.buttonPanel.addButton("Számít");
this.buttonPanel.addButton("Névjegy");
this.buttonPanel.addButton("Kilépés");
}
private void addComponent() {
this.add(this.buttonPanel);
}
private void initWindow() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
this.setVisible(true);
}
}
package controllers;
import javax.swing.JButton;
import views.Mainwindow;
public class MainController {
Mainwindow mainwindow;
public MainController() {
this.mainwindow = new Mainwindow();
this.handleEvent();
}
private void handleEvent() {
JButton calcButton = this.mainwindow.buttonPanel.buttons.get("Számít");
JButton aboutButton = this.mainwindow.buttonPanel.buttons.get("Névjegy");
JButton exitButton = this.mainwindow.buttonPanel.buttons.get("Kilépés");
calcButton.addActionListener(e -> {
System.out.println("Számít árnyékeljárás...");
});
aboutButton.addActionListener(e -> {
System.out.println("Névjegy árnyékeljárás...");
});
exitButton.addActionListener(e -> {
System.out.println("Kilépés árnyékeljárás...");
});
}
}