
Patrick B. answered 05/31/21
Math and computer tutor/teacher
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
public class MyPanel extends JPanel
{
private JButton cmdButton1;
private JButton cmdButton2;
private JButton cmdButton3;
private String strTitle;
private Color backgroundColor;
public MyPanel(String strTitleStr, Color backColor)
{
strTitle = new String(strTitleStr);
this.backgroundColor = backColor;
//construct components
cmdButton1 = new JButton ("Button 1");
cmdButton2 = new JButton ("Button 2");
cmdButton3 = new JButton ("Button 3");
//adjust size and set layout
setPreferredSize (new Dimension (200, 150));
setLayout (null);
//add components
add (cmdButton1);
add (cmdButton2);
add (cmdButton3);
//set component bounds (only needed by Absolute Positioning)
cmdButton1.setBounds (35, 30, 100, 20);
cmdButton2.setBounds (35, 55, 100, 20);
cmdButton3.setBounds (35, 85, 100, 20);
Border blackline = BorderFactory.createTitledBorder(strTitle);
setBorder(blackline);
setBackground(backgroundColor);
cmdButton1.addActionListener(
new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null,"Button1");
}
}
);
cmdButton2.addActionListener(
new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null,"Button2");
}
}
);
cmdButton3.addActionListener(
new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null,"Button3");
}
}
);
}
}
//*********************************************************************************//
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MyFrame extends javax.swing.JFrame
{
private final MyPanel leftPanel;
private final MyPanel rightPanel;
public MyFrame()
{
leftPanel = new MyPanel("Left Panel",Color.RED); // our top component
rightPanel = new MyPanel("Right Panel",Color.GREEN); // our bottom component
// now lets define the default size of our window and its layout:
setPreferredSize(new Dimension(500, 200));
setResizable(false);
// the contentPane is the container that holds all our components
getContentPane().setLayout(new GridLayout()); // the default GridLayout is like a grid with 1 column and 1 row,
// we only add one element to the window itself
getContentPane().add(leftPanel);
getContentPane().add(rightPanel);
pack(); // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
setLocationRelativeTo(null);
}
public static void main(String args[]){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
MyFrame frame = new MyFrame();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}