gpt4 book ai didi

java - 如何在将字符串粘贴到 JSpinner 之前验证和修改它?

转载 作者:行者123 更新时间:2023-11-30 03:08:35 24 4
gpt4 key购买 nike

我有一个 JSpinner,其 SpinnerDateModel 的格式为“HH:mm”。我希望用户(例如)能够从表(或任何其他源)复制“yyyy-MM-dd HH:mm:ss.SSS”中的日期并将其粘贴到 JSpinner 中 - HH:mm仅部分。这样的完整日期字符串通常对组件无效,但我仍然想尝试粘贴的字符串并从中获取所需的信息(如果存在)...我认为我的验证方法应该如下所示,但我不知道如何更改 Paste() 行为,以便我可以添加验证和更改粘贴文本...

        private String validateAndReturnCorrected(String pastedText) {

DateFormat hoursMinutesFormat = new SimpleDateFormat("HH:mm");
try {
// trying to paste a full date string?
DateFormat fullDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = fullDateFormat.parse(pastedText);
return hoursMinutesFormat.format(date);
} catch (ParseException ex) {
}
// trying to paste hour and minutes?
try {
Date date = hoursMinutesFormat.parse(pastedText);
return hoursMinutesFormat.format(date);
} catch (ParseException ex1) {
}
// trying to paste date in HH:mm:ss format?
try {
DateFormat hoursMinutesSecondsFormat = new SimpleDateFormat("HH:mm:ss");
Date date = hoursMinutesSecondsFormat.parse(pastedText);
return hoursMinutesSecondsFormat.format(date);
} catch (ParseException ex2) {
}
// trying to paste date in HH:mm:ss.SSS format?
try {
DateFormat hoursMinutesSecondsMilisecondsFormat = new SimpleDateFormat("HH:mm:ss.SSS");
Date date = hoursMinutesSecondsMilisecondsFormat.parse(pastedText);
return hoursMinutesFormat.format(date);
} catch (ParseException ex3) {
}

// unable to correct the string...
return "";

}
<小时/>

更新

更改谷歌搜索问题后,我发现以下两个网站解决了问题:

所以解决方案看起来像这样:

class ProxyAction extends TextAction implements ClipboardOwner {

private TextAction action;

public ProxyAction(TextAction action) {
super(action.toString());
this.action = action;
}

@Override
public void actionPerformed(ActionEvent e) {
String cbc=getClipboardContents();
setClipboardContents(validateAndReturnCorrected(cbc));
action.actionPerformed(e);
setClipboardContents(cbc);
System.out.println("Paste Occured...............................................................");
}

// here goes the validateAndReturnCorrected method

public String getClipboardContents() {
String result = "";
try {
result = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException ex) {
ex.printStackTrace();
}
return result;
}

public void setClipboardContents(String aString) {
StringSelection stringSelection = new StringSelection(aString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, this);
}

@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
}
}

最佳答案

I want the user to be (for example) able to copy a date in "yyyy-MM-dd HH:mm:ss.SSS" from a table (or any other source) and paste it into the JSpinner - the HH:mm part only.

  • 这个简单的事情是在 JSpinners Xxx(Spinner)Model 中实现的。取决于 - SimpleDateFormat 是否添加到 JSpinner

  • 输入验证(SpinnerEditor)只是一个JFormattedTextField默认情况下(有关详细信息,请阅读 JFormattedTextFields 配置和 InputVerifier)

  • 例如(基础知识和标准,无需覆盖或设置特殊的东西),日期从 12 月 8 日更改为 12 月 10 日,时间从上午 10 点更改为上午 7 点。

enter image description here

.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.AbstractSpinnerModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerNumberModel;

