Witam.
Mam prośbe do was, ponieważ męczę się z tym problem i nie moge go zrobić a mianowicie chce żeby
liczenie wierszy bylo w TextEdit..
public class TextEdit extends QMainWindow
{
public TextEdit()
{
setWindowIcon(new QIcon("images/Notepad-16x16.png"));
QMenuBar menuBar = new QMenuBar();
setMenuBar(menuBar);
textEdit = new QTextEdit();
@SuppressWarnings("unused")
TextEdit syntaxHighlighter;
setupEditor();
setCentralWidget(textEdit);
try
{
createActions();
}
catch (Exception e)
{
e.printStackTrace();
}
createMenus();
createToolBars();
createStatusBar();
readSettings();
textEdit.document().contentsChanged.connect(this, "documentWasModified()");
setCurrentFile("");
}
public void closeEvent(QCloseEvent event)
{
if (maybeSave()) {
writeSettings();
event.accept();
} else {
event.ignore();
}
}
public void newFile()
{
if (maybeSave()) {
textEdit.clear();
setCurrentFile("");
}
//! [8] //! [9]
}
public void open()
{
if (maybeSave()) {
String fileName = QFileDialog.getOpenFileName(this);
if (fileName.length() != 0)
loadFile(fileName);
}
//! [10] //! [11]
}
public boolean save()
{
if (curFile.length() == 0) {
return saveAs();
} else
{
return saveFile(curFile);
}
}
public boolean saveAs()
{
String fileName = QFileDialog.getSaveFileName(this);
if (fileName.length() == 0)
return false;
return saveFile(fileName);
}
public void about()
{
QMessageBox.about (this,"O programie","<I></I><center><b><font color=#004faf>Text+</font></b><br /><br /><BIG>Wersja 1.0.0</BIG> " +
"<p></p>Copyright ©2009 by Kevin Ostajewski<small><p><small>Wszelkie prawa zastrzeżone.</p>" +
"<p>Nieautoryzowane rozpowszechnianie elementów <br />programu jest łamaniem praw autorskich.</p></small></center>");
}
public void documentWasModified()
{
setWindowModified(textEdit.document().isModified());
}
private void createActions()
{
newAct = new QAction(new QIcon(rsrcPath + "/New-16x16.png"), tr("&Nowy"), this);
newAct.setShortcut(new QKeySequence(tr("Ctrl+N")));
newAct.setStatusTip(tr("Tworzy nowy plik"));
newAct.triggered.connect(this, "newFile()");
openAct = new QAction(new QIcon(rsrcPath + "/folder-open-16x16 (1).png"), tr("&Otwórz"), this);
openAct.setShortcut(tr("Ctrl+O"));
openAct.setStatusTip(tr("Odwiera plik"));
openAct.triggered.connect(this, "open()");
saveAct = new QAction(new QIcon(rsrcPath + "/Save-16x16.png"), tr("&Zapisz"), this);
saveAct.setShortcut(tr("Ctrl+S"));
saveAct.setStatusTip(tr("Zapisuje dokument"));
saveAct.triggered.connect(this, "save()");
saveAsAct = new QAction(tr("Zapisz &jako"), this);
// saveAsAct.setStatusTip(tr("Save the document under a new name"));
saveAsAct.triggered.connect(this, "saveAs()");
exitAct = new QAction(new QIcon(rsrcPath + "/Log-Out-16x16.png"),tr("&Koniec"), this);
exitAct.setShortcut(tr("Ctrl+Q"));
exitAct.setStatusTip(tr("Zamyka program"));
exitAct.triggered.connect(this, "close()");
cutAct = new QAction(new QIcon(rsrcPath + "/Cut-16x16.png"), tr("&Wytnij"), this);
cutAct.setShortcut(tr("Ctrl+X"));
cutAct.setStatusTip(tr("Wytnij zaznaczony tekst"));
cutAct.triggered.connect(textEdit, "cut()");
copyAct = new QAction(new QIcon(rsrcPath + "/Copy-16x16.png"), tr("&Kopiuj"), this);
copyAct.setShortcut(tr("Ctrl+C"));
copyAct.setStatusTip(tr("Kopiuj zaznaczony tekst"));
copyAct.triggered.connect(textEdit, "copy()");
pasteAct = new QAction(new QIcon(rsrcPath + "/Paste-16x16.png"), tr("&Wklej"), this);
pasteAct.setShortcut(tr("Ctrl+V"));
pasteAct.setStatusTip(tr("Wklej zaznaczony tekst"));
pasteAct.triggered.connect(textEdit, "paste()");
aboutAct = new QAction(new QIcon(rsrcPath + "/help-16x16.png"), tr("&O programie"), this);
aboutAct.setStatusTip(tr("Informacje"));
aboutAct.triggered.connect(this, "about()");
cutAct.setEnabled(false);
copyAct.setEnabled(false);
textEdit.copyAvailable.connect(cutAct, "setEnabled(boolean)");
textEdit.copyAvailable.connect(copyAct, "setEnabled(boolean)");
}
private void createMenus()
{
fileMenu = menuBar().addMenu(tr("&Plik"));
fileMenu.addAction(newAct);
fileMenu.addAction(openAct);
fileMenu.addAction(saveAct);
fileMenu.addAction(saveAsAct);
fileMenu.addSeparator();
fileMenu.addAction(exitAct);
editMenu = menuBar().addMenu(tr("&Edycja"));
editMenu.addAction(cutAct);
editMenu.addAction(copyAct);
editMenu.addAction(pasteAct);
menuBar().addSeparator();
helpMenu = menuBar().addMenu(tr("&Pomoc"));
helpMenu.addAction(aboutAct);
helpMenu.addSeparator();
}
private void createToolBars()
{
fileToolBar = addToolBar(("Plik"));
fileToolBar.addAction(newAct);
fileToolBar.addAction(openAct);
fileToolBar.addAction(saveAct);
editToolBar = addToolBar(tr("Edycja"));
editToolBar.addAction(cutAct);
editToolBar.addAction(copyAct);
editToolBar.addAction(pasteAct);
}
private void createStatusBar()
{
statusBar().showMessage(tr("Gotowy"));
}
private void readSettings()
{
QSettings settings = new QSettings("Nokia", "Application Example");
QPoint pos = QVariant.toPoint(settings.value("pos", new QPoint(200, 200)));
QSize size = QVariant.toSize(settings.value("size", new QSize(400, 400)));
resize(size);
move(pos);
}
private void writeSettings()
{
QSettings settings = new QSettings("Nokia", "Application Example");
settings.setValue("pos", pos());
settings.setValue("size", size());
}
//! [24]
private boolean maybeSave()
{
if (textEdit.document().isModified()) {
QMessageBox.StandardButton ret = QMessageBox.warning(this, tr("Text+"),
tr("Niniejszy dokument został zmodyfikowany.\n" +
"Zapisać zmiany ?"),
new QMessageBox.StandardButtons(QMessageBox.StandardButton.Ok,
QMessageBox.StandardButton.Discard,
QMessageBox.StandardButton.Cancel));
if (ret == QMessageBox.StandardButton.Ok) {
return save();
} else if (ret == QMessageBox.StandardButton.Cancel) {
return false;
}
}
return true;
//! [24] //! [25]
}
//! [25]
//! [26]
public void loadFile(String fileName)
{
QFile file = new QFile(fileName);
if (!file.open(new QFile.OpenMode(QFile.OpenModeFlag.ReadOnly, QFile.OpenModeFlag.Text))) {
QMessageBox.warning(this, tr("Text+"), String.format(tr("Nie może odczytać pliku %1$s:\n%2$s."), fileName, file.errorString()));
return;
}
//! [26] //! [27]
QTextStream in = new QTextStream(file);
QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
textEdit.setPlainText(in.readAll());
QApplication.restoreOverrideCursor();
setCurrentFile(fileName);
statusBar().showMessage(tr("Gotowy"), 2000);
}
public boolean saveFile(String fileName)
{
QFile file = new QFile(fileName);
if (!file.open(new QFile.OpenMode(QFile.OpenModeFlag.WriteOnly, QFile.OpenModeFlag.Text))) {
QMessageBox.warning(this, tr("Text+"), String.format(tr("Nie może zapisać pliku %1$s:\n%2$s."), fileName, file.errorString()));
return false;
}
QTextStream out = new QTextStream(file);
QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
out.writeString(textEdit.toPlainText());
QApplication.restoreOverrideCursor();
setCurrentFile(fileName);
statusBar().showMessage(tr("Plik został zapisany"), 2000);
file.close();
return true;
}
public void setCurrentFile(String fileName)
{
curFile = fileName;
textEdit.document().setModified(false);
setWindowModified(false);
String shownName;
if (curFile.length() == 0)
shownName = "beznazwy.txt";
else
shownName = strippedName(curFile);
setWindowTitle(String.format(tr("%1$s[*] - %2$s"), shownName, tr("Text+")));
}
private static String strippedName(String fullFileName)
{
return new QFileInfo(fullFileName).fileName();
}
private void setupEditor() {
QFont font = new QFont();
font.setFamily("Courier");
font.setFixedPitch(true);
font.setPointSize(10);
textEdit = new QTextEdit();
textEdit.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap);
textEdit.setFont(font);
new Highlighter(textEdit.document());
}
private class Highlighter extends QSyntaxHighlighter {
public class HighlightingRule {
public QRegExp pattern;
public QTextCharFormat format;
public HighlightingRule(QRegExp pattern, QTextCharFormat format) {
this.pattern = pattern;
this.format = format;
}
}
Vector<HighlightingRule> highlightingRules = new Vector<HighlightingRule>();
QRegExp commentStartExpression;
QRegExp commentEndExpression;
QTextCharFormat keywordFormat = new QTextCharFormat();
QTextCharFormat classFormat = new QTextCharFormat();
QTextCharFormat commentFormat = new QTextCharFormat();
QTextCharFormat quotationFormat = new QTextCharFormat();
QTextCharFormat functionFormat = new QTextCharFormat();
public Highlighter(QTextDocument parent) {
super(parent);
HighlightingRule rule;
QBrush brush;
QRegExp pattern;
brush = new QBrush(QColor.blue,Qt.BrushStyle.SolidPattern);
keywordFormat.setForeground(brush);
keywordFormat.setFontWeight(QFont.Weight.Bold.value());
String[] keywords = { "abstract", "continue", "for", "new",
"switch", "assert", "default", "goto",
"package", "synchronized", "boolean",
"do", "if", "private", "this", "break",
"double", "implements", "protected",
"throw", "byte", "else", "import",
"public", "throws", "case", "enum",
"instanceof", "return", "transient",
"catch", "extends", "int", "short",
"try", "char", "final", "interface",
"static", "void", "class", "finally",
"long", "strictfp", "volatile", "const",
"float", "native", "super", "while" , "java" };
for (String keyword : keywords) {
pattern = new QRegExp("\\b" + keyword + "\\b");
rule = new HighlightingRule(pattern, keywordFormat);
highlightingRules.add(rule);
}
brush = new QBrush(QColor.darkMagenta);
pattern = new QRegExp("\\bQ[A-Za-z]+\\b");
classFormat.setForeground(brush);
classFormat.setFontWeight(QFont.Weight.Bold.value());
rule = new HighlightingRule(pattern, classFormat);
highlightingRules.add(rule);
brush = new QBrush(QColor.gray, Qt.BrushStyle.SolidPattern);
pattern = new QRegExp("//[^\n]*");
commentFormat.setForeground(brush);
rule = new HighlightingRule(pattern, commentFormat);
highlightingRules.add(rule);
brush = new QBrush(QColor.blue, Qt.BrushStyle.SolidPattern);
pattern = new QRegExp("\".*\"");
pattern.setMinimal(true);
quotationFormat.setForeground(brush);
rule = new HighlightingRule(pattern, quotationFormat);
highlightingRules.add(rule);
brush = new QBrush(QColor.darkGreen, Qt.BrushStyle.SolidPattern);
pattern = new QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
functionFormat.setForeground(brush);
functionFormat.setFontItalic(true);
rule = new HighlightingRule(pattern, functionFormat);
highlightingRules.add(rule);
commentStartExpression = new QRegExp("/\\*");
commentEndExpression = new QRegExp("\\*/");
}
public void highlightBlock(String text) {
for (HighlightingRule rule : highlightingRules) {
QRegExp expression = rule.pattern;
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = commentStartExpression.indexIn(text);
while (startIndex >= 0) {
int endIndex = commentEndExpression.indexIn(text, startIndex);
int commentLength;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex + commentEndExpression.matchedLength();
}
setFormat(startIndex, commentLength, commentFormat);
startIndex = commentStartExpression.indexIn(text, startIndex + commentLength);
}
}
}
private String curFile;
private QTextEdit textEdit;
private QMenu fileMenu;
private QMenu editMenu;
private QMenu helpMenu;
private QToolBar fileToolBar;
private QToolBar editToolBar;
private QAction newAct;
private QAction openAct;
private QAction saveAct;
private QAction saveAsAct;
private QAction exitAct;
private QAction cutAct;
private QAction copyAct;
private QAction pasteAct;
private QAction aboutAct;
private String rsrcPath = "images";
public static void main(String[] args)
{
QApplication.initialize(args);
TextEdit application = new TextEdit();
application.show();
QApplication.exec();
}
}
////// połączyć do programu ||
public class TextEdit extends QPlainTextEdit
{
public TextEdit()
{
lineNumberArea = new LineNumberArea(this);
blockCountChanged.connect(this, "updateLineNumberAreaWidth(Integer)");
updateRequest.connect(this, "updateLineNumberArea(QRect,Integer)");
cursorPositionChanged.connect(this, "highlightCurrentLine()");
updateLineNumberAreaWidth(0);
highlightCurrentLine();
setWindowTitle("Code Editor Example");
setWindowIcon(new QIcon("classpath:com/trolltech/images/qt-logo.png"));
}
public int lineNumberAreaWidth()
{
int digits = 1;
int max = Math.max(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
int space = 3 + fontMetrics().width('9') * digits;
return space;
}
public void updateLineNumberAreaWidth(Integer newBlockCount)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
public void updateLineNumberArea(QRect rect, Integer dy)
{
if (dy > 0)
lineNumberArea.scroll(0, dy);
else
lineNumberArea.update(0, rect.y(), lineNumberArea.width(),
rect.height());
if (rect.contains(viewport().rect()))
updateLineNumberAreaWidth(0);
}
protected void resizeEvent(QResizeEvent e)
{
super.resizeEvent(e);
QRect cr = contentsRect();
lineNumberArea.setGeometry(new QRect(cr.left(), cr.top(),
lineNumberAreaWidth(), cr.height()));
}
private void highlightCurrentLine()
{
List<QTextEdit_ExtraSelection> extraSelections =
new Vector<QTextEdit_ExtraSelection>();
if (!isReadOnly()) {
QTextEdit_ExtraSelection selection =
new QTextEdit_ExtraSelection();
QColor lineColor = QColor.gray.lighter(155);
QTextCharFormat format = selection.format();
format.setBackground(new QBrush(lineColor));
format.setProperty(QTextFormat.Property.FullWidthSelection.value(), new Boolean(true));
selection.setFormat(format);
QTextCursor cursor = textCursor();
cursor.clearSelection();
selection.setCursor(cursor);
extraSelections.add(selection);
}
setExtraSelections(extraSelections);
}
public void lineNumberAreaPaintEvent(QPaintEvent event)
{
QPainter painter = new QPainter(lineNumberArea);
painter.setPen(new QPen(QColor.black));
painter.fillRect(event.rect(), new QBrush(QColor.white));
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event.rect().bottom()) {
if (block.isVisible() && bottom >= event.rect().top()) {
String number = String.valueOf(blockNumber + 1);
painter.drawText(0, top, lineNumberArea.width(), fontMetrics().height(),
Qt.AlignmentFlag.AlignRight.value(), number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
private static class LineNumberArea extends QWidget
{
public LineNumberArea(TextEdit editor)
{
codeEditor = editor;
setParent(codeEditor);
}
public QSize sizeHint()
{
return new QSize(codeEditor.lineNumberAreaWidth(), 0);
}
protected void paintEvent(QPaintEvent event)
{
codeEditor.lineNumberAreaPaintEvent(event);
}
private TextEdit codeEditor;
}
private LineNumberArea lineNumberArea;
public static void main(String args[])
{
QApplication.initialize(args);
new TextEdit().show();
QApplication.exec();
}
}
Bardzo proszę o pomoc !