Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Swing / AWT / SWT
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Jeanne Boyarsky
Ron McLeod
Paul Clapham
Liutauras Vilda
Sheriffs:
paul wheaton
Rob Spoor
Devaka Cooray
Saloon Keepers:
Stephan van Hulst
Tim Holloway
Carey Brown
Frits Walraven
Tim Moores
Bartenders:
Mikalai Zaikin
Forum:
Swing / AWT / SWT
button in jpanel should change background of jframe?
Chris Song
Greenhorn
Posts: 2
posted 19 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
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
Posts: 4632
posted 19 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
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); } }
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
JLayeredPane in JPanel?
changing background color of JFrame
set picture as background of JFRAME and JPanel
Message dialog box displaying behind the main frame
JFrames and JPanel
More...