package java实践;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JDialog;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public class Goto extends JDialog {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public Goto(JTextArea textArea) {
setVisible(true);
setBounds(100, 100, 691, 134);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("请输入行序号:");
label.setBounds(73, 36, 105, 18);
contentPane.add(label);
textField = new JTextField();
textField.setBounds(176, 33, 170, 24);
contentPane.add(textField);
textField.setColumns(10);
JButton button = new JButton("定位到");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int totalLine = textArea.getLineCount();
int[] lineNumber = new int[totalLine + 1];
String s = textArea.getText();
int pos = 1, t = 0;
while (true) {
pos = s.indexOf('\12', pos);
if (pos == -1)
break;
lineNumber[t++] = pos++;
}
int gt = 1;
gt = Integer.parseInt(textField.getText());
if (gt < 2 || gt >= totalLine) {
if (gt < 2) {
textArea.setCaretPosition(0);
}else {
textArea.setCaretPosition(s.length());
}
}else {
textArea.setCaretPosition(lineNumber[gt - 2] + 1);
}
setVisible(false);
}
});
button.setBounds(360, 32, 113, 27);
contentPane.add(button);
JButton button_1 = new JButton("取消");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
button_1.setBounds(497, 32, 113, 27);
contentPane.add(button_1);
}
}