JPanel Basic Tutorial
Note that JPanel class has no menubar like JFrame JMenuBar.
How to declare Java JPanel class
[class JPanel extends JComponent implements Accessible
]
Java JPanel Constructors
- JPanel()-creates a JPanel with a doule buffer and flow layout.
- JPanel(boolean isBuffered)-creates JPanel with flowLayout and specified buffering strategy.
- JPanel(LayoutManager layout)-create JPanel with specified Layout.
Java JPanel Example
[
/** * This program creates A JFrame and adds JPanel
* with two buttons
* * @author Eric */
import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JFrame; import java.awt.Color; public class JavaJPanel extends JFrame { JavaJPanel() { super("JFrame Example"); JPanel panel=new JPanel(); panel.setBounds(10,20,200,100); panel.setBackground(Color.BLUE); JButton b1=new JButton("Button 1"); b1.setBounds(10,100,80,30); b1.setBackground(Color.PINK); JButton b2=new JButton("Button 2"); b2.setBounds(100,100,80,30); b2.setBackground(Color.MAGENTA); panel.add(b1); panel.add(b2); add(panel); setSize(300,200); setLocationRelativeTo(null); setLayout(null); setVisible(true); } public static void main(String args[]) { new JavaJPanel(); } }
]
Java JPanel Example adding ActionListener
[
/** * This program creates A JFrame and adds JPanel* with two buttons which implement ActionListener ** @author Eric */import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JFrame; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; public class JavaJPanel extends JFrame implements ActionListener{ public JButton b1,b2; JavaJPanel() { super("JFrame Example"); JPanel panel=new JPanel(); panel.setBounds(10,20,150,100); panel.setBackground(Color.BLUE); b1=new JButton("Button 1"); b1.setBounds(10,100,80,30); b1.setBackground(Color.PINK); b1.addActionListener(this); b2=new JButton("Button 2"); b2.addActionListener(this); b2.setBounds(100,100,80,30); b2.setBackground(Color.MAGENTA); panel.add(b1); panel.add(b2); add(panel); setSize(300,200); setLocationRelativeTo(null); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent evt) { if(evt.getSource()==b1) { JOptionPane.showMessageDialog(this,"You clicked Button 1", "JPanel Example",JOptionPane.INFORMATION_MESSAGE); } if(evt.getSource()==b2) { JOptionPane.showMessageDialog(this,"You clicked Button 2", "JPanel Example",JOptionPane.INFORMATION_MESSAGE); } } public static void main(String args[]) { new JavaJPanel(); } }