Java_Swing_Programs
Java_Swing_Programs
Features of Swing:
1. Platform-independent
2. Lightweight components
3. Supports MVC architecture
4. Pluggable look and feel
2.3 Buttons
Swing provides various buttons like JButton, JCheckBox, and JRadioButton.
Example 2: Creating JButton and adding ActionListener:
```java
import javax.swing.*;
import java.awt.event.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Example");
JButton button = new JButton("Click Me");
button.addActionListener(e -> JOptionPane.showMessageDialog(null, "Button Clicked!"));
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
```
// Model
class Counter {
private int count = 0;
public int getCount() { return count; }
public void increment() { count++; }
}
// View
class CounterView extends JFrame {
JButton button = new JButton("Increment");
JLabel label = new JLabel("Count: 0");
CounterView() {
setLayout(new java.awt.FlowLayout());
add(label);
add(button);
setSize(200, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Controller
class CounterController {
Counter model;
CounterView view;
view.button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.increment();
view.updateCount(model.getCount());
}
});
}
}