Reputation: 13
I have created a class named Frame which simply creates a frame:
package panels;
public class Frame extends prog
{
public Frame() {
JFrame myFrame = new JFrame();
myFrame.setLayout( new FlowLayout() );
myFrame.setTitle("GUI Demo - ISTE-121");
myFrame.pack();
myFrame.setLocation(600,300);
myFrame.setSize(400,200);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Then, I have added that frame to the main()
:
package panels;
public class prog {
public static void main(String args[]) {
Frame first = new Frame();
}
}
I have created a class named panels and want to add this to class Frame. How should I do that?
The subclass is as follows:
public class panels extends Frame {
final JTextField items;
final JTextField number;
final JTextField cost;
final JTextField amount;
public panels()
{
JPanel order = new JPanel();
order.setLayout(new GridLayout(5,5,2,2));
order.add(new JLabel("Item no:", SwingConstants.RIGHT));
order.add(items = new JTextField(3));
order.add(new JLabel("Number of:", SwingConstants.RIGHT));
order.add(number = new JTextField(3));
order.add(new JLabel("Cost", SwingConstants.RIGHT));
order.add(cost = new JTextField(3));
order.add(new JLabel("Amount owed:", SwingConstants.RIGHT));
order.add(amount = new JTextField(10));
amount.setEditable(false);
}
}
Upvotes: 1
Views: 66
Reputation: 36
Change name of your first class. This class must extend a JFrame, panels class should extend JPanel. You should learn about layout managers, adding panel to container. It's basics of Swing. It's improved code of your program:
class MyFrame extends JFrame {
public MyFrame() {
JFrame myFrame = new JFrame();
myFrame.setLayout( new FlowLayout() );
myFrame.add(new panels());
myFrame.setTitle("GUI Demo - ISTE-121");
myFrame.pack();
myFrame.setLocation(600,300);
myFrame.setSize(400,200);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
class panels extends JPanel {
final JTextField items;
final JTextField number;
final JTextField cost;
final JTextField amount;
public panels() {
setLayout(new GridLayout(5,5,2,2));
add(new JLabel("Item no:", SwingConstants.RIGHT));
add(items = new JTextField(3));
add(new JLabel("Number of:", SwingConstants.RIGHT));
add(number = new JTextField(3));
add(new JLabel("Cost", SwingConstants.RIGHT));
add(cost = new JTextField(3));
add(new JLabel("Amount owed:", SwingConstants.RIGHT));
add(amount = new JTextField(10));
amount.setEditable(false);
}
}
public class FrameTest {
public static void main(String args[]) {
MyFrame first = new MyFrame();
}
}
Upvotes: 1