Александр's questions
请告诉我,是否有时间间隔,例如
Period period = Period.of(5,3,15);
有必要对指定的时间段应用 0.5 的系数,即将它分成两半,如何做到这一点?
上面的方法返回一个零区间,虽然周期的计算是正确的,告诉我错误是什么。
private Period kavendarVisl(DefaultTableModel dtm)
{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
Period period = Period.ZERO;
Period smalPeriod;
for (int row=0;row<dtm.getRowCount();row++)
{
LocalDate ld1=LocalDate.parse(dtm.getValueAt(row,0).toString(),formatter);
LocalDate ld2 = LocalDate.now();
if (!dtm.getValueAt(row,1).toString().equals(""))
{
ld2=LocalDate.parse(dtm.getValueAt(row,1).toString(),formatter);
}
smalPeriod = Period.between(ld1,ld2);
period.plus(smalPeriod);
System.out.println(smalPeriod.getYears() + " - " + smalPeriod.getMonths());
}
System.out.println(period.getYears() +" - " +period.getMonths());
return period;
}
告诉我有一个表格
public class MainFrame extends JFrame {
private int colThread=0;
MainThread mt=new MainThread("Поток - 1");
public MainFrame()
{
setSize(300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable jTable=new JTable(20,4);
jTable.setRowHeight(20);
jTable.addMouseListener(new RightMouse());
add(jTable);
}
}
还有一个右键监听类
public class RightMouse extends MouseAdapter{
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if (e.getButton()==MouseEvent.BUTTON3)
{
JPopupMenu popupMenu = new TableMenu(e);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
private class TableMenu extends JPopupMenu
{
JMenuItem anMenu;
public TableMenu(MouseEvent event) {
this.anMenu = new JMenuItem("Увеличить ширину строки");
add(anMenu);
this.anMenu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (event.getComponent() instanceof JTable)
{
JTable table = (JTable) event.getComponent();
try {
table.setRowHeight(table.getRowHeight() + 10);
}catch (IllegalArgumentException err)
{
table.setRowHeight(10);
}
}
}
});
this.anMenu = new JMenuItem("Уменьшить ширину строки");
add(anMenu);
this.anMenu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (event.getComponent() instanceof JTable)
{
JTable table = (JTable) event.getComponent();
try {
table.setRowHeight(table.getRowHeight() - 10);
}catch (IllegalArgumentException err)
{
table.setRowHeight(10);
}
}
}
});
}
}
}
问题是我怎样才能改变某一行的高度,鼠标指针当前可以在该行上,而不是表中的所有行
请告诉我有一个表格
public class MainFrame extends JFrame {
private int colThread=0;
MainThread mt=new MainThread("Поток - 1");
public MainFrame()
{
setSize(300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
JButton jb=new JButton("Запустить поток");
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jb.setText("Перезапустить поток");
colThread = colThread + 1;
if (!mt.isInterrupted())
{
mt.interrupt();
}
mt.start();
}
});
jp.add(jb);
add(jp);
}
}
有一个流类:
public class MainThread extends Thread{
private int summ;
private String threadName;
public MainThread(String threadName)
{
this.threadName = threadName;
}
@Override
public void run() {
summ = 0;
while(true)
{
summ = summ +1;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.threadName + " " + summ);
}
}
}
和主要课程:
public class MainClass {
public static void main(String[] args) {
MainFrame mf = new MainFrame();
mf.setVisible(true);
}
}
问题是如何在单击按钮时重新启动线程的执行。以这种形式执行程序时,会出现错误,不过这是可以理解的,因为线程在工作,不清楚为什么interrupt()不起作用?
我正在尝试通过动态 Web 项目在 Eclipse 中创建一个 servlet
//@WebServlet("/hello_world")
public class FirstServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw=response.getWriter();
pw.println("<html>");
pw.println("<h1> Hello World </h1>");
pw.println("</html>");
}
}
在 WEB-INF 文件夹中创建了以下 web.xlm 文件:
<?xml version="1.0" ecoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/hello_world</url-pattern>
</servlet-mapping>
</web-app>
Tomcat 连接到 8081 端口。我正在尝试对 URL http://localhost:8081/hello_world进行 servlet 调用,但事实证明需要通过项目名称调用它,而 web.xml 确实如此根本不工作。请告诉我有什么问题。
这种方式如何替换IDE中的部分代码,比如我决定进入
DefaultTableModel dtm=view.getZPJPanel().getPeriodDTM();
如何将整个代码中的所有内容都更改为dtm view.getZPJPanel().getPeriodDTM();
请告诉我,在上面的代码中,JDialog对象的左上角是放在屏幕中心的,我需要对象的中心在屏幕中心
public class RaschetDialog {
public static void main(String[] args) {
JDialog raschetDialog=new JDialog();
raschetDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
raschetDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
raschetDialog.setLocationRelativeTo(null);
raschetDialog.setSize(600,400);
raschetDialog.setVisible(true);
raschetDialog.dispose();
for (int i=0;i<1000;i++){
System.out.println(i);
}
}
}
手动输入日期时出错
线程“AWT-EventQueue-0”中的异常 java.lang.ClassCastException:java.util.Date 无法转换为 java.util.Calendar
如何改进代码以便手动输入和使用下拉日历成为可能?
public class WordWorker {
public static void main(String[] args) {
Locale locale=new Locale("ru","RU");
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(300,300);
UtilDateModel model=new UtilDateModel();
Properties p=new Properties();
p.put("text.today","Today");
p.put("text.month","Month");
p.put("text.year","Year");
JDatePanelImpl datePanel=new JDatePanelImpl(model,p);
JDatePickerImpl datePicker=new JDatePickerImpl(datePanel,new DateLabelFormatter());
datePicker.setTextEditable(true);
frame.add(datePicker,"Center");
JButton jButton=new JButton("Кнопка");
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(datePicker.getModel().getDay());
System.out.println(datePicker.getModel().getMonth()+1);
System.out.println(datePicker.getModel().getYear());
System.out.println(datePicker.getModel().getValue());
}
});
frame.add(jButton,"South");
frame.setVisible(true);
}
private static class DateLabelFormatter extends JFormattedTextField.AbstractFormatter
{
private String datePattern="dd.MM.yyyy";
private SimpleDateFormat dateFormatter=new SimpleDateFormat(datePattern);
@Override
public Object stringToValue(String text) throws ParseException {
return dateFormatter.parseObject(text);
}
@Override
public String valueToString(Object value) throws ParseException {
if (value!=null)
{
Calendar cal= (Calendar) value;
return dateFormatter.format(cal.getTime());
}
return "";
}
}
}
试图创建我自己的对话框
public class InformJDialog extends JDialog {
private String title;
public InformJDialog(String title) {
this.title = "<html><font size=6 color=black>"+title;
this.setSize(180,120);
this.setUndecorated(true);
this.setLocationRelativeTo(null);
this.setLayout(new BorderLayout());
this.setModal(true);
JLabel jLabel=new JLabel(this.title);
jLabel.setVerticalAlignment(SwingConstants.CENTER);
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
this.add(jLabel,BorderLayout.CENTER);
}
}
但是,与控制按钮一起,框架也被禁用,告诉我如何离开框架或创建自己的框架。谢谢你。
告诉我如何比较 ImageIcon 类的两个对象,如果它们包含相同的图片,则为真。谢谢你。
请告诉我,有一个序列化类,其中需要重写方法,例如toString,重写之前序列化的类后对象没有反序列化,我该如何解决这个问题?
有一个自定义类
public class Man implements Serializable{
private HashMap<Object,Object> manMap;
public HashMap<Object, Object> getManMap() {
return manMap;
}
public void setManMap(HashMap<Object, Object> manMap) {
this.manMap = manMap;
}
}
有一些代码
Man man11=new Man();
HashMap<Object,Object> dannie=new HashMap<>();
dannie.put("Фамилия","Иванов");
dannie.put("Имя","Иван");
dannie.put("Отчество","Иванович");
man11.setManMap(dannie);
Man msn22=man11;
dannie.put("Фамилия","Сидоров");
dannie.put("Имя","Сидор");
dannie.put("Отчество","Сидорович");
man11.setManMap(dannie);
System.out.println(msn22.getManMap().get("Фамилия").toString()+
msn22.getManMap().get("Имя").toString()+
msn22.getManMap().get("Отчество").toString());
请告诉我如何创建不随对象更改的对象的副本。需要使副本保持与更改前对象相同的状态吗?
告诉:
HashMap<String,String>data=new HashMap<>();
data.put("Имя","Вася");
data.put("Фамилия","Иванов");
HashMap<String,String>data11=data;
data.put("Имя","Петя");
System.out.println(data11.get("Имя"));
我怎样才能让第二次Map
保存价值?
请告诉我有一个单元格范围,有必要使用 Apache POI 显示该范围的所有内部边界
CellRangeAddress region=new
CellRangeAddress(7,9,0,4);
RegionUtil.setBorderRight(BorderStyle.MEDIUM,region,sheet);
RegionUtil.setBorderLeft(BorderStyle.MEDIUM,region,sheet);
RegionUtil.setBorderBottom(BorderStyle.MEDIUM,region,sheet);
RegionUtil.setBorderTop(BorderStyle.MEDIUM,region,sheet);
上面的代码显示了外部边框,但内部边框是必须的,我知道你可以为范围的每个单元格创建一个样式并遍历所有,但我认为有一个更合理的方式。谢谢你。
告诉我,在技术上是否可以使用 Apache Poi 将 ImageIcon 图像插入 Word 文档?
下午好,告诉我如何在编辑单元格中的数据后从单元格中获取值?在这个例子中,没有变化
public class PP extends JDialog {
public PP() {
setDefaultCloseOperation(HIDE_ON_CLOSE);
setTitle("паспортные данные");
setSize(400,220);
setLocationRelativeTo(null);
setVisible(true);
add(pasportJTable());
JButton addJButton=new ADDButton();
add(addJButton,"South");
}
private JTable pasportJTable() {
String[] dannie = new String[]{
"Серия паспорта", "Номер паспорта","Дата выдачи паспорта", "Кем выдан паспорт",
"Код подразделения",
"Адрес регистрации", "Дата регистрации",
};
JTable pasportJTable = new JTable(7,2);
pasportJTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
pasportJTable.setRowHeight(20);
pasportJTable.setOpaque(false);
pasportJTable.getColumnModel().getColumn(0).setPreferredWidth(140);
pasportJTable.getColumnModel().getColumn(0).setMaxWidth(140);
pasportJTable.getColumnModel().getColumn(0).setWidth(140);
for(int i=0;i<dannie.length;i++)
{
pasportJTable.setValueAt(dannie[i],i,0);
pasportJTable.setValueAt("Не изменен",i,1);
}
return pasportJTable;
}
private class ADDButton extends JButton
{
public ADDButton() {
super("Изменить");
setFocusPainted(false);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i=0;i<pasportJTable().getRowCount();i++)
{
System.out.println(pasportJTable().getModel().getValueAt(i,0)+" - "+
pasportJTable().getModel().getValueAt(i,1));
PP.this.setVisible(false);
PP.this.dispose();
}
}
});
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PP();
}
});
}
}
请告诉我。JTable 表的列存在以下性质的问题,使用了一个编辑器,该编辑器又返回一个 JScrollPane 对象(或任何其他容器),上面有一个 JTextArea 对象,因此使用键盘进行编辑时,无法在 JTextArea 中输入任何值,因为它不是嵌套对象接收焦点(需要单击鼠标)。如何将焦点放在嵌套对象上?
public class PP extends JFrame {
private String data[][]=new String[][]{{"","",""},{"","",""}};
private String column[]=new String[]{"Фамилия","Имя","Отчество"};
public PP() throws HeadlessException {
super("Кадровая работа");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setExtendedState(MAXIMIZED_BOTH);
this.setVisible(true);
JTable jTable=new JTable(data,column);
jTable.setRowHeight(40);
jTable.getColumnModel().getColumn(1).setCellEditor(new EditorJTA());
this.add(new JScrollPane(jTable));
}
private class EditorJTA extends AbstractCellEditor
implements TableCellEditor {
private JTextArea editor = new JTextArea();
private JScrollPane result=new JScrollPane(editor);
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
editor.setLineWrap(true);
editor.setWrapStyleWord(true);
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
stopCellEditing();
}
}
});
result.setBorder(new LineBorder(null, 0));
return result;
}
@Override
public Object getCellEditorValue() {
return editor.getText();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PP();
}
});
}
}
美好的一天,告诉我,在我创建的表格中,在编辑单元格时,之前的值下降了,怎么办,当你用鼠标输入它时,之前的值在 Excel 中会保持什么样的状态?
public class PP extends JFrame {
public PP() throws HeadlessException {
super("Кадровая работа");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setExtendedState(MAXIMIZED_BOTH);
add(levayaJTable());
this.setVisible(true);
}
//Модель основной таблицы
private JTable levayaJTable() {
String[] dannie = new String[]{
"1. Фамилия", "2. Имя", "3. Отчество", "4. Личный номер", "5. Число, месяц, год рождения",
"6. Место рождения (согласно паспорта)", "7. Серия и номер паспорта", "8. Дата выдачи", "9. Кем выдан",
};
JTable levayaJTable = new JTable(new OsnovTable(dannie))
{
@Override
public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
super.changeSelection(rowIndex, 1, toggle, extend);
}
};
levayaJTable.setRowHeight(20);
levayaJTable.setOpaque(false);
levayaJTable.getColumnModel().getColumn(1)
.setCellEditor(new MaskEditor());
return levayaJTable;
}
//Модель основной таблицы
private class OsnovTable extends AbstractTableModel {
String[] dannie;
HashMap<String, String> data = new HashMap<>();
public OsnovTable(String[] dannie) {
this.dannie = dannie;
}
@Override
public int getRowCount() {
return dannie.length;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) return dannie[rowIndex];
if (columnIndex == 1) return data.get(dannie[rowIndex]);
return null;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (columnIndex == 0) return false;
if (columnIndex == 1) return true;
return false;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
data.put(dannie[rowIndex], (String) aValue);
fireTableCellUpdated(rowIndex, columnIndex);
}
}
//Создание редактора таблицы
private class MaskEditor extends AbstractCellEditor
implements TableCellEditor {
private JFormattedTextField editor;
public MaskEditor() {
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
MaskFormatter dateMask = null;
try {
if (table.getModel().getValueAt(row, 0).equals("5. Число, месяц, год рождения")
|| table.getModel().getValueAt(row, 0).equals("8. Дата выдачи")
|| table.getModel().getValueAt(row, 0).equals("12. Дата регистрации"))
{
dateMask = new MaskFormatter("##.##.####");
} else if (table.getModel().getValueAt(row, 0).equals("7. Серия и номер паспорта")) {
dateMask = new MaskFormatter("#### ######");
}else if (table.getModel().getValueAt(row, 0).equals("Код подразделения"))
{dateMask = new MaskFormatter("###-###");}
} catch (ParseException e) {
e.printStackTrace();
}
editor = new JFormattedTextField(dateMask);
editor.setBorder(new LineBorder(null, 0));
editor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stopCellEditing();
table.changeSelection(row+1,column,false,false);
}
});
return editor;
}
@Override
public Object getCellEditorValue() {
return editor.getText();
}
}
//Команда выхода из приложения
class ExitAction extends AbstractAction {
public ExitAction() {
putValue(NAME, "Выход");
}
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PP();
}
});
}
}
在上面的代码中,对表格单元格应用了不同的JFormattedTextField,问题是改变单元格中的值时,没有保存,请问如何解决这个问题?代码显示完整
public class KadrPress extends JFrame{
public KadrPress() throws HeadlessException {
super("Кадровая работа");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.add(lineMenu(),"North");
this.add(osnTabPane(),"Center");
this.setExtendedState(MAXIMIZED_BOTH);
this.setVisible(true);
}
//Создание меню
private JMenuBar lineMenu()
{
//Меню файл
JMenuBar lineMenu=new JMenuBar();
//Меню Файл
JMenu filemenu=new JMenu("Файл");
JMenuItem newFile=new JMenuItem("Создать");
JMenuItem openFile=new JMenuItem("Открыть");
JMenuItem saveFile=new JMenuItem("Сохранить");
filemenu.add(newFile);
filemenu.add(openFile);
filemenu.add(saveFile);
filemenu.addSeparator();
filemenu.add(new ExitAction());
lineMenu.add(filemenu);
return lineMenu;
}
//Создание основной панели с вкладками
private JTabbedPane osnTabPane()
{
JTabbedPane osnTabPane=new JTabbedPane();
osnTabPane.addTab("Общие сведения",osnovSvedeniyaJLabel());
osnTabPane.addTab("Лист 2",new JPanel());
return osnTabPane;
}
//Панель основные сведения
private JPanel osnovSvedeniyaJLabel()
{
JPanel osnovSvedeniyaJLabel=new JPanel();
osnovSvedeniyaJLabel.setLayout(new GridLayout(1,2));
osnovSvedeniyaJLabel.add(levayaJTable());
osnovSvedeniyaJLabel.add(new JLabel("2"));
return osnovSvedeniyaJLabel;
}
//Модель основной таблицы
private JTable levayaJTable ()
{
String[]dannie=new String[]{
"Фамилия","Имя","Отчество","Личный номер","Число, месяц, год рождения",
"Место рождения (согласно паспорта)","Серия и номер паспорта","Дата выдачи","Кем выдан",
"Код подразделения","Серия и номер удост. личности (Военного билета)","Дата выдачи(ВБ)",
"Кем выдано","ИНН"
};
JTable levayaJTable=new JTable(new OsnovTable(dannie));
levayaJTable.setRowHeight(20);
levayaJTable.setOpaque(false);
levayaJTable.getColumnModel().getColumn(1)
.setCellEditor(new MaskEditor(new JFormattedTextField()));
return levayaJTable;
}
//Модель основной таблицы
private class OsnovTable extends AbstractTableModel
{
String[]dannie;
HashMap<String,String>data=new HashMap<>();
public OsnovTable(String[]dannie) {
this.dannie=dannie;
}
@Override
public int getRowCount() {
return dannie.length;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex==0)return dannie[rowIndex];
if (columnIndex==1) return data.get(dannie[rowIndex]);
return null;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (columnIndex==0)return false;
if (columnIndex==1)return true;
return false;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
data.put(dannie[rowIndex], (String) aValue);
}
}
//Создание редактора таблицы
private class MaskEditor extends DefaultCellEditor
{
public MaskEditor(JTextField textField) {
super(textField);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JFormattedTextField result= (JFormattedTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);
MaskFormatter dateMask;
try
{
if (table.getModel().getValueAt(row,0).equals("Число, месяц, год рождения")
||table.getModel().getValueAt(row,0).equals("Дата выдачи"))
{
dateMask=new MaskFormatter("##.##.####");
result=new JFormattedTextField(dateMask);
}
if (table.getModel().getValueAt(row,0).equals("Серия и номер паспорта"))
{
dateMask=new MaskFormatter("#### ######");
result=new JFormattedTextField(dateMask);
}
result.setBorder(new LineBorder(null,0));
return result;
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
}
//Команда выхода из приложения
class ExitAction extends AbstractAction
{
public ExitAction() {
putValue(NAME,"Выход");
}
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new KadrPress();
}
});
}
}