public class JSpinnerTest {

public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 250;
private JFrame frame = new JFrame();
private JPanel mainPanel = new JPanel(new GridLayout(0, 3, 10, 10));
private JButton okButton = new JButton("Ok");
private JPanel buttonPanel = new JPanel();

public JSpinnerTest() {
buttonPanel.add(okButton);
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(0, 3, 10, 10));

JSpinner defaultSpinner = new JSpinner();
addRow("Default", defaultSpinner);
JSpinner boundedSpinner = new JSpinner(new SpinnerNumberModel(5, 0, 10, 0.5));
addRow("Bounded", boundedSpinner);
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
JSpinner listSpinner = new JSpinner(new SpinnerListModel(fonts));
addRow("List", listSpinner);
JSpinner reverseListSpinner = new JSpinner(new SpinnerListModel(fonts) {
private static final long serialVersionUID = 1L;

@Override
public Object getNextValue() {
return super.getPreviousValue();
}

@Override
public Object getPreviousValue() {
return super.getNextValue();
}
});
addRow("Reverse List", reverseListSpinner);
JSpinner dateSpinner = new JSpinner(new SpinnerDateModel());
addRow("Date", dateSpinner);
JSpinner betterDateSpinner = new JSpinner(new SpinnerDateModel());
String pattern = ((SimpleDateFormat) DateFormat.getDateInstance()).toPattern();
betterDateSpinner.setEditor(new JSpinner.DateEditor(betterDateSpinner, pattern));
addRow("Better Date", betterDateSpinner);
JSpinner timeSpinner = new JSpinner(new SpinnerDateModel());
pattern = ((SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.SHORT)).toPattern();
timeSpinner.setEditor(new JSpinner.DateEditor(timeSpinner, pattern));
addRow("Time", timeSpinner);
JSpinner permSpinner = new JSpinner(new PermutationSpinnerModel("meat"));
addRow("Word permutations", permSpinner);
frame.setTitle("SpinnerTest");
frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.add(mainPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

private void addRow(String labelText, final JSpinner spinner) {
mainPanel.add(new JLabel(labelText));
mainPanel.add(spinner);
final JLabel valueLabel = new JLabel();
mainPanel.add(valueLabel);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
Object value = spinner.getValue();
valueLabel.setText(value.toString());
}
});
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JSpinnerTest frame = new JSpinnerTest();

}
});
}
}

class PermutationSpinnerModel extends AbstractSpinnerModel {

private static final long serialVersionUID = 1L;

/**
* Constructs the model.
*
* @param w the word to permute
*/
public PermutationSpinnerModel(String w) {
word = w;
}

@Override
public Object getValue() {
return word;
}

@Override
public void setValue(Object value) {
if (!(value instanceof String)) {
throw new IllegalArgumentException();
}
word = (String) value;
fireStateChanged();
}

@Override
public Object getNextValue() {
int[] codePoints = toCodePointArray(word);
for (int i = codePoints.length - 1; i > 0; i--) {
if (codePoints[i - 1] < codePoints[i]) {
int j = codePoints.length - 1;
while (codePoints[i - 1] > codePoints[j]) {
j--;
}
swap(codePoints, i - 1, j);
reverse(codePoints, i, codePoints.length - 1);
return new String(codePoints, 0, codePoints.length);
}
}
reverse(codePoints, 0, codePoints.length - 1);
return new String(codePoints, 0, codePoints.length);
}

@Override
public Object getPreviousValue() {
int[] codePoints = toCodePointArray(word);
for (int i = codePoints.length - 1; i > 0; i--) {
if (codePoints[i - 1] > codePoints[i]) {
int j = codePoints.length - 1;
while (codePoints[i - 1] < codePoints[j]) {
j--;
}
swap(codePoints, i - 1, j);
reverse(codePoints, i, codePoints.length - 1);
return new String(codePoints, 0, codePoints.length);
}
}
reverse(codePoints, 0, codePoints.length - 1);
return new String(codePoints, 0, codePoints.length);
}

private static int[] toCodePointArray(String str) {
int[] codePoints = new int[str.codePointCount(0, str.length())];
for (int i = 0, j = 0; i < str.length(); i++, j++) {
int cp = str.codePointAt(i);
if (Character.isSupplementaryCodePoint(cp)) {
i++;
}
codePoints[j] = cp;
}
return codePoints;
}

private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

private static void reverse(int[] a, int i, int j) {
while (i < j) {
swap(a, i, j);
i++;
j--;
}
}
private String word;
}

关于java - 如何在将字符串粘贴到 JSpinner 之前验证和修改它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34151284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com