日期:2014-05-20  浏览次数:20802 次

最后30分。问几个swing初级问题
1。怎么得到文本框中选中的文本?
2。如果设置文本框自动选中文件?比如点一个button就自动选中文本框中的第三个字符?

。。   外加一个   :有没有剪贴板类?   谢谢回答!

------解决方案--------------------
因为按住按钮后,焦点被button得到了,而textArea失去了焦点,所以被选中的文本不会被高亮显示,实际上文本是被选中的,只要textArea得到了焦点,被选中的文本就会被高亮显示出来,看一下程序你就知道了:


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
import java.beans.*;
import javax.swing.event.*;
import java.util.*;

class HelloJava extends JPanel implements Runnable {
private JComboBox comboBox;
JTextArea textArea;
static int times = 0;

public HelloJava() {
textArea = new JTextArea(10, 10);
textArea.setLineWrap(true);
//textArea.setSelectedTextColor(new Color(255, 0, 0));
//textArea.setSelectionColor(new Color(0, 255, 0));
JScrollPane scroller = new JScrollPane();
scroller.getViewport().setView(textArea);
this.add(scroller);

AbstractAction action = new AbstractAction( "Select ") {
public void actionPerformed(ActionEvent ae) {
textArea.select(0, textArea.getText().length());
System.out.println(textArea.getSelectedText());// 输出测试是否有文本被选中.
textArea.requestFocus(); // 关键就在这里,让textArea获得焦点,高亮显示被选中文本.
}
};

JButton button = new JButton(action);
this.add(button);
}

public void addMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu( "File ");
menuBar.add(fileMenu);
JMenuItem exitMenuItem = new JMenuItem( "Exit ");
fileMenu.add(exitMenuItem);
JFrame frame = (JFrame)SwingUtilities.getRoot(this);
frame.setJMenuBar(menuBar);
}

protected void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D)g;
GradientPaint gradient = new GradientPaint(0, 0, Color.BLACK,
0, this.getHeight(), Color.WHITE, true);
g2d.setPaint(gradient);
g2d.fillRect(0, 0, this.getWidth(), this.getHeight());

}

public void run() {
while (true) {
try {

Thread.sleep(500);

} catch(InterruptedException ie) {

}
}
}

private static void createUIAndShow() {
JFrame frame = new JFrame( "Swing Example ");
//JWindow frame = new JWindow();
frame.setUndecorated(false);
int width = 400;
int height = 400;
frame.setSize(width, height);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((int)((screenSize.getWidth() - width) / 2),
(int)((screenSize.getHeight() - height) / 2));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setUndecorated(true);