Implement a class called CounterGUI which extends JF rame to display a GUI ident
ID: 3683142 • Letter: I
Question
Implement a class called CounterGUI which extends JF rame to display a GUI identical to the one depicted below: Initialise the frame in the CounterGUI constructor. Also call a createComponents() method from the constructor to create and add the components. Include a main() method within the Counter GUI class as a static method which sets the frame to visible. As part of the last assignment, you will be required to get the buttons to function. For now, just get the GUI elements displayed. To do this, create a 150times200 frame. Add a panel (JPane1) to the frame which contains a text field (JTextField) and 2 buttons (JButton). If you use the default layout for JPane1 (which is FlowLayout) and the dimensions specified for the frame, your GUI elements should display as depicted in the figure. You can initialize the String values displayed in the GUI elements when you call the constructor for each element. Note that the frame should be called CounterGUI. You can right Justify the text field using (calling the method off of you text field): setHorizontalAlignment(JTextFleld.RIGHT). Challenge (you don't have to do this to get full credit for the lab) Play around with layout functionality to get your GUI elements to layout as depicted in the figure to the right. Consider adding 2 panels instead of 1 (use the first to contain the field, and the 2^nd to contain the buttons). The frame's content pane uses a BoderLayout and you can position the panels by adding them as follows: add(buttonPane1, BorderLayout.CENTER); add(fieldPane1, BoderLayout.LINE_START); Since the panels have a FlowLayout by default, the buttons should display properly in the button panel without any adjustments.Explanation / Answer
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CounterGUI extends JFrame implements ActionListener
{
JTextField t;
JButton b1, b2;
JPanel p;
int count = 0;
public CounterGUI()
{
createComponents();
}
public void createComponents()
{
t = new JTextField(10);
t.setHorizontalAlignment(JTextField.RIGHT);
b1 = new JButton("Increment");
b2 = new JButton("Decrement");
b1.addActionListener(this);
b2.addActionListener(this);
p = new JPanel();
Container c = getContentPane();
c.setLayout(new FlowLayout());
p.setLayout(new BorderLayout());
p.add(t, BorderLayout.NORTH);
p.add(b1, BorderLayout.CENTER);
p.add(b2, BorderLayout.SOUTH);
c.add(p);
}
public static void main(String[] args)
{
CounterGUI g = new CounterGUI();
g.setSize(150,200);
g.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
count++;
t.setText("" + count);
}
if(e.getSource()==b2)
{
count--;
t.setText("" + count);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.