站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

Questions and Exercises: User Interfaces That Swing - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Getting Started with Swing

Questions and Exercises: User Interfaces That Swing

Questions

Use the API documentation to answer these questions.
1. Show the code that creates a label displaying the following text, with the italics and boldface as shown in this screenshot:

2. Use the API documentation or online tutorial, if necessary, to answer the following questions:

a. 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 (Jlabel) be centered instead of left-aligned?

b. What method do you use to enable and disable such components as Swing buttons?

c. How do you add a component to the rightmost (east) cell in a container that uses BorderLayout?

3. Is the following code thread-safe? If so, why? If not, what can you do to make it thread-safe?
   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);
   }

Exercises

You'll need to work on these exercises in order, as they build upon each other. Hint: Your answer to question 2 will be useful.
1. Write an application called SwingApp1 that has two buttons and one label, arranged as shown in the following screenshot:


Hint: You can use the content pane's default BorderLayout to manage the buttons and label.

2. Copy SwingApp1.java to SwingApp2.java, and modify SwingApp2 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:

3. Copy SwingApp2.java to SwingApp3.java, and modify SwingApp3 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.

Check your answers.(in the Creating a GUI with JFC/Swing trail)

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail Search
Feedback Form