Хорошо, позвольте мне перефразировать мой вопрос:System.out.println (NOT_AN_EMPTY_STRING); не распечатывая пустую строку (иначе ничего)
Код:
System.out.println("Message is:" + focusOwner + focusOwner.getPage() == null + focusOwner.getText());
Выход:
false
Альтернативный код:
System.out.println("Message is:" + focusOwner);
Выход:
Message is:pscript.gui.elements.Answer[,0,98,639x22,invalid,layout=net.miginfocom.swing.MigLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synt[email protected],flags=9,maximumSize=,minimumSize=,preferredSize=]
Некоторые факты:
focusOwner является класс ответа, который расширяет элемент, который расширяет JPanel. Метод toString() никогда не переоценивается. Доказательство:
public class Answer extends Element
{
private static final long serialVersionUID = 1L;
private JLabel letter;
private JCheckBox check;
private Question question;
//getter and setters
void setQuestion(Question question)
{
this.question = question;
}
public Question getQuestion()
{
return question;
}
JLabel getLetter()
{
return letter;
}
public boolean isCorrect()
{
return check.isSelected();
}
public String getLetterText()
{
return letter.getText();
}
//navigational methods
@Override
public Element getPreviousElement()
{
Element previousElement = getQuestion().getPreviousAnswer((Answer) getElement());
if (previousElement != null)
{
return previousElement;
}
else
{
return getQuestion();
}
}
@Override
public Element getNextElement()
{
Element nextElement = getQuestion().getNextAnswer((Answer) getElement());
if (nextElement != null)
{
return nextElement;
}
else
{
nextElement = getPage().getNextElement(getQuestion());
if (nextElement != null)
{
return nextElement;
}
else
{
Page nextPage = getChapter().getNextPage(getPage());
if (nextPage != null)
{
return nextPage.getLastElement().lastElement();
}
else
{
Chapter nextChapter = getDocument().getNextChapter(getChapter());
if (nextChapter != null)
{
return nextChapter.getTitle();
}
else
{
return getDocument().getChapter(1).getTitle();
}
}
}
}
}
//other methods
private Element addNextElement()
{
if (getQuestion().getAnswerCount() < 5)
{
return addNextAnswer();
}
else
{
return addNextQuestion();
}
}
private Answer addNextAnswer()
{
Answer nextAnswer = new Answer();
getQuestion().addAnswer(nextAnswer, getQuestion().getAnswerIndex((Answer) getElement())+1);
getQuestion().rewriteLetters();
return nextAnswer;
}
private Question addNextQuestion()
{
Question nextQuestion = new Question();
getPage().addElement(nextQuestion, getPage().getElementIndex(getQuestion())+1);
getChapter().rewriteNumbers();
return nextQuestion;
}
private Element removeAnswer()
{
Element previousElement = getPreviousElement();
Question question = getQuestion();
question.removeAnswer((Answer)getElement());
question.rewriteLetters();
return previousElement;
}
private void checkLoop()
{
Question question = getQuestion();
if (question != null)
{
getDocument().setSaved(false);
if ((check.isSelected()) && (question.checkFlag == false))
{
question.checkFlag = true;
int answerCount = question.getAnswerCount();
for (int i = 1; i <= answerCount; i++)
{
question.getAnswer(i).check.setSelected(false);
}
check.setSelected(true);
question.checkFlag = false;
}
}
}
//actions
@Override
void primaryAction()
{
addNextElement().takeFocus();
}
@Override
void secondaryAction()
{
addNextQuestion().takeFocus();
}
@Override
void deleteAction()
{
removeAnswer().takeFocus();
}
//constructors
Answer()
{
super();
setBackground(Color.WHITE);
//TODO
check = new JCheckBox();
check.setBackground(Color.WHITE);
check.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent arg0)
{
checkLoop();
}
});
add(check, "top, gapleft " + LayoutConstants.CHECK_SPACE_LEFT + ", gaptop "+ LayoutConstants.CHECK_ABOVE + ", w " + LayoutConstants.CHECK_WIDTH);
letter = new JLabel("a)", SwingConstants.LEFT);
letter.setFont(Main.otherFont);
letter.setBackground(Color.WHITE);
add(letter, "top, gaptop " + LayoutConstants.LETTER_ABOVE + ", w " + LayoutConstants.LETTER_WIDTH);
getTextBox().setMargin(LayoutConstants.ANSWER_INSETS);
add(getTextBox(), "span, grow, push, w " + LayoutConstants.ANSWERBOX_WIDTH);
}
public Answer(String text, boolean correct)
{
this();
getTextBox().setText(text);
check.setSelected(correct);
}
}
Элемент:
public class Element extends JPanel
{
private static final long serialVersionUID = 1L;
private JTextArea textBox = new JTextArea();
private Page page = null;
private InputMap inputM = getTextBox().getInputMap();
private ActionMap actionM = getTextBox().getActionMap();
//getter and setters
Element getElement()
{
return this;
}
void setPage(Page page)
{
this.page = page;
}
public Page getPage()
{
return page;
}
Chapter getChapter()
{
return getPage().getChapter();
}
Document getDocument()
{
return getChapter().getDocument();
}
public JTextArea getTextBox()
{
return textBox;
}
public String getText()
{
return getTextBox().getText();
}
public void setText(String text)
{
getTextBox().setText(text);
}
public boolean isEmpty()
{
return getTextBox().getText().equals("");
}
//other methods
public void takeFocus()
{
getDocument().setFocusOwner(getElement());
scrollRectToVisible(getTextBox().getBounds());
getTextBox().grabFocus();
}
void addListener()
{
AbstractDocument document = (AbstractDocument) getTextBox().getDocument();
document.addDocumentListener(new DocumentListener()
{
@Override
public void changedUpdate(DocumentEvent e)
{
getDocument().setSaved(false);
}
@Override
public void insertUpdate(DocumentEvent e)
{
getDocument().setSaved(false);
}
@Override
public void removeUpdate(DocumentEvent e)
{
getDocument().setSaved(false);
}
});
}
Element lastElement()
{
if (getElement() instanceof Question)
{
if (((Question) getElement()).getAnswerCount() != 0)
{
return ((Question) getElement()).getLastAnswer();
}
}
return getElement();
}
//navigational methods
public Element getPreviousElement()
{
return null;
}
public Element getNextElement()
{
return null;
}
//actions
void primaryAction() {}
void secondaryAction() {}
private void tertiaryAction()
{
Chapter chapter = getChapter();
int chapterIndex = getDocument().getChapterIndex(chapter);
new CreateChapterDialog(getDocument(), chapterIndex+1); //TOD quaternary maybe??
getDocument().setKeyPressed(false);
}
void deleteAction() {}
private void upAction()
{
getPreviousElement().takeFocus();
}
private void downAction()
{
getNextElement().takeFocus();
}
//constructors
Element()
{
setLayout(new MigLayout("insets 0, gap 0!"));
getTextBox().setLineWrap(true);
getTextBox().setWrapStyleWord(true);
getTextBox().addKeyListener(new KeyAdapter()
{
@Override
public void keyReleased(KeyEvent e)
{
getDocument().setKeyPressed(false);
}
});
CustomDocumentFilter filter;
if (this instanceof Title)
{
getTextBox().setFont(Main.titleFont);
filter = new CustomDocumentFilter(250);
}
else if (this instanceof Question)
{
getTextBox().setFont(Main.questionFont);
filter = new CustomDocumentFilter(500);
}
else
{
getTextBox().setFont(Main.otherFont);
filter = new CustomDocumentFilter(500);
}
AbstractDocument document = (AbstractDocument) getTextBox().getDocument();
document.setDocumentFilter(filter);
//primary action
inputM.put(KeyStroke.getKeyStroke("ENTER"), "enter");
actionM.put("enter", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent arg0)
{
if (!getDocument().isKeyPressed())
{
getDocument().setKeyPressed(true);
getDocument().setSaved(false);
primaryAction();
}
}
});
//secondary action
inputM.put(KeyStroke.getKeyStroke("shift ENTER"), "pressedShiftEnter");
actionM.put("pressedShiftEnter", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if (!getDocument().isKeyPressed())
{
getDocument().setKeyPressed(true);
getDocument().setSaved(false);
secondaryAction();
}
}
});
//tertiary action
inputM.put(KeyStroke.getKeyStroke("control ENTER"), "pressedCtrlEnter");
actionM.put("pressedCtrlEnter", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if (!getDocument().isKeyPressed())
{
getDocument().setKeyPressed(true);
getDocument().setSaved(false);
tertiaryAction();
}
}
});
//up action
inputM.put(KeyStroke.getKeyStroke("shift TAB"), "shiftTab");
actionM.put("shiftTab", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
upAction();
}
});
//down action
inputM.put(KeyStroke.getKeyStroke("TAB"), "Tab");
actionM.put("Tab", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
downAction();
}
});
//delete action
inputM.put(KeyStroke.getKeyStroke("shift DELETE"), "shiftDelete");
actionM.put("shiftDelete", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if (!getDocument().isKeyPressed())
{
getDocument().setKeyPressed(true);
getDocument().setSaved(false);
deleteAction();
}
}
});
getTextBox().addFocusListener(new FocusAdapter()
{
@Override
public void focusGained(FocusEvent e)
{
getDocument().setFocusOwner(getElement());
}
});
}
}
focusOwner.getPage() возвращает один из его частных переменных, что является или не является нулевым (в данном случае это не так).
focusOwner.getText() вызывает метод getText() JTextArea, включенный в класс, и возвращает возвращаемое значение (которое в данном случае является пустой строкой).
Существует. Это самое близкое к SSCCE, которое я могу вам дать.
EDIT:
Как это объяснить:
System.out.println("Message is:" + focusOwner + focusOwner.getPage() == null + focusOwner.getText());
System.out.println("Message is:" + focusOwner);
возвращение этого:
false
Message is:pscript.gui.elements.Answer[,0,98,639x22,invalid,layout=net.miginfocom.swing.MigLayout,alignmentX=0.0,alignmentY=0.0,[email protected],flags=9,maximumSize=,minimumSize=,preferredSize=]
Мы говорим о значении той же переменной печатается в два ПОДРЯД строки кода, и он НЕ ИМЕЕТ ТОЛЬКО ЗНАЧЕНИЕ.
, что ваша проблема? – nachokk
Давай теперь .... Где твоя [sscce] (http://sscce.org)? Если вы не можете создать sscce, то вы не выделили свою проблему ... и мы тоже не можем, если вы ** не заставляете нас сами создавать SSCCE, что действительно не справедливо для нас, поскольку мы «Добровольцы, не так ли? Положите несколько усилий или просто забудьте об этом и удалите этот вопрос. –
Вы показали нам вывод для конкатенации строк и булевского выражения и для некоторого объекта. Где происходит вывод * ничего * (как говорит ваш заголовок)? –