Here is the code I have. Basically all I want to do is change the
background of the frame to black when I click the mouse (mouseClicked)
and change it back to white when I release the mouse (mouseReleased).
I can't access frame directly to do frame.setBackground(Color.BLACK),
and that is where I am stuck.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class BackgroundChange extends JFrame
{
public BackgroundChange()
{
}
public static void main(String[] args)
{
BackgroundChange frame = new BackgroundChange();
frame.setTitle("Background Change");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
frame.setBackground(Color.WHITE);
}
}
class BackgroundChangePanel extends BackgroundChange implements
MouseListener
{
public BackgroundChangePanel()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
}
Michael Rauscher - 28 Nov 2006 08:10 GMT
Rick schrieb:
> Here is the code I have. Basically all I want to do is change the
> background of the frame to black when I click the mouse (mouseClicked)
> and change it back to white when I release the mouse (mouseReleased).
> I can't access frame directly to do frame.setBackground(Color.BLACK),
> and that is where I am stuck.
That's not the way it works. A frame is - hmm... a frame. What you see
on screen within a frame is not the frame but a container. Imagine the
frame as the window border.
A possible solution:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test {
private JPanel getContentPanel() {
JPanel panel = new JPanel();
panel.addMouseListener( new MouseAdapter() {
public void mouseClicked( MouseEvent e ) {
((JComponent)e.getSource()).setBackground(Color.BLACK);
}
});
panel.setPreferredSize( new Dimension(600,400) );
return panel;
}
public void createAndShowGUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
frame.setContentPane( getContentPanel() );
frame.pack();
frame.setVisible( true );
}
public static final void main( String args[] ) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
new Test().createAndShowGUI();
}
});
}
}
Bye
Michael