Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
AhmadLang / Introduction to Programming Using Java-1.pdf
Скачиваний:
71
Добавлен:
31.05.2015
Размер:
5.27 Mб
Скачать

CHAPTER 6. INTRODUCTION TO GUI PROGRAMMING

285

(The source code for the applet that produced this picture can be found in BorderDemo.java.)

6.7.3SliderAndComboBoxDemo

Now that we have looked at components and layouts, it’s time to put them together into some complete programs. We start with a simple demo that uses a JLabel, a JComboBox, and a couple of JSliders, all laid out in a GridLayout, as shown in this picture:

The sliders in this applet control the foreground and background color of the label, and the combo box controls its font style. Writing this program is a matter of creating the components, laying them out, and programming listeners to respond to events from the sliders and combo box. In my program, I define a subclass of JPanel which will be used for the applet’s content pane. This class implements ChangeListener and ActionListener, so the panel itself can act as the listener for change events from the sliders and action events from the combo box. In the constructor, the four components are created and configured, a GridLayout is installed as the layout manager for the panel, and the components are added to the panel:

/* Create the sliders, and set up this panel to listen for ChangeEvents that are generated by the sliders. */

bgColorSlider = new JSlider(0,255,100); bgColorSlider.addChangeListener(this);

fgColorSlider = new JSlider(0,255,200); fgColorSlider.addChangeListener(this);

CHAPTER 6. INTRODUCTION TO GUI PROGRAMMING

286

/* Create the combo box, and add four items to it, listing different font styles. Set up the panel to listen for ActionEvents from the combo box. */

fontStyleSelect = new JComboBox(); fontStyleSelect.addItem("Plain Font"); fontStyleSelect.addItem("Italic Font"); fontStyleSelect.addItem("Bold Font"); fontStyleSelect.addItem("Bold Italic Font"); fontStyleSelect.setSelectedIndex(2); fontStyleSelect.addActionListener(this);

/* Create the display label, with properties to match the values of the sliders and the setting of the combo box. */

displayLabel = new JLabel("Hello World!", JLabel.CENTER); displayLabel.setOpaque(true); displayLabel.setBackground( new Color(100,100,100) ); displayLabel.setForeground( new Color(255, 200, 200) ); displayLabel.setFont( new Font("Serif", Font.BOLD, 30) );

/* Set the layout for the panel, and add the four components. Use a GridLayout with 4 rows and 1 column. */

setLayout(new GridLayout(4,1)); add(displayLabel); add(bgColorSlider); add(fgColorSlider); add(fontStyleSelect);

The class also defines the methods required by the ActionListener and ChangeListener interfaces. The actionPerformed() method is called when the user selects an item in the combo box. This method changes the font in the JLabel, where the font depends on which item is currently selected in the combo box, fontStyleSelect:

public void actionPerformed(ActionEvent evt) { switch ( fontStyleSelect.getSelectedIndex() ) { case 0:

displayLabel.setFont( new Font("Serif", Font.PLAIN, 30) ); break;

case 1:

displayLabel.setFont( new Font("Serif", Font.ITALIC, 30) ); break;

case 2:

displayLabel.setFont( new Font("Serif", Font.BOLD, 30) ); break;

case 3:

displayLabel.setFont( new Font("Serif", Font.BOLD + Font.ITALIC, 30) ); break;

}

}

And the stateChanged() method, which is called when the user manipulates one of the sliders, uses the value on the slider to compute a new foreground or background color for the label. The method checks evt.getSource() to determine which slider was changed:

CHAPTER 6. INTRODUCTION TO GUI PROGRAMMING

287

public void stateChanged(ChangeEvent evt) { if (evt.getSource() == bgColorSlider) { int bgVal = bgColorSlider.getValue();

displayLabel.setBackground( new Color(bgVal,bgVal,bgVal) );

//NOTE: The background color is a shade of gray,

//determined by the setting on the slider.

}

else {

int fgVal = fgColorSlider.getValue(); displayLabel.setForeground( new Color( 255, fgVal, fgVal) );

//Note: The foreground color ranges from pure red to pure

//white as the slider value increases from 0 to 255.

}

}

(The complete source code is in the file SliderAndComboBoxDemo.java.)

6.7.4A Simple Calculator

As our next example, we look briefly at an example that uses nested subpanels to build a more complex user interface. The program has two JTextFields where the user can enter two numbers, four JButtons that the user can click to add, subtract, multiply, or divide the two numbers, and a JLabel that displays the result of the operation:

Like the previous example, this example uses a main panel with a GridLayout that has four rows and one column. In this case, the layout is created with the statement:

setLayout(new GridLayout(4,1,3,3));

which allows a 3-pixel gap between the rows where the gray background color of the panel is visible. The gray border around the edges of the panel is added with the statement

setBorder( BorderFactory.createEmptyBorder(5,5,5,5) );

The first row of the grid layout actually contains two components, a JLabel displaying the text “x =” and a JTextField. A grid layout can only only have one component in each position. In this case, that component is a JPanel, a subpanel that is nested inside the main panel. This subpanel in turn contains the label and text field. This can be programmed as follows:

xInput = new JTextField("0", 10);

// Create a text field sized to hold 10 chars.

JPanel xPanel = new JPanel();

// Create the subpanel.

xPanel.add( new JLabel(" x = "));

// Add a label to the subpanel.

xPanel.add(xInput);

// Add the text field to the subpanel

mainPanel.add(xPanel);

// Add the subpanel to the main panel.

CHAPTER 6. INTRODUCTION TO GUI PROGRAMMING

288

The subpanel uses the default FlowLayout layout manager, so the label and text field are simply placed next to each other in the subpanel at their preferred size, and are centered in the subpanel.

Similarly, the third row of the grid layout is a subpanel that contains four buttons. In this case, the subpanel uses a GridLayout with one row and four columns, so that the buttons are all the same size and completely fill the subpanel.

One other point of interest in this example is the actionPerformed() method that responds when the user clicks one of the buttons. This method must retrieve the user’s numbers from the text field, perform the appropriate arithmetic operation on them (depending on which button was clicked), and set the text of the label to represent the result. However, the contents of the text fields can only be retrieved as strings, and these strings must be converted into numbers. If the conversion fails, the label is set to display an error message:

public void actionPerformed(ActionEvent evt) {

double x, y; // The numbers from the input boxes.

try {

String xStr = xInput.getText();

x = Double.parseDouble(xStr);

}

catch (NumberFormatException e) {

// The string xStr is not a legal number. answer.setText("Illegal data for x."); xInput.requestFocus();

return;

}

try {

String yStr = yInput.getText();

y = Double.parseDouble(yStr);

}

catch (NumberFormatException e) {

// The string yStr is not a legal number. answer.setText("Illegal data for y."); yInput.requestFocus();

return;

}

/* Perfrom the operation based on the action command from the button. The action command is the text displayed on the button. Note that division by zero produces an error message. */

String op = evt.getActionCommand(); if (op.equals("+"))

answer.setText( "x + y = " + (x+y) ); else if (op.equals("-"))

answer.setText( "x - y = " + (x-y) ); else if (op.equals("*"))

answer.setText( "x * y = " + (x*y) ); else if (op.equals("/")) {

if (y == 0)

answer.setText("Can’t divide by zero!"); else

answer.setText( "x / y = " + (x/y) );