1
我有一個JTextArea和一個JTextField,現在我想,如果我在JTextArea中點擊鏈接時轉到的JTextArea和 當我點擊JTextField的按鈕控制轉移到了JTextField,當開關的JTextField。我 沒有得到任何東西去做這樣的事情。 該程序只是基於點擊的JRadioButton來更改JTextField中的文本。點擊一個按鈕
***This is the code:***
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class prg_32 extends JPanel implements ItemListener{
JTextArea a1;
JButton t1,t2;
JRadioButton b1,b2,b3,b4;
JTextField fld1;
ButtonGroup grp;
GridBagConstraints gbc = new GridBagConstraints(); //GridBagConstraints object
public prg_32(){
setLayout(new GridBagLayout());
a1 = new JTextArea(3,10); //TextArea
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 3;
gbc.fill = GridBagConstraints.VERTICAL;
add(a1,gbc); //location of JTextArea
t1 = new JButton("TextArea");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridheight = 1;
add(t1,gbc); //location of JButton
t2 = new JButton("TextField");
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridheight = 1;
add(t2,gbc); //location of JButton
b1 = new JRadioButton("Bold",false);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridheight = 1;
add(b1,gbc);
b2 = new JRadioButton("Italic",false);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridheight = 1;
add(b2,gbc);
b3 = new JRadioButton("Plain",false);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridheight = 1;
add(b3,gbc);
b4 = new JRadioButton("Bold/Italic",true);
gbc.gridx = 2;
gbc.gridy = 2;
gbc.gridheight = 1;
add(b4,gbc);
grp = new ButtonGroup();
grp.add(b1);
grp.add(b2);
grp.add(b3);
grp.add(b4);
fld1 = new JTextField("enter your name");
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(fld1,gbc);
fld1.setFont(new Font("Serif",Font.BOLD + Font.ITALIC,14));
b1.addItemListener(this); //Event Handling
b2.addItemListener(this); //Event Handling
b3.addItemListener(this); //Event Handling
b4.addItemListener(this); //Event Handling
}
public void itemStateChanged(ItemEvent e) {
Font font = null;
if(b1.isSelected())
font = new Font("Serif",Font.BOLD,14);
else if(b2.isSelected())
font = new Font("Serif",Font.ITALIC,14);
else if(b3.isSelected())
font = new Font("Serif",Font.PLAIN,14);
else
font = new Font("Serif",Font.BOLD + Font.ITALIC,14);
fld1.setFont(font);
}
public static void main(String[] args){
prg_32 px = new prg_32();
JFrame jf = new JFrame();
jf.setSize(500, 300);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(px);
}
}
請勿使用requestFocus()。閱讀API。正確的使用方法是'requestFocustInWindow()'。 – camickr