I'm trying to write a Java program that declares a JFrame class and creates an object of that class in the main. For the life of me I cannot get the JFrame title, JPanel, and JButtons to appear when I create the "MyButtons" object in the main. All I get is a blank JPanel.
import java.awt.*;
import javax.swing.*;
import java.util.*;
class MyButtons extends JFrame
{
public MyButtons()
{
JFrame frame = new JFrame("MyButtons");
JPanel panel = new JPanel();
frame.add(panel);
JButton b1 = new JButton("Button 1");
JButton b2 = new JButton("Button 2");
panel.add(b1);
panel.add(b2);
}
}
class TestMyButtons
{
public static void main(String [] args)
{
MyButtons go = new MyButtons();
go.setSize(200,75);
go.setLocation(200,300);
go.setVisible(true);
go.setResizable(true);
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Answer
As you extend JFrame so you don't need to create another JFrame instance at constructor. Simply add panel
to MyButtons
which already inherited JFrame
.
public MyButtons(){
//JFrame frame = new JFrame("MyButtons"); Commentted this
JPanel panel = new JPanel();
//frame.add(panel); And this
JButton b1 = new JButton("Button 1");
JButton b2 = new JButton("Button 2");
panel.add(b1);
panel.add(b2);
add(panel); // Add panel to MyButtons frame
}
No comments:
Post a Comment