我希望我能记住包括我的所有细节,所以在这里。
我正在使用Java,我正在创建自己的界面,主窗口是一个JFrame,背景附加到JFrame,背景图像(如JLabel)与窗口完全吻合。然后我有一个附加到背景Jlabel的图像作为“开始”按钮。我的问题是我想创建一个自定义类,它将促进自己类中的每个按钮功能。
所以我不想让主类中的函数对按钮做出反应,而是想创建一个可以添加到后台的类...这里是我的代码也许有人可以给我一个例子而我可以弄明白其余的事情或指出我正确的方向。
下面的代码包含原文,请提供一个示例,说明如何将其更改为在Jlabel按钮的自己的类中封装eventlisteners
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class pipboy{
public static void main(String[] args){
pipboy pipboy_os = new pipboy();
pipboy_os.runmain();
}
public void runmain(){
//Create and set up the window.
JFrame frame = new JFrame("PIPBOY Research v0.0.03");
//background
ImageIcon background = new ImageIcon("UI/background/default.png");
JLabel label=new JLabel(background);
//radiation animated
ImageIcon animated_loading = new ImageIcon("UI/icon/loading/loading.png");
JLabel animated_icon = new JLabel(animated_loading);
animated_icon.setSize(128, 128);
animated_icon.setLocation(300, 125);
//Buff arm guy icon
ImageIcon icon_loading = new ImageIcon("UI/icon/34.png");
JLabel icon = new JLabel(icon_loading);
icon.setSize(128, 128);
icon.setLocation(300, 50);
label.add(icon);
label.add(animated_icon);
frame.add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
//Full screen
frame.setSize(800,480);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//This is the handler class i made but i want it in its own class with the buff arm icon picure so it can do something specific when the image is pressed
HandlerClass handler = new HandlerClass();
frame.addMouseListener(handler);
frame.addMouseMotionListener(handler);
}
private static class HandlerClass implements MouseListener, MouseMotionListener{
public void mouseClicked(MouseEvent event){
System.out.println(String.format("Clicked at %d,%d", event.getX(), event.getY()));
}
public void mousePressed(MouseEvent event){
}
public void mouseReleased(MouseEvent event){
}
public void mouseEntered(MouseEvent event){
}
public void mouseExited(MouseEvent event){
}
public void mouseDragged(MouseEvent event){
}
public void mouseMoved(MouseEvent event){
}
}
}
答案 0 :(得分:0)
显然我不知道多态性是如何在Java中起作用的,但这是我的解决方案(改变了一些名称)
import javax.swing.*;
class GUItests{
public JFrame mainContainerFrame;
public static void main(String[] args){
GUItests mainController = new GUItests();
mainController.startGUI();
}
public void startGUI(){
mainContainerFrame = new JFrame("test Frame");
mainContainerFrame.setSize(800,480);
mainContainerFrame.pack();
mainContainerFrame.setVisible(true);
mainContainerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel customButtonVar = customButton();
mainContainerFrame.getContentPane().add(customButtonVar);
}
public JLabel customButton(){
JLabel icon = new JLabel("testing");
icon.setSize(128, 128);
icon.setLocation(300, 50);
return icon;
}
}