Start of Tutorial > Start of Trail |
Search
Feedback Form |
Question 1: Show the code that creates a label displaying the following text, with the italics and boldface as shown in this screenshot:
Answer 1:label = new JLabel("<html>The <em>last</em> word is <b>bold</b>.");Question 2: Use the API documentation or online tutorial, if necessary, to answer the following questions:
Question 2a: Assume that you have a Swing label that tends to have more horizontal space than it needs to display its text. What code would you use to make the text within a label (Question 3: Is the following code thread-safe? If so, why? If not, what can you do to make it thread-safe?Jlabel
) be centered instead of left-aligned?
Answer 2a: Here are two ways:ornew JLabel(labelText, JLabel.CENTER);label.setHorizontalAlignment(JLabel.CENTER);Question 2b: What method do you use to enable and disable such components as Swing buttons?
Answer 2b: TheComponent setEnabled
method.Question 2c: How do you add a component to the rightmost (east) cell in a container that uses
BorderLayout
?
Answer 2c: Here's one way:container.add(component, BorderLayout.EAST);JLabel label; Container createGUI() { ... //create a JPanel; add components to it, including label ... return panel; } public static void main(String[] args) { JFrame f = new JFrame("A Frame"); f.setContentPane(createGUI()); f.pack(); f.setVisible(true); String labelText = findTextFromSomewhere(); label.setText(labelText); }
Answer 3: It's not thread-safe because the main thread updates the label after the label is visible. You can useSwingUtilities.invokeLater
to makelabel.setText
be executed on the event-dispatching thread.
Question 1: Write an application calledSwingApp1
that has two buttons and one label, arranged as shown in the following screenshot:
Hint: You can use the content pane's defaultBorderLayout
to manage the buttons and label.
Answer 1: SeeSwingApp1
.Question 2: Copy
SwingApp1.java
toSwingApp2.java
, and modifySwingApp2
so that the Stop button is initially disabled. Implement and register one or two action listeners so that when the user clicks either button, the clicked button is disabled, the other button is enabled, and the label is updated appropriately. Your application should look like this:
Answer 2: SeeSwingApp2
.Question 3: Copy
SwingApp2.java
toSwingApp3.java
, and modifySwingApp3
so that its Start button brings up a dialog that looks like this:
If the user chooses the Go ahead button, the Start button should do exactly what it did in SwingApp2
. If the user does anything else, the application should update the label to report the cancellation and leave the buttons in their existing state.
Answer 3: SeeSwingApp3
.
Start of Tutorial > Start of Trail |
Search
Feedback Form |