📄 radiobuttons.java
字号:
import java.text.*; // need this for formatting
import javax.swing.*;
import java.awt.event.*;
import java.awt.Container; // need this to add controls
import java.awt.*; // need this for layout manager
public class RadioButtons extends JFrame
{
private JFrame mainFrame;
private JButton exitButton;
private JLabel inLabel;
private JTextField tinField;
private JRadioButton rdbutCourier;
private JRadioButton rdbutSansSerif;
private JRadioButton rdbutSerif;
public RadioButtons() // a constructor
{
mainFrame = new JFrame("Radio Button Example");
// create all components
exitButton = new JButton("Exit");
inLabel = new JLabel("Enter Some Text:");
tinField = new JTextField(20);
rdbutCourier = new JRadioButton("Courier");
rdbutSansSerif = new JRadioButton("SansSerif");
rdbutSerif = new JRadioButton("Serif");
// put the buttons into a single group
ButtonGroup rgroup = new ButtonGroup();
rgroup.add(rdbutCourier);
rgroup.add(rdbutSansSerif);
rgroup.add(rdbutSerif);
// get the content pane
Container c = mainFrame.getContentPane();
// set the layout managare
c.setLayout(new FlowLayout());
// add the components to the ContentPane
c.add(inLabel);
c.add(tinField);
c.add(rdbutCourier);
c.add(rdbutSansSerif);
c.add(rdbutSerif);
c.add(exitButton);
// create accelerator keys
rdbutCourier.setMnemonic('C');
rdbutSansSerif.setMnemonic('S');
rdbutSerif.setMnemonic('f');
exitButton.setMnemonic('x');
// set the initial button and corresponding font
rdbutCourier.setSelected(true);
tinField.setFont(new Font("Courier",Font.PLAIN, 12));
mainFrame.setSize(300,150);
// define and register window event handler
mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e) {System.exit(0);}
});
// create and register the event handlers
ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler
exitButton.addActionListener(ehandler); // register the handler
RButHandler rhandler = new RButHandler();
rdbutCourier.addItemListener(rhandler);
rdbutSansSerif.addItemListener(rhandler);
rdbutSerif.addItemListener(rhandler);
mainFrame.show();
}
// inner classes for the Radio Button handlers
class RButHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
if (e.getSource() == rdbutCourier)
tinField.setFont(new Font("Courier",Font.PLAIN, 12));
else if (e.getSource() == rdbutSansSerif)
tinField.setFont(new Font("SansSerif",Font.PLAIN, 12));
else if (e.getSource() == rdbutSerif)
tinField.setFont(new Font("Serif",Font.PLAIN, 12));
tinField.repaint();
}
} // end of inner class
// inner class for the Exit button event handler
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
} // end of inner class
public static void main(String args[])
{
new RadioButtons(); // instantiate a GUI object
}
} // end of class
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -