필자는 Java Homework를 완료했지만 모든 기본 클래스 (두 개의 개인 클래스 포함)로 통합되었습니다. 클래스를 별도로 처리하여 코드를 좀 더 우아하게 만들려고합니다. 청취자가 기존 패널과 상호 작용하는 데 문제가 있습니다.청취 클래스를 사용하여 모든 청취를 처리합니다.
내가보고있는 주요 부분은 Listener.java에 있습니다. 마우스 클릭과 액션 리스너. 청취자를 트리거하기 위해 클릭 한 버튼의 이름을 가져올 수 있는데, 도움이되지만 Panel 패널에 추가 된 "DrawBoard"패널과 상호 작용할 수는 없습니다.
Window.java :
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends JFrame {
/**
*
*/
private static final long serialVersionUID = -8255319694373975038L;
public static void main(String[] args){
new Window();
}
public Window(){
// Adds the custom panel
Panel Panel = new Panel();
this.add(Panel);
// Basic Window Features
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,800);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
Panel.java :
public class Panel extends JPanel{
public Panel(){
Button testButton = new Button("Test");
DrawBoard drawBoard = new DrawBoard();
Listener listener = new Listener();
this.add(testButton);
this.add(drawBoard);
}
}
Button.java
나는이 상호 작용을 작업 할 수있는 가장 좋은 방법이 무엇인지 궁금하네요import java.awt.Dimension;
import javax.swing.JButton;
public class Button extends JButton{
public Button(String name) {
this.setText(name);
this.setName((String) name);
buttonSettings();
}
private void buttonSettings(){
Listener listener = new Listener();
this.addActionListener(listener);
int width = 200;
int height = 50;
Dimension dim = new Dimension(width,height);
this.setPreferredSize(dim);
}
}
DrawBoard. 자바
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
public class DrawBoard extends JPanel{
public DrawBoard(){
DrawBoardSettings();
}
private void DrawBoardSettings(){
int width = 600;
int height = 600;
Dimension dim = new Dimension(width,height);
this.setPreferredSize(dim);
this.setBackground(Color.WHITE);
}
}
Listener.java 여기
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JComponent;
public class Listener implements ActionListener, MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
**// Draw a dot at the mouse location of the DrawBoard JPanel that was added by the Panel JPanel that was added by the Window JFrame**
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
String name = ((JComponent) e.getSource()).getName();
**// Draw a rectangle on the DrawBoard JPanel that was added by the Panel JPanel that was added by the Window JFrame**
}
}
감사합니다. 나는 그저 한 번 수업을 시작했는지 확인한 다음 다른 수업에서 그 첫 번째 인스턴스를 호출하도록했습니다. –