Я учусь использовать классы Java Swing и создаю простое приложение для практики.Я не знаю, как справиться с этой проблемой:Я хотел бы, чтобы, когда мышь входит в окно, была опущена вторая панель, на которой есть кнопки, чтобы свернуть окно, выйти или создать новое (которое я еще не реализовал).Другая панель, основная, закрывает рамку, поэтому я не могу добавить слушателя в рамку, чтобы зафиксировать прохождение мыши.Однако, если мышь попадает на верхнюю панель, анимация работает не так, как должна, и появляются небольшие ошибки.
Как мне убедиться, что когда мышь проходит по окну, в обоих случаях, если она находится на первой панели или на второй, анимация продолжается без помех?
Вот код:
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.LayoutManager;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
class PostIt extends JFrame {
private enum Colors {
YELLOW, BLUE, GREEN, ORANGE, VIOLET, RED;
}
// stuff
private static final long serialVersionUID = 1L;
private static int count = 0;
private int color;
// components
private final JPanel topPanel;
private final JButton minimize;
private final JButton exit;
private final JButton add;
// coords and dimensions
private static Point componentCoords = null;
private static final int WIDTH = 200; // 30*6
private static final int HEIGHT = 200; // 30*7
private static final int ORIGINALX = 700;
private static final int ORIGINALY = 100;
// 7*6 matrix
// 30*30 px each cell
private static int animationH = 10;
public PostIt() {
// frame
environment();
count++;
// panel
final JPanel panel = new JPanel();
panel.setBounds(0, 0, WIDTH, animationH);
panel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(final MouseEvent e) {
}
@Override
public void mouseDragged(final MouseEvent e) {
final Point currentCoords = e.getLocationOnScreen();
setLocation(currentCoords.x - componentCoords.x, currentCoords.y - componentCoords.y);
}
});
panel.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(final MouseEvent e) {}
@Override
public void mousePressed(final MouseEvent e) {
componentCoords = e.getPoint();
}
@Override
public void mouseReleased(final MouseEvent e) {
componentCoords = null;
}
@Override
public void mouseEntered(final MouseEvent e) {}
@Override
public void mouseExited(final MouseEvent e) {}
});
// top panel
topPanel = new JPanel((LayoutManager) null);
topPanel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(final MouseEvent e) {
}
@Override
public void mouseDragged(final MouseEvent e) {
final Point currentCoords = e.getLocationOnScreen();
setLocation(currentCoords.x - componentCoords.x, currentCoords.y - componentCoords.y);
}
});
topPanel.setBackground(randomColor());
topPanel.addMouseListener(new MouseListener() {
@Override
public void mousePressed(final MouseEvent e) {
componentCoords = e.getPoint();
}
@Override
public void mouseClicked(final MouseEvent e) {
}
@Override
public void mouseEntered(final MouseEvent e) { // expand
new Timer(1, e1 -> {
panel.setSize(WIDTH, animationH);
animationH += 1;
if (animationH >= 30) {
((Timer) e1.getSource()).stop();
}
}).start();
}
@Override
public void mouseExited(final MouseEvent e) { // compress
new Timer(1, e1 -> {
panel.setSize(WIDTH, animationH);
animationH -= 1;
if (animationH <= 10) {
((Timer) e1.getSource()).stop();
}
}).start();
}
@Override
public void mouseReleased(final MouseEvent e) {
componentCoords = null;
}
});
add(topPanel);
panel.setBackground(topPanel.getBackground().darker());
topPanel.add(panel);
// exit
exit = new JButton("x");
exit.addActionListener(e -> {
count--;
dispose();
});
// topPanel.add(exit);
// add
add = new JButton("+");
add.addActionListener(e -> {
final PostIt p = new PostIt();
System.out.println(count);
});
// topPanel.add(add);
// add
minimize = new JButton("_");
minimize.addActionListener(e -> {
setState(JFrame.ICONIFIED);
});
// topPanel.add(minimize);
}
public static boolean isMouseWithinComponent(final Component c)
{
final Point mousePos = MouseInfo.getPointerInfo().getLocation();
final Rectangle bounds = c.getBounds();
bounds.setLocation(c.getLocationOnScreen());
return bounds.contains(mousePos);
}
private void save() {
}
private void restore() {
}
/*
* private void loadImages () { try { exitIcon = new ImageIcon(ImageIO.read(new
* File("src\\media\\exit48.png"))); addIcon = new ImageIcon(ImageIO.read(new
* File("src\\media\\add48.png"))); minimizeIcon = new
* ImageIcon(ImageIO.read(new File("src\\media\\minimize48.png"))); } catch
* (Exception e) { e.printStackTrace(); } }
*/
private Color randomColor() {
switch (Colors.values()[randInt(Colors.values().length - 1)]) {
case YELLOW:
return new Color(255, 240, 120);
case BLUE:
return new Color(200, 240, 250);
case GREEN:
return new Color(205, 255, 140);
case ORANGE:
return new Color(250, 190, 5);
case RED:
return new Color(240, 140, 130);
case VIOLET:
return new Color(215, 175, 250);
default:
return null;
}
}
private void environment() {
setBounds(nextX(), nextY(), WIDTH, HEIGHT);
setAlwaysOnTop(true);
setUndecorated(true);
setResizable(false);
setVisible(true);
}
private static int randInt(final int min, final int max) {
if (min < 0 || min > max || max <= 0)
throw new IllegalArgumentException();
return (int) (java.lang.Math.random() * (max - min + 1) + min);
}
private static int randInt(final int max) {
return randInt(0, max);
}
private int nextX() {
return randInt(ORIGINALX - 50, ORIGINALX + 50);
}
private int nextY() {
return randInt(ORIGINALY - 50, ORIGINALY + 50);
}
public static void main(final String[] args) {
EventQueue.invokeLater(() -> {
try {
new PostIt();
} catch (final Exception ex) {
ex.printStackTrace();
// Logger.getLogger(PostIt.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
}