Algo parece estar mal con el diseño, JButton muestra un comportamiento inesperado al cambiar el tamaño de la ventana
JRE Versión 1.7 Actualización 3
COMPORTAMIENTO ESPERADO
Mientras ejecuto el programa, funciona como se esperaba, todo funciona sin problemas. Como cuando hago clic enSTOP
JButton
la animación se detiene y el texto en la mismaJButton
cambios aSTART
. Ahora cuando hago clic enBALL COLOUR
JButton
, el color de laBALL
cambios, así como el color de laBALL COLOUR
JBUTTON
, también cambia, al de laBALL
. Todo este comportamiento funciona si ejecuto mi aplicación como está sin cambiar el tamaño.
COMPORTAMIENTO INESPERADO
Pero cuando yoRESIZE
myJFrame
, tirando de laRight Side
, es cuando se muestra un comportamiento inesperado de mi aplicación, en el sentido de que si presionoSTOP
JButton
y luego haga clic enBALL COLOUR
, el texto en elJButton
hizo clic anteriormente cuyo texto cambió aSTART
cambiará aSTOP
nuevamente cuando no debería ser así como el color de laBALL COLOUR
JButton
permanecerá sin cambios o cambiará aBLUE
, cuando debe cambiarse al color de la pelota. Adjunto las fotos para más información. Pero si intenta cambiar el tamaño a su tamaño original o más cerca de eso, las cosas volverán a la normalidad. Por qué está pasando esto ? Cualquier idea o pista será muy apreciada.
Como mi aplicación se ejecuta con COMPORTAMIENTO ESPERADO como se describió anteriormente
Y aquí el COMPORTAMIENTO INESPERADO
LÍNEA DE FONDO
Por qué la aplicación se ejecuta como siempre, como debería ser, en elBEGINNING
, pero no cuandoRESIZED
arrastrando esRIGHT SIDE
, pero nuevamente, si lo lleva a su tamaño original o más cerca, las cosas vuelven a la normalidad, ¿funciona como se esperaba?
Así que considerando el escenario, ¿estoy haciendo algo mal en el programa? ¿O es exactamente esta la situación, donde debería estar usando laSwingWorker
, O ¿Es un problema con laLayout
, o algo oculto relacionado conContent Pane
. Por favor, ponga algo de luz: -)
aquí está el código que estoy usando, lo reduje al mínimo, ya que creo que demuestra mi problema:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BallAnimation
{
private int x;
private int y;
private boolean positiveX;
private boolean positiveY;
private boolean isTimerRunning;
private int speedValue;
private int diameter;
private DrawingArea drawingArea;
private Timer timer;
private int colourCounter;
Color[] colours = {
Color.BLUE.darker(),
Color.MAGENTA.darker(),
Color.BLACK.darker(),
Color.RED.darker(),
Color.PINK.darker(),
Color.CYAN.darker(),
Color.DARK_GRAY.darker(),
Color.YELLOW.darker(),
Color.GREEN.darker()
};
private Color backgroundColour;
private Color foregroundColour;
private ActionListener timerAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
x = getX();
y = getY();
drawingArea.setXYColourValues(x, y, backgroundColour
, foregroundColour);
}
};
private JPanel buttonPanel;
private JButton startStopButton;
private JButton speedIncButton;
private JButton speedDecButton;
private JButton resetButton;
private JButton colourButton;
private JButton exitButton;
private ComponentAdapter componentAdapter = new ComponentAdapter()
{
public void componentResized(ComponentEvent ce)
{
timer.restart();
startStopButton.setText("STOP");
isTimerRunning = true;
}
};
public BallAnimation()
{
x = y = 0;
positiveX = positiveY = true;
speedValue = 1;
colourCounter = 0;
isTimerRunning = false;
diameter = 50;
backgroundColour = Color.WHITE.brighter();
foregroundColour = colours[colourCounter];
timer = new Timer(10, timerAction);
}
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Ball Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
drawingArea = new DrawingArea(x, y
, backgroundColour, foregroundColour, diameter);
drawingArea.addComponentListener(componentAdapter);
frame.add(makeButtonPanel(), BorderLayout.LINE_END);
frame.add(drawingArea, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private JPanel makeButtonPanel()
{
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1));
buttonPanel.setBorder(BorderFactory.createLineBorder(
Color.DARK_GRAY, 5, true));
startStopButton = new JButton("START");
startStopButton.setBackground(Color.GREEN.darker());
startStopButton.setForeground(Color.WHITE.brighter());
startStopButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("START/STOP JButton Clicked!");
if (!isTimerRunning)
{
startStopButton.setText("STOP");
timer.start();
isTimerRunning = true;
buttonPanel.revalidate();
buttonPanel.repaint();
}
else if (isTimerRunning)
{
startStopButton.setText("START");
timer.stop();
isTimerRunning = false;
buttonPanel.revalidate();
buttonPanel.repaint();
}
}
});
startStopButton.setBorder(BorderFactory.createLineBorder(
Color.WHITE, 4, true));
buttonPanel.add(startStopButton);
colourButton = new JButton("BALL COLOUR");
colourButton.setBackground(colours[colourCounter]);
colourButton.setForeground(Color.WHITE);
colourButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("COLOUR JButton Clicked!");
//timer.restart();
colourCounter++;
if (colourCounter == 9)
colourCounter = 0;
foregroundColour = colours[colourCounter];
drawingArea.setXYColourValues(x, y, backgroundColour
, foregroundColour);
//drawingArea.setForegroundForBall(foregroundColour);
colourButton.setBackground(foregroundColour);
colourButton.revalidate();
colourButton.repaint();
//timer.start();
}
});
colourButton.setBorder(BorderFactory.createLineBorder(
Color.WHITE, 2, true));
buttonPanel.add(colourButton);
exitButton = new JButton("EXIT");
exitButton.setBackground(Color.RED.darker());
exitButton.setForeground(Color.WHITE.brighter());
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("EXIT JButton Clicked!");
timer.stop();
System.exit(0);
}
});
exitButton.setBorder(BorderFactory.createLineBorder(
Color.RED.darker().darker(), 4, true));
buttonPanel.add(exitButton);
return buttonPanel;
}
private int getX()
{
if (x < 0)
positiveX = true;
else if (x >= drawingArea.getWidth() - diameter)
positiveX = false;
return (calculateX());
}
private int calculateX()
{
if (positiveX)
return (x += speedValue);
else
return (x -= speedValue);
}
private int getY()
{
if (y < 0)
positiveY = true;
else if (y >= drawingArea.getHeight() - diameter)
positiveY = false;
return (calculateY());
}
private int calculateY()
{
if (positiveY)
return (y += speedValue);
else
return (y -= speedValue);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new BallAnimation().createAndDisplayGUI();
}
};
SwingUtilities.invokeLater(runnable);
}
}
class DrawingArea extends JComponent
{
private int x;
private int y;
private int ballDiameter;
private Color backgroundColor;
private Color foregroundColor;
public DrawingArea(int x, int y
, Color bColor, Color fColor, int dia)
{
this.x = x;
this.y = y;
ballDiameter = dia;
backgroundColor = bColor;
foregroundColor = fColor;
setBorder(BorderFactory.createLineBorder(
Color.DARK_GRAY.darker(), 5, true));
}
public void setXYColourValues(int x, int y
, Color bColor, Color fColor)
{
this.x = x;
this.y = y;
backgroundColor = bColor;
foregroundColor = fColor;
repaint();
}
public Dimension getPreferredSize()
{
return (new Dimension(500, 400));
}
public void paintComponent(Graphics g)
{
g.setColor(backgroundColor);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(foregroundColor);
g.fillOval(x, y, ballDiameter, ballDiameter);
}
}
** ÚLTIMA EDICIÓN: **