Hallo Java Freunde,
mein Problem ist folgendes:
Ich habe eine extra Klasse für Buttons erstellt das ich, wenn ich einen Button brauche einfach nur ein Objekt erstellen und Parameter übergeben muss. Doch nun habe ich das Problem das wenn ich mit ActionListener eine abfrage mache möchte mit if(e.getSource() == BUTTON_NAME) das er alle Buttons anspricht also unabhängig vom namen. Wie kann ich das beheben ???:L
Haupt Klasse:
Button Klasse:
mein Problem ist folgendes:
Ich habe eine extra Klasse für Buttons erstellt das ich, wenn ich einen Button brauche einfach nur ein Objekt erstellen und Parameter übergeben muss. Doch nun habe ich das Problem das wenn ich mit ActionListener eine abfrage mache möchte mit if(e.getSource() == BUTTON_NAME) das er alle Buttons anspricht also unabhängig vom namen. Wie kann ich das beheben ???:L
Haupt Klasse:
Java:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Frame extends JFrame{
public JButton btn_start, btn_exit;
public JLabel lbl_gameName;
public final int ScreenWidth = 800, ScreenHeight = 500;
public static void main(String[] args) {
Frame frame = new Frame();
}
public Frame(){
setSize(ScreenWidth, ScreenHeight);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
setLayout(null);
setBackground(Color.GREEN);
// Label create
lbl_gameName = new Label((ScreenWidth/2)-105,10,500,40,"Wilderness");
lbl_gameName.setFont(new Font("Arial", Font.CENTER_BASELINE,40));
lbl_gameName.setForeground(Color.GRAY);
// Buttons create
btn_start = new Button((ScreenWidth/2)-150,80,300,40,"Spiel starten");
btn_exit = new Button((ScreenWidth/2)-150,160,300,40,"Spiel beenden");
// Button add ActionListener
btn_start.addActionListener(new Al());
btn_exit.addActionListener(new Al());
}
public void paint(Graphics g){
super.paint(g);
//g.drawImage(Toolkit.getDefaultToolkit().getImage("C:/Java/img/bg.jpg"), 0, 0, 800, 500, this);
add(btn_start);
add(btn_exit);
add(lbl_gameName);
}
public class Al implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btn_exit)
System.out.println("Game is closed");
System.exit(0);
}
}
}
Button Klasse:
Java:
import java.awt.Component;
import javax.swing.JButton;
public class Button extends JButton{
public static int x, y,width,height;
public static String title;
public Button(int p_x, int p_y, int p_width, int p_height, String p_title){
x = p_x;
y = p_y;
width = p_width;
height = p_height;
title = p_title;
System.out.println("Button wurde deklariert " + "public: "+ x + y + width + height + "intern: " + p_x + p_x + p_width + p_height);
setBounds(x,y,width,height);
setText(title);
setLayout(null);
}
}