A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Swing / AWT / SWT
Author
button in jpanel should change background of jframe?
Chris Song
Greenhorn
Joined: Jan 29, 2005
Posts: 2
posted
Jan 30, 2005 15:41:00
0
Hello I have created 2 classes
First class is a jpanel and it has a button
Second class is a jframe and displays an object of jpanel.
I wrote this program so that i can understand object oriented programming.
My question is How can i change the jframe background colour by clicking the button that is in the jpanel class?
Could somebody provide me with a similar example. I would really apreciate it.
Thanks
Michael Dunn
Ranch Hand
Joined: Jun 09, 2003
Posts: 4632
posted
Jan 30, 2005 16:55:00
0
this changes the color of the containing
JPanel
of the main class, not the
JFrame
itself.
I've included 2 ways
1) passing a reference of the parent class to the child class
2) just using getParent()
import javax.swing.*; import java.awt.*; import java.awt.event.*; class MainApp extends JFrame { JPanel frame = new JPanel(); public MainApp() { setLocation(300,200); setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(400,300)); frame.add(new MyPanel(this)); getContentPane().add(frame); pack(); } public static void main(String args[]){new MainApp().setVisible(true);} } class MyPanel extends JPanel { MainApp mainFrame; Color[] colors = {Color.WHITE,Color.BLUE,Color.RED,Color.YELLOW,Color.BLACK}; int colorNum = 0; public MyPanel(MainApp ma) { mainFrame = ma; setLayout(new BorderLayout()); setPreferredSize(new Dimension(150,75)); add(new JLabel("Hello World",SwingConstants.CENTER),BorderLayout.NORTH); JButton btn = new JButton("Change color"); btn.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ colorNum = (colorNum+1) % colors.length; //mainFrame.frame.setBackground(colors[colorNum]);}}); getParent().setBackground(colors[colorNum]);}}); add(btn,BorderLayout.SOUTH); } }
I agree. Here's the link:
http://aspose.com/file-tools
subject: button in jpanel should change background of jframe?
Similar Threads
Message dialog box displaying behind the main frame
JFrames and JPanel
JLayeredPane in JPanel?
changing background color of JFrame
set picture as background of JFRAME and JPanel
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter