下面列出了javax.swing.JTextField#getText ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Verify that the height value is correct.
*
* @param input
* @return true if the value is valid; false otherwise
*/
private boolean verifyValueRangeUpperBoundInput(JComponent input) {
JTextField textField = (JTextField) input;
String inputString = textField.getText();
try {
double valueUpperBound;
if (inputString.startsWith("-")) {
valueUpperBound = Double.parseDouble(inputString.substring(1));
valueUpperBound = -valueUpperBound;
} else {
valueUpperBound = Double.parseDouble(inputString);
}
// TODO: fix check for actual ranges
} catch (NumberFormatException e) {
textField.setForeground(Color.RED);
return false;
}
textField.setForeground(Color.BLACK);
return true;
}
private PasswordAuthentication getCredential(String msg, boolean proxy) {
JTextField user = new JTextField(30);
JPasswordField pass = new JPasswordField(30);
String prompt = proxy ? StringResource.get("PROMPT_PROXY")
: String.format(StringResource.get("PROMPT_SERVER"), msg);
Object[] obj = new Object[5];
obj[0] = prompt;
obj[1] = StringResource.get("DESC_USER");
obj[2] = user;
obj[3] = StringResource.get("DESC_PASS");
obj[4] = pass;
if (JOptionPane.showOptionDialog(null, obj, StringResource.get("PROMPT_CRED"), JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) {
PasswordAuthentication pauth = new PasswordAuthentication(user.getText(), pass.getPassword());
return pauth;
}
return null;
}
/**
* Method to check whether value is provided or not; and display message box in case it is not provided
*
* @param textField Text field to be checked for value
* @param fieldName Name of the field
* @return Flag whether value exists or not
*/
private boolean checkMandatory(JTextField textField, String fieldName) {
if (!textField.isEnabled()) {
return true;
}
String value = textField.getText();
if (value == null || value.trim().equals("")) {
JOptionPane.showMessageDialog(this, labelUtil.getString("gui.msg.err.mandatoryCheck", fieldName),
labelUtil.getString("gui.msg.title.err"), JOptionPane.ERROR_MESSAGE);
textField.requestFocus();
return false;
}
return true;
}
/**
* Verify that the y-value is correct.
*
* @param input
* @return true if the value is valid; false otherwise
*/
private boolean verifyDomainRangeLowerBoundInput(JComponent input) {
JTextField textField = (JTextField) input;
String inputString = textField.getText();
try {
double domainLowerBound;
if (inputString.startsWith("-")) {
domainLowerBound = Double.parseDouble(inputString.substring(1));
domainLowerBound = -domainLowerBound;
} else {
domainLowerBound = Double.parseDouble(inputString);
}
// TODO: fix check for actual ranges
} catch (NumberFormatException e) {
textField.setForeground(Color.RED);
return false;
}
textField.setForeground(Color.BLACK);
return true;
}
/**
* Set file path from file chooser dialog.
*
* @param textField TextField to set the file path
* @param imagePanel ImagePnel to set the image
*/
private void setFilePathActionPerformed(JTextField textField, ImagePanel imagePanel) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("PNG Images", "png"));
if (!IOSImageUtil.isNullOrWhiteSpace(textField.getText())) {
File f = new File(textField.getText());
if (f.getParentFile() != null && f.getParentFile().exists()) {
chooser.setCurrentDirectory(f.getParentFile());
}
if (f.exists()) {
chooser.setSelectedFile(f);
}
} else {
File dir = getChosenDirectory();
if (dir != null) chooser.setCurrentDirectory(dir);
}
chooser.setApproveButtonText(getResource("button.approve", "Choose"));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
setFilePath(textField, chooser.getSelectedFile(), imagePanel);
}
}
private String hostDialogBox( String input)
{
JTextField hostnameTextField = new JTextField();
hostnameTextField.setText(input);
final JComponent[] inputs = new JComponent[] { new JLabel("Specify a hostname"), new JLabel( "You can use wildcards (* matches zero or more characters, ? matches any character except a dot)"),
hostnameTextField};
int result = JOptionPane.showConfirmDialog(null, inputs, input.length() == 0 ? "Add host" : "Edit host", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if( result == JOptionPane.OK_OPTION)
{
return hostnameTextField.getText();
}
else
{
return "";
}
}
private void checkFieldIsExecutable(
String name, JTextField textField, Optional<String> defaultValue) {
String text = textField.getText();
String executable = textToOptional(text).orElse(defaultValue.orElse(null));
if (executable == null) {
Messages.showErrorDialog(
getProject(),
"No " + name + " executable was specified or auto-detected for this field.",
"No Executable Specified");
} else {
try {
String found = executableDetector.getNamedExecutable(executable);
Messages.showInfoMessage(
getProject(),
found + " appears to be a valid executable",
"Found Executable " + executable);
} catch (RuntimeException e) {
Messages.showErrorDialog(
getProject(),
executable + " could not be resolved to a valid executable.",
"Invalid Executable");
}
}
}
@Override
public Object getCellEditorValue() {
JTextField textField = (JTextField) getComponent();
String newText = textField.getText();
String oldText = property().getText();
property().setText(newText);
if (!newText.equals(oldText)) {
markProperty();
}
return property();
}
@Override
public void actionPerformed(ActionEvent e) {
JTextField textLabel = (JTextField) e.getSource();
if (textLabel== frame.nameTextField) {
nameOfAnimal = textLabel.getText();
textLabel.setEditable(false);
frame.nrOfLegsTextField.requestFocus();
} else if (textLabel == frame.nrOfLegsTextField) {
nrOfLegs = textLabel.getText();
textLabel.setEditable(false);
frame.maintananceCostTextField.requestFocus();
} else if (textLabel == frame.maintananceCostTextField) {
maintananceCost = textLabel.getText();
textLabel.setEditable(false);
frame.dangerPercTextField.requestFocus();
} else if (textLabel == frame.dangerPercTextField) {
dangerPerc = textLabel.getText();
textLabel.setEditable(false);
frame.normalBodyTempTextField.requestFocus();
} else if (textLabel == frame.normalBodyTempTextField) {
normalBodyTemp = textLabel.getText();
textLabel.setEditable(false);
frame.percBodyHairTextField.requestFocus();
} else if (textLabel == frame.percBodyHairTextField) {
percBodyHair = textLabel.getText();
textLabel.setEditable(false);
frame.dummyLabel.requestFocus();
}
}
private TroopAmountElement getAmountForUnit(UnitHolder pUnit) {
JTextField field = getFieldForUnit(pUnit);
if(field != null) {
return new TroopAmountElement(pUnit, field.getText());
}
return new TroopAmountElement(pUnit, "0");
}
private boolean isVariableValue(JTextField tf) {
String value = tf.getText();
if(value != null) {
return value.startsWith("${") && value.endsWith("}");
} else {
return false;
}
}
/**
* Popups have a single purpose, to populate the Text fields with valid values, but users can
* type those in manually. The following parse functions try to recover the source storage, columns
* from the Text fields for quantities. On successful parsing (names and sources local variables are set).
* The syntax for File sources is File:<xxxx>:<yyyyy>
**/
private boolean parseDomainOrRangeText(JTextField jQtyTextField, boolean isDomain) {
String text = jQtyTextField.getText();
// Check for Empty
if (text.length()==0)
return false;
// Check for qualifiers
// We need to be forgiving in case the user types in the quantity manually
String trimmed = text.trim();
// Split around ":
String columnNameList = trimmed;
// If file doesn't exist or doesn't have column complain, otherwise
// set Storage and Column
String[] columns=columnNameList.trim().split(",",-1);
if (isDomain){
if (columns.length!=1){
JOptionPane.showMessageDialog(this, "Can't have more than one column for domain");
return false;
} else{
setDomainName(columns[0].trim());
return true; // Should check coordinate exists
}
} else { // range
for(int i=0; i<columns.length; i++){
columns[i]=columns[i].trim();
}
rangeNames = new String[columns.length];
System.arraycopy(columns, 0, rangeNames, 0, columns.length);
// set sourceY here after all error detection is done.
return true;
}
}
protected Object edit(Object o) {
JTextField f = new JTextField(20);
if(o != null) {
f.setText((String)o);
}
if(showEditDialog(f)) {
return f.getText();
}
return o;
}
public TextFieldFocusListener(JTextField parent)
{
defaultText = parent.getText();
}
public TextFieldFocusListener(JTextField parent)
{
defaultText = parent.getText();
}
protected void replaceLDC() {
final JPanel panel = new JPanel(new BorderLayout(5, 5));
final JPanel input = new JPanel(new GridLayout(0, 1));
final JPanel labels = new JPanel(new GridLayout(0, 1));
panel.add(labels, "West");
panel.add(input, "Center");
panel.add(new JLabel(JByteMod.res.getResource("big_string_warn")), "South");
labels.add(new JLabel("Find: "));
JTextField find = new JTextField();
input.add(find);
labels.add(new JLabel("Replace with: "));
JTextField with = new JTextField();
input.add(with);
JComboBox<String> ldctype = new JComboBox<String>(new String[] { "String", "float", "double", "int", "long" });
ldctype.setSelectedIndex(0);
labels.add(new JLabel("Ldc Type: "));
input.add(ldctype);
JCheckBox exact = new JCheckBox(JByteMod.res.getResource("exact"));
JCheckBox cases = new JCheckBox(JByteMod.res.getResource("case_sens"));
labels.add(exact);
input.add(cases);
if (JOptionPane.showConfirmDialog(this.jbm, panel, "Replace LDC", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, searchIcon) == JOptionPane.OK_OPTION && !find.getText().isEmpty()) {
int expectedType = ldctype.getSelectedIndex();
boolean equal = exact.isSelected();
boolean ignoreCase = !cases.isSelected();
String findCst = find.getText();
if (ignoreCase) {
findCst = findCst.toLowerCase();
}
String replaceWith = with.getText();
int i = 0;
for (ClassNode cn : jbm.getFile().getClasses().values()) {
for (MethodNode mn : cn.methods) {
for (AbstractInsnNode ain : mn.instructions) {
if (ain.getType() == AbstractInsnNode.LDC_INSN) {
LdcInsnNode lin = (LdcInsnNode) ain;
Object cst = lin.cst;
int type;
if (cst instanceof String) {
type = 0;
} else if (cst instanceof Float) {
type = 1;
} else if (cst instanceof Double) {
type = 2;
} else if (cst instanceof Long) {
type = 3;
} else if (cst instanceof Integer) {
type = 4;
} else {
type = -1;
}
String cstStr = cst.toString();
if (ignoreCase) {
cstStr = cstStr.toLowerCase();
}
if (type == expectedType) {
if (equal ? cstStr.equals(findCst) : cstStr.contains(findCst)) {
switch (type) {
case 0:
lin.cst = replaceWith;
break;
case 1:
lin.cst = Float.parseFloat(replaceWith);
break;
case 2:
lin.cst = Double.parseDouble(replaceWith);
break;
case 3:
lin.cst = Long.parseLong(replaceWith);
break;
case 4:
lin.cst = Integer.parseInt(replaceWith);
break;
}
i++;
}
}
}
}
}
}
JByteMod.LOGGER.log(i + " ldc's replaced");
}
}
public void performAction () {
ResourceBundle bundle = NbBundle.getBundle (AddJspWatchAction.class);
JPanel panel = new JPanel();
panel.getAccessibleContext ().setAccessibleDescription (bundle.getString ("ACSD_WatchPanel")); // NOI18N
JTextField textField;
JLabel textLabel = new JLabel (bundle.getString ("CTL_Watch_Name")); // NOI18N
textLabel.setBorder (new EmptyBorder (0, 0, 0, 10));
panel.setLayout (new BorderLayout ());
panel.setBorder (new EmptyBorder (11, 12, 1, 11));
panel.add ("West", textLabel); // NOI18N
panel.add ("Center", textField = new JTextField (25)); // NOI18N
textField.getAccessibleContext ().setAccessibleDescription (bundle.getString ("ACSD_CTL_Watch_Name")); // NOI18N
textField.setBorder (
new CompoundBorder (textField.getBorder (),
new EmptyBorder (2, 0, 2, 0))
);
textLabel.setDisplayedMnemonic (
bundle.getString ("CTL_Watch_Name_Mnemonic").charAt (0) // NOI18N
);
String t = null;//Utils.getELIdentifier();
// Utils.log("Watch: ELIdentifier = " + t);
boolean isScriptlet = Utils.isScriptlet();
Utils.log("Watch: isScriptlet: " + isScriptlet);
if ((t == null) && (isScriptlet)) {
t = Utils.getJavaIdentifier();
Utils.log("Watch: javaIdentifier = " + t);
}
if (t != null) {
textField.setText(t);
} else {
textField.setText(watchHistory);
}
textField.selectAll ();
textLabel.setLabelFor (textField);
textField.requestFocus ();
org.openide.DialogDescriptor dd = new org.openide.DialogDescriptor (
panel,
bundle.getString ("CTL_Watch_Title") // NOI18N
);
dd.setHelpCtx (new HelpCtx ("debug.add.watch"));
Dialog dialog = DialogDisplayer.getDefault ().createDialog (dd);
dialog.setVisible(true);
dialog.dispose ();
if (dd.getValue() != org.openide.DialogDescriptor.OK_OPTION) return;
String watch = textField.getText();
if ((watch == null) || (watch.trim ().length () == 0)) {
return;
}
String s = watch;
int i = s.indexOf (';');
while (i > 0) {
String ss = s.substring (0, i).trim ();
if (ss.length () > 0)
DebuggerManager.getDebuggerManager ().createWatch (ss);
s = s.substring (i + 1);
i = s.indexOf (';');
}
s = s.trim ();
if (s.length () > 0)
DebuggerManager.getDebuggerManager ().createWatch (s);
watchHistory = watch;
// open watches view
// new WatchesAction ().actionPerformed (null); TODO
}
private void startClientAsync(final JTextField lServerAddressTextField)
{
try
{
mErrorTextArea.setText("");
final String lServerAddress = lServerAddressTextField.getText();
final int lTCPPort = Integer.parseInt(mTCPPortTextField.getText());
final int lWindowSize = Integer.parseInt(mWindowSizeField.getText());
final int lBytesPerVoxel = Integer.parseInt(mBytesPerVoxelTextField.getText());
final boolean lTimeShiftMultiChannel = mTimeShiftAndMultiChannelCheckBox.isSelected();
final boolean lChannelFilter = mChannelFilterCheckBox.isSelected();
final int lNumberOfLayers = Integer.parseInt(mNumberOfColorsField.getText());
final Runnable lStartClientRunnable = new Runnable()
{
@Override
public void run()
{
mClearVolumeTCPClientHelper.startClient(mVolumeCaptureListener,
lServerAddress,
lTCPPort,
lWindowSize,
lBytesPerVoxel,
lNumberOfLayers,
lTimeShiftMultiChannel,
lChannelFilter,
appicon);
}
};
final Thread lStartClientThread = new Thread( lStartClientRunnable,
"StartClientThread" + lServerAddressTextField.getText());
lStartClientThread.setDaemon(true);
lStartClientThread.start();
}
catch (final Throwable e)
{
mClearVolumeTCPClientHelper.reportErrorWithPopUp( e,
e.getLocalizedMessage());
e.printStackTrace();
}
}
/**
* Create a simple multi input pane, that returns what the use inserts.
*
* @param parentComponent
* @param title
* the dialog title.
* @param labels
* the labels to set.
* @param defaultValues
* a set of default values.
* @param fields2ValuesMap a map that allows to set combos for the various options.
* @return the result inserted by the user.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static String[] showMultiInputDialog( Component parentComponent, String title, String[] labels, String[] defaultValues,
HashMap<String, String[]> fields2ValuesMap ) {
Component[] valuesFields = new Component[labels.length];
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(900, labels.length * 70));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
String input[] = new String[labels.length];
panel.setLayout(new GridLayout(labels.length, 2, 5, 5));
for( int i = 0; i < labels.length; i++ ) {
panel.add(new JLabel(labels[i]));
boolean doneCombo = false;
if (fields2ValuesMap != null) {
String[] values = fields2ValuesMap.get(labels[i]);
if (values != null) {
JComboBox<String> valuesCombo = new JComboBox<>(values);
valuesFields[i] = valuesCombo;
panel.add(valuesCombo);
if (defaultValues != null) {
valuesCombo.setSelectedItem(defaultValues[i]);
}
doneCombo = true;
}
}
if (!doneCombo) {
valuesFields[i] = new JTextField();
panel.add(valuesFields[i]);
if (defaultValues != null) {
((JTextField) valuesFields[i]).setText(defaultValues[i]);
}
}
}
// JScrollPane scrollPane = new JScrollPane(panel);
// scrollPane.setPreferredSize(new Dimension(800, 300));
int result = JOptionPane.showConfirmDialog(parentComponent, panel, title, JOptionPane.OK_CANCEL_OPTION);
if (result != JOptionPane.OK_OPTION) {
return null;
}
for( int i = 0; i < labels.length; i++ ) {
if (valuesFields[i] instanceof JTextField) {
JTextField textField = (JTextField) valuesFields[i];
input[i] = textField.getText();
}
if (valuesFields[i] instanceof JComboBox) {
JComboBox<String> combo = (JComboBox) valuesFields[i];
input[i] = combo.getSelectedItem().toString();
}
}
return input;
}
/**
* Add a new curve to the curve list
*/
protected void AddCurve() {
if (!bEditMode) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel(bundle.getString("frmEditCurve.AddCurvePanel.name.text")));
JTextField tfName = new JTextField("");
panel.add(tfName);
int result = JOptionPane.showConfirmDialog(this, panel,
bundle.getString("frmEditCurve.AddCurvePanel.title"), JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if ((result == JOptionPane.OK_OPTION) && (!tfName.getText().isEmpty())) {
if (Utils.FileExist(
Utils.getSelectedCurveFolder(CgConst.CURVE_FOLDER_USER) + tfName.getText() + ".par")) {
JOptionPane.showMessageDialog(this, bundle.getString("frmEditCurve.AddCurvePanelPanel.fileexist"));
return;
}
// -- Add the 2 extreme points to the list and sort the list (not really
// necessary...)
param = new ParamData();
param.name = tfName.getText();
param.data.add(new CgParam(-50.0, "0"));
param.data.add(new CgParam(50.0, "0"));
Collections.sort(param.data);
// -- Update
tablemodel.setParam(param);
Old_Paramfile = Paramfile;
Paramfile = param.name;
bEditMode = true;
ChangeEditStatus();
RefreshView();
settings.SelectedCurveFolder = CgConst.CURVE_FOLDER_USER;
UpdateSelBtStatus();
RefreshCurveList(Utils.getSelectedCurveFolder(settings.SelectedCurveFolder));
}
}
}