Let’s start out easy so that there is no user interaction yet. Write a Swing com
ID: 3802365 • Letter: L
Question
Let’s start out easy so that there is no user interaction yet. Write a Swing component MyLabels that extends JPanel and contains three JLabel instances that display “One”, “Two” and “Three”, respectively. Your component should prefer to have a size of 200*100 pixels, and have an etched border around it. Write a main method that creates and opens a JFrame instance that uses FlowLayout and contains three separate instances of MyLabels. (Inside the frame, there will therefore be a total of nine labels showing; that is, three labels inside each of your three MyLabels components.)
Explanation / Answer
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
public class MyLabels extends JPanel {
private JLabel one, two ,three;
public MyLabels()
{
one = new JLabel("One");
n.setHorizontalAlignment(SwingConstants.CENTER);
two = new JLabel("Two");
s.setHorizontalAlignment(SwingConstants.CENTER);
three = new JLabel("Three");
e.setHorizontalAlignment(SwingConstants.CENTER);
this.add(one); //Adding the labels to the panel
this.add(two);
this.add(three);
this.setPreferedSize(new Dimension(200,100));
this.setBorder(new EtchedBorder(EtchedBorder.RAISED)); //This can be either raised or lowered
}
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout()); //creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
for (int i = 0; i < 3; i++) {
MyLabels panel = new MyLabels();
frame.add(panel); //Adding panels to the frame
}
frame.setVisible(true);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.