So, I have a keyListener in my program. As soon as it's activated, it draws another component on screen.
What happens is the newest component gets drawn on screen in a place it shouldn't be or wrongly sized (just for a split second) and then snaps to it's designated location and size and everything looks great.
Is there a way to instruct my program to calculate position and size of the component prior to drawing it on screen to avoid that flicker?
package core;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
#SuppressWarnings("serial")
class DefaultFont extends Font
{
public DefaultFont()
{
super("Arial", PLAIN, 20);
}
}
#SuppressWarnings("serial")
class Page extends JPanel
{
public JPanel largePage;
public int content;
public Page(JPanel panel, int index)
{
largePage = new JPanel();
largePage.setLayout(new BoxLayout(largePage, BoxLayout.Y_AXIS));
largePage.setMaximumSize(new Dimension(794, 1123));
largePage.setPreferredSize(new Dimension(794, 1123));
largePage.setAlignmentX(Component.CENTER_ALIGNMENT);
largePage.setBackground(Color.WHITE);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
setMaximumSize(new Dimension(556, 931));
setBackground(Color.LIGHT_GRAY);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new Box.Filler(new Dimension(556, 0), new Dimension(556, 931), new Dimension(556, 931)));
largePage.add(this);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
panel.add(largePage, index);
panel.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
content = 0;
Main.pages.add(this);
}
}
#SuppressWarnings("serial")
class Heading extends JTextArea
{
public boolean type;
public AbstractDocument doc;
public ArrayList<JPanel/*Question*/> questions;
public ArrayList<JPanel/*List*/> list;
public Heading(boolean segment, Page page)
{
type = segment;
setBackground(Color.RED);
setFont(new Font("Arial", Font.BOLD, 20));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 10, 0, Color.WHITE);
setBorder(BorderFactory.createCompoundBorder(out, in));
setLineWrap(true);
setWrapStyleWord(true);
setText("Heading 1 Heading 1 Heading 1 Heading 1");
doc = (AbstractDocument)this.getDocument();
doc.setDocumentFilter(new DocumentFilter()
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 100)
{
;
fb.insertString(offs, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 100 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
fb.insertString(offs, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 100)
{
fb.replace(offs, length, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 100 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
});
page.add(this, 0);
page.content++;
if (type)
{
questions = new ArrayList<JPanel>();
}
else
{
list = new ArrayList<JPanel>();
}
}
}
#SuppressWarnings("serial")
class Question extends JPanel
{
public JPanel questionArea, numberArea, answerArea;
public JLabel number;
public JTextArea question;
public AbstractDocument doc;
public Question(Page page, int pageNum, int index)
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE));
questionArea = new JPanel();
questionArea.setLayout(new BoxLayout(questionArea, BoxLayout.X_AXIS));
questionArea.setBorder(BorderFactory.createMatteBorder(0, 0, 8, 0, Color.WHITE));
numberArea = new JPanel();
numberArea.setLayout(new BorderLayout());
numberArea.setBackground(Color.WHITE);
number = new JLabel(pageNum+". ", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
number.setFont(new Font("Arial", Font.PLAIN, 17));
numberArea.add(number, BorderLayout.NORTH);
questionArea.add(numberArea);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 17));
question.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("Is this the first question?");
doc = (AbstractDocument)question.getDocument();
doc.setDocumentFilter(new DocumentFilter()
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 200)
{
;
fb.insertString(offs, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
fb.insertString(offs, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 200)
{
fb.replace(offs, length, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
});
questionArea.add(question);
add(questionArea);
answerArea = new JPanel();
answerArea.setLayout(new BoxLayout(answerArea, BoxLayout.Y_AXIS));
add(answerArea);
page.add(this, index);
page.content++;
}
}
#SuppressWarnings("serial")
class Answer extends JPanel
{
public JPanel letterArea;
public JLabel letter;
public JTextArea answer;
public char[] letters = {'a', 'b', 'c', 'd', 'e' };
public AbstractDocument doc;
public Answer(Question q, int index)
{
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
letterArea = new JPanel();
letterArea.setLayout(new BorderLayout());
letterArea.setBackground(Color.WHITE);
letter = new JLabel(letters[index-1]+") ", JLabel.RIGHT);
letter.setMinimumSize(new Dimension(150, 20));
letter.setPreferredSize(new Dimension(150, 20));
letter.setMaximumSize(new Dimension(150, 20));
letter.setFont(new Font("Arial", Font.PLAIN, 17));
letterArea.add(letter, BorderLayout.NORTH);
add(letterArea);
answer = new JTextArea();
answer.setFont(new Font("Arial", Font.PLAIN, 17));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE);
answer.setBorder(BorderFactory.createCompoundBorder(out, in));
answer.setLineWrap(true);
answer.setWrapStyleWord(true);
answer.addKeyListener(new KeyListener()
{
#Override
public void keyPressed(KeyEvent arg0)
{
new Answer((Question) ((JTextArea) arg0.getSource()).getParent().getParent().getParent(), 2);
Main.mWindow.repaint();
Main.mWindow.validate();
}
public void keyReleased(KeyEvent arg0) {}
public void keyTyped(KeyEvent arg0) {}
});
doc = (AbstractDocument)answer.getDocument();
doc.setDocumentFilter(new DocumentFilter()
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 200)
{
;
fb.insertString(offs, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
fb.insertString(offs, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 200)
{
fb.replace(offs, length, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
});
answer.setBackground(Color.PINK);
add(answer);
q.answerArea.add(this, index-1);
}
}
public class Main
{
public static Properties config;
public static Locale currentLocale;
public static ResourceBundle lang;
public static JFrame mWindow;
public static JMenuBar menu;
public static JMenu menuFile, menuEdit;
public static JMenuItem itmNew, itmClose, itmLoad, itmSave, itmSaveAs, itmExit, itmCut, itmCopy, itmPaste, itmProperties;
public static JDialog newDoc;
public static JLabel newDocText1, newDocText2;
public static JRadioButton questions, list;
public static ButtonGroup newDocButtons;
public static JButton newDocOk;
public static Boolean firstSegment;
public static JPanel workspace;
public static JScrollPane scroll;
public static ArrayList<Page> pages;
public static void newDocumentForm()
{
//new document dialog
mWindow.setEnabled(false);
newDoc = new JDialog(mWindow, "newDoc");
newDoc.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
newDoc.addWindowListener(new WindowListener ()
{
public void windowActivated(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0)
{
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
});
newDoc.setSize(400, 200);
newDoc.setLocationRelativeTo(null);
newDoc.setResizable(false);
newDoc.setLayout(null);
newDoc.setVisible(true);
newDocText1 = new JLabel("newDocText1");
newDocText1.setBounds(5, 0, 400, 20);
newDocText2 = new JLabel("newDocText2");
newDocText2.setBounds(5, 20, 400, 20);
newDoc.add(newDocText1);
newDoc.add(newDocText2);
firstSegment = true;
questions = new JRadioButton("questions");
questions.setSelected(true);
questions.setFocusPainted(false);
questions.setBounds(10, 60, 400, 20);
questions.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = true;
}
});
list = new JRadioButton("list");
list.setFocusPainted(false);
list.setBounds(10, 80, 400, 20);
list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = false;
}
});
newDoc.add(questions);
newDoc.add(list);
newDocButtons = new ButtonGroup();
newDocButtons.add(questions);
newDocButtons.add(list);
newDocOk = new JButton("ok");
newDocOk.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
newDocOk.doClick();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
newDocOk.setFocusPainted(false);
newDocOk.setBounds(160, 120, 80, 40);
newDocOk.setMnemonic(KeyEvent.VK_ACCEPT);
newDocOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
createNewDocument();
}
});
newDoc.add(newDocOk);
newDocOk.requestFocus();
}
public static void createNewDocument()
{
//dispose of new document dialog
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
//create document display
workspace = new JPanel();
workspace.setLayout(new BoxLayout(workspace, BoxLayout.PAGE_AXIS));
workspace.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
workspace.setBackground(Color.BLACK);
scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getVerticalScrollBar().setUnitIncrement(20);
scroll.setViewportView(workspace);
pages = new ArrayList<Page>();
Page p = new Page(workspace, 1);
new Heading(true, p);
Question q = new Question(p, 1, 1);
new Answer(q, 1);
mWindow.add(scroll, BorderLayout.CENTER);
mWindow.repaint();
mWindow.validate();
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
//create main window
mWindow = new JFrame("title");
mWindow.setSize(1000, 800);
mWindow.setMinimumSize(new Dimension(1000, 800));
mWindow.setLocationRelativeTo(null);
mWindow.setLayout(new BorderLayout());
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mWindow.setVisible(true);
//create menu bar
menu = new JMenuBar();
menuFile = new JMenu("file");
menuEdit = new JMenu("edit");
itmNew = new JMenuItem("new");
itmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
itmNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newDocumentForm();
}
});
itmClose = new JMenuItem("close");
itmClose.setActionCommand("Close");
itmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
itmLoad = new JMenuItem("load");
itmLoad.setActionCommand("Load");
itmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
itmSave = new JMenuItem("save");
itmSave.setActionCommand("Save");
itmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
itmSaveAs = new JMenuItem("saveAs");
itmSaveAs.setActionCommand("SaveAs");
itmExit = new JMenuItem("exit");
itmExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Add confirmation window!
System.exit(0);
}
});
itmCut = new JMenuItem("cut");
itmCut.setActionCommand("Cut");
itmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
itmCopy = new JMenuItem("copy");
itmCopy.setActionCommand("Copy");
itmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
itmPaste = new JMenuItem("paste");
itmPaste.setActionCommand("Paste");
itmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
itmProperties = new JMenuItem("properties");
itmProperties.setActionCommand("properties");
itmProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
menuFile.add(itmNew);
menuFile.add(itmClose);
menuFile.addSeparator();
menuFile.add(itmLoad);
menuFile.addSeparator();
menuFile.add(itmSave);
menuFile.add(itmSaveAs);
menuFile.addSeparator();
menuFile.add(itmExit);
menuEdit.add(itmCut);
menuEdit.add(itmCopy);
menuEdit.add(itmPaste);
menuEdit.addSeparator();
menuEdit.add(itmProperties);
menu.add(menuFile);
menu.add(menuEdit);
//create actionListener for menus
mWindow.add(menu, BorderLayout.NORTH);
mWindow.repaint();
mWindow.validate();
}
}
It's not SSCCE (it's whole set of interdependent components, replicating it in a new program would be pain in the neck, and might not even be that much shorter), but the whole thing occurs in the Answer class. You can almost ignore anything else.
P.S. To get thing draw pres ctrl+n, then enter!
Then click in the pink textarea and just press a button...
P.P.S. If you hold that button, you get really cool effect... :D
You probably need to validate() and then repaint() in the KeyListener. Key bindings may be a better way to go.
Related
I have a SortedListModel called comandaDescriptionListModel:
private SortedListModel comandaDescriptionListModel;
I have other SortedListModels within my application, but this one fails to add items after 1 element. Just 1 element gets added, and it makes no sense.
btnAddComanda.addActionListener(new ActionListener() {
#SuppressWarnings("unchecked")
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel addPanel = new JPanel();
addPanel.add(new JLabel("Descrição:"));
JTextField comandaDescriptionField = new JTextField();
comandaDescriptionField.setPreferredSize(new Dimension(200, 24));
addPanel.add(comandaDescriptionField);
comandaDescriptionField.requestFocusInWindow();
String comandaName = "C" + Integer.toString(comandaListModel.getSize()+1);
int result = JOptionPane.showConfirmDialog(null, addPanel, "Adicionar comanda",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
if (comandaListModel.getSize() == 0) {
productComboBox.setEnabled(true);
btnAddProduct.setEnabled(true);
}
String comandaDescription = comandaDescriptionField.getText();
getCurrentCashRegister().addComanda(comandaName, comandaDescription);
// Comanda description model not adding items,
// Need to fix it
comandaListModel.addElement(comandaName);
comandaDescriptionListModel.addElement(comandaDescription); // HERE <<<
comandaList.setSelectedIndex(comandaList.getLastVisibleIndex());
clearProductComboBox();
updateProductComboBox();
}
}
});
Here's a screenshot:
Under "descrição", it should continue to "b" and "c". I can only think it's a bug. Is there some swing bug that causes problems when appending to more than one list at the same time?
When I deal with multi JList components, I do it in own way and also play with all given facilities.
why not, I use this below source code?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MultiListExample extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textField;
private JButton addBtn, removeBtn;
private JList<String> list1, list2, list3;
private DefaultListModel<String> dlm1, dlm2, dlm3;
public MultiListExample() {
init();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException ex) {
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MultiListExample();
}
});
}
private void init() {
setTitle("Multi List Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 100, 300, 300);
textField = new JTextField();
textField.setFont(new Font("Dialog", Font.PLAIN, 15));
add(textField, BorderLayout.PAGE_START);
JPanel panel = new JPanel(new BorderLayout());
add(panel, BorderLayout.CENTER);
addBtn = new JButton("Add Element");
addBtn.setFocusPainted(false);
addBtn.setFont(textField.getFont());
panel.add(addBtn, BorderLayout.PAGE_START);
JPanel innerPanel = new JPanel(new GridLayout(1, 3));
panel.add(innerPanel, BorderLayout.CENTER);
dlm1 = new DefaultListModel<String>();
dlm1.addElement("Apple");
dlm1.addElement("Avocado");
dlm1.addElement("Banana");
dlm1.addElement("Jambul");
list1 = new JList<String>(dlm1);
list1.setFont(textField.getFont());
innerPanel.add(list1);
dlm2 = new DefaultListModel<String>();
dlm2.addElement("Currant");
dlm2.addElement("Cherry");
dlm2.addElement("Cloudberry");
dlm2.addElement("Raisin");
list2 = new JList<String>(dlm2);
list2.setFont(textField.getFont());
list2.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 1, Color.BLACK));
innerPanel.add(list2);
dlm3 = new DefaultListModel<String>();
dlm3.addElement("Dragonfruit");
dlm3.addElement("Durian");
dlm3.addElement("Feijoa");
dlm3.addElement("Fig");
dlm3.addElement("Grape");
list3 = new JList<String>(dlm3);
list3.setFont(textField.getFont());
innerPanel.add(list3);
removeBtn = new JButton("Remove Element");
removeBtn.setFocusPainted(false);
removeBtn.setFont(textField.getFont());
add(removeBtn, BorderLayout.PAGE_END);
list1.setSelectedIndex(dlm1.getSize() - 1);
list2.setSelectedIndex(dlm2.getSize() - 1);
list3.setSelectedIndex(dlm3.getSize() - 1);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
addElementListener();
}
});
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
addElementListener();
}
});
removeBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (dlm1.getSize() > 0)
dlm1.remove(list1.getSelectedIndex());
if (dlm2.getSize() > 0)
dlm2.remove(list2.getSelectedIndex());
if (dlm3.getSize() > 0)
dlm3.remove(list3.getSelectedIndex());
if (dlm1.getSize() > 0)
list1.setSelectedIndex(0);
if (dlm2.getSize() > 0)
list2.setSelectedIndex(0);
if (dlm3.getSize() > 0)
list3.setSelectedIndex(0);
}
});
setVisible(true);
}
private void addElementListener() {
if (textField.getText().length() > 2) {
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list1, dlm1);
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list2, dlm2);
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list3, dlm3);
}
}
private void addSortAndRemoveDuplicates(String element, JList<String> list, DefaultListModel<String> model) {
// Here doing all DefaultListModel operations explicitly.
if (!model.contains(element)) {
model.addElement(element);
int size = model.getSize();
String[] elements = new String[size];
for (int i = 0; i < size; i++)
elements[i] = (String) model.getElementAt(i);
Arrays.sort(elements);
model.removeAllElements();
for (int i = 0; i < size; i++)
model.addElement(elements[i]);
list.setSelectedIndex(model.getSize() - 1);
}
}
private String firstLetterCapWord(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
}
I'm new to java and wondering what's wrong with my code.
To test the keylistener, I pressed N, but nothing happened. I then rearranged some methods but that didn't work either.
My code is below, any input is welcome :)
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Calculator extends MyFrame implements KeyListener {
private static final long serialVersionUID = 1L;
//declare variable
protected JPanel northPanel;
protected JPanel plusPanel, minusPanel, multiplyPanel, dividePanel,modPanel, equalPanel;
protected JPanel rowPanel1, rowPanel2, rowPanel3, rowPanel4, southPanel;
protected JPanel[] numPanel = new JPanel[10];
protected JTextField textField;
protected JButton plusButton, minusButton, multiplyButton;
protected JButton divideButton, modButton, equalButton;
protected JButton[] numButton = new JButton[10];
public void setTextField() {
textField = new JTextField("0.0");
textField.setBackground(Color.GRAY);
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setEditable(false);
}
public void setButton() {
for (int i = 0; i <= 9; i++) {
numButton[i] = new JButton(i + "");
}
plusButton = new JButton("+");
minusButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
modButton = new JButton("%");
equalButton = new JButton("=");
}
public void setSqualJpanel() {
for (int i = 0; i <= 9; i++) {
numPanel[i] = createSquareJpanel(Color.pink, 30, numButton[i]);
}
plusPanel = createSquareJpanel(Color.green, 30, plusButton);
minusPanel = createSquareJpanel(Color.green, 30, minusButton);
multiplyPanel = createSquareJpanel(Color.green, 30, multiplyButton);
dividePanel = createSquareJpanel(Color.green, 30, divideButton);
modPanel = createSquareJpanel(Color.green, 30, modButton);
equalPanel = createSquareJpanel(Color.blue, 30, equalButton);
}
public void addComponents() {
rowPanel1 = new JPanel();
rowPanel2 = new JPanel();
rowPanel3 = new JPanel();
rowPanel4 = new JPanel();
southPanel = new JPanel (new BorderLayout());
northPanel = new JPanel(new BorderLayout());
northPanel.add(textField);
rowPanel1.add(numPanel[0]);
rowPanel1.add(numPanel[1]);
rowPanel1.add(numPanel[2]);
rowPanel1.add(numPanel[3]);
rowPanel2.add(numPanel[4]);
rowPanel2.add(numPanel[5]);
rowPanel2.add(numPanel[6]);
rowPanel2.add(numPanel[7]);
rowPanel3.add(numPanel[8]);
rowPanel3.add(numPanel[9]);
rowPanel3.add(plusPanel);
rowPanel3.add(minusPanel);
rowPanel4.add(multiplyPanel);
rowPanel4.add(dividePanel);
rowPanel4.add(modPanel);
rowPanel4.add(equalPanel);
southPanel.add(rowPanel2, BorderLayout.NORTH);
southPanel.add(rowPanel3, BorderLayout.CENTER);
southPanel.add(rowPanel4, BorderLayout.SOUTH);
add(northPanel, BorderLayout.NORTH);
add(rowPanel1, BorderLayout.CENTER);
add(southPanel, BorderLayout.SOUTH);
}
public void setFrameFeatures (String title) {
setTitle(title);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = getSize().width;
int h = getSize().height;
int x = (dim.width - w) / 2;
int y = (dim.height - h) / 2;
setLocation(x, y);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void createAndShowGUI() {
Calculator frame = new Calculator();
frame.setFrameFeatures("Simple Calculator");
frame.setTextField();
frame.setButton();
frame.setSqualJpanel();
frame.addComponents();
frame.pack();
frame.addListener();
}
private void addListener() {
addKeyListener(this);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_N){
JOptionPane.showMessageDialog(null,"You Pressed N");
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
I usually add my key listeners to jpanels not frames.
Hi I've there a little problem: What I want is to delay the appearance of JLabels in a JDialog-Window, in terms of that the first line of JLabels shoud come out and then two seconds later the second line of Jlabels etc.
I've tried something with Windowlistener,the doClick()-Method etc., bu every time the Jdialog revalidates all of its panels AT ONCE and shows them without any delaying!
Please help me(Just copy the code below and try out)!
package footballQuestioner;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class attempter {
public static void main(String[] args) throws InterruptedException {
JDialog dialog = new Punkte();
}
}
class Punkte extends JDialog {
private JPanel screenPanel = new JPanel(new GridLayout(4, 1));
private JButton button = new JButton();
private int i = 1;
private class WindowHandler implements WindowListener {
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowOpened(WindowEvent e) {
button.doClick(1000);
button.doClick(1000);
button.doClick(1000);
button.doClick(); // here im trying to delay the appearance of the
// JLabels....
}
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
switch (i) {
case 1:
settingUpPanel(getPanelFromScreenPanel(i), "Right", new Color(
102, 205, 0));
settingUpPanel(getPanelFromScreenPanel(i), "Wrong", Color.RED);
break;
case 2:
settingUpPanel(getPanelFromScreenPanel(i), "Trefferquote",
Color.YELLOW);
break;
case 3:
settingUpPanel(getPanelFromScreenPanel(i), "Ausgezeichnet",
Color.BLUE);
break;
}
System.out.println(i);
i++;
}
}
public Punkte() {
button.addActionListener(new ButtonHandler());
addWindowListener(new WindowHandler());
setModal(true);
setResizable(true);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
settingUpScreenPanel();
add(screenPanel);
setSize(1200, 1000);
centeringWindow();
setVisible(true);
}
private void settingUpScreenPanel() {
JPanel titlePanel = new JPanel(new GridBagLayout());
JPanel rightWrongCountPanel = new JPanel(new GridLayout(1, 2));
JPanel shareOfRightQuestions = new JPanel(new GridBagLayout());
JPanel grade = new JPanel(new GridBagLayout());
settingUpPanel(titlePanel, "Result", Color.BLACK);
// settingUpPanel(rightWrongCountPanel,
// "Right: "+numberOfRightAnsers+"/6",new Color(102,205,0));
// settingUpPanel(rightWrongCountPanel,
// "Wrong: "+(6-numberOfRightAnsers)+"/6", Color.RED);
// settingUpPanel(shareOfRightQuestions,
// "Trefferquote: "+(numberOfRightAnsers*100/6)+"%",Color.YELLOW);
// settingUpPanel(summaSummarum,
// getBufferedImage("footballQuestioner/Strich.png"));
// settingUpPanel(grade,"Aushezeichnet", Color.BLUE);
borderingJPanel(screenPanel, null, null);
titlePanel.setOpaque(false);
rightWrongCountPanel.setOpaque(false);
shareOfRightQuestions.setOpaque(false);
grade.setOpaque(false);
screenPanel.add(titlePanel);
screenPanel.add(rightWrongCountPanel);
screenPanel.add(shareOfRightQuestions);
screenPanel.add(grade);
}
private void settingUpPanel(JComponent panel, String string, Color color) {
Font font = new Font("Rockwell Extra Bold", Font.PLAIN, 65);
JPanel innerPanel = new JPanel(new GridBagLayout());
JLabel label = new JLabel(string);
label.setForeground(color);
label.setFont(font);
innerPanel.add(label);
innerPanel.setOpaque(false);
panel.add(innerPanel);
panel.validate();
panel.repaint();
}
public JPanel getPanelFromScreenPanel(int numberOfPanel) {
JPanel screenPanel = (JPanel) getContentPane().getComponent(0);
JPanel labelPanel = (JPanel) screenPanel.getComponent(numberOfPanel);
return labelPanel;
}
public void centeringWindow() {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x;
int y;
x = (int) (dimension.getWidth() - getWidth()) / 2;
y = (int) (dimension.getHeight() - getHeight()) / 2;
setLocation(x, y);
}
public void borderingJPanel(JComponent panel, String jPanelname,
String fontStyle) {
Font font = new Font(fontStyle, Font.BOLD + Font.ITALIC, 12);
if (jPanelname != null) {
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY,
Color.WHITE), jPanelname,
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION, font));
} else if (jPanelname == null || fontStyle == null) {
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(EtchedBorder.LOWERED, Color.BLACK,
Color.WHITE)));
}
panel.setOpaque(false);
}
}
This is a really good use case for javax.swing.Timer...
This will allow you to schedule a callback, at a regular interval with which you can perform an action, safely on the UI.
private class WindowHandler extends WindowAdapter {
#Override
public void windowOpened(WindowEvent e) {
System.out.println("...");
Timer timer = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = getPanelFromScreenPanel(1);
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int index = 0; index < 100; index++) {
panel.add(new JLabel(Integer.toString(index)), gbc);
}
panel.revalidate();
}
});
timer.start();
timer.setRepeats(false);
}
}
Now, if you wanted to do a series of actions, separated by the interval, you could use a counter to determine the number of "ticks" that have occurred and take appropriate action...
private class WindowHandler extends WindowAdapter {
#Override
public void windowOpened(WindowEvent e) {
System.out.println("...");
Timer timer = new Timer(2000, new ActionListener() {
private int counter = 0;
private int maxActions = 10;
#Override
public void actionPerformed(ActionEvent e) {
switch (counter) {
case 0:
// Action for case 0...
break;
case 1:
// Action for case 1...
break;
.
.
.
}
counter++;
if (counter >= maxActions) {
((Timer)e.getSource()).stop();
}
}
});
timer.start();
}
}
Take a look at How to use Swing Timers for more details
So, I have a program with JTextArea with DocumentFilter. It should (among other things) filter out tab characters and prevent them to be entered in the JTextArea completely.
Well, it works well when I type, but I can still paste it in. i shouldn't be able to, according to the code...
Below is kind of a SSCCE. Just run it, press ctrl+n and enter. All the colored fileds are JTextAreas with same DocumentFilter. The filter itself is the first class (DefaultDocFilter), only thing you need to look into.
package core;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;
class DefaultDocFilter extends DocumentFilter
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 200)
{
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
System.out.print(str);
fb.insertString(offs, str, a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
str.substring(0, spaceLeft);
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
fb.insertString(offs, str, a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n") || str.equals("\t"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 200)
{
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
fb.replace(offs, length, str, a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
}
#SuppressWarnings("serial")
class DefaultFont extends Font
{
public DefaultFont()
{
super("Arial", PLAIN, 20);
}
}
#SuppressWarnings("serial")
class Page extends JPanel
{
public JPanel largePage;
public int content;
public Page(JPanel panel, int index)
{
largePage = new JPanel();
largePage.setLayout(new BoxLayout(largePage, BoxLayout.Y_AXIS));
largePage.setMaximumSize(new Dimension(794, 1123));
largePage.setPreferredSize(new Dimension(794, 1123));
largePage.setAlignmentX(Component.CENTER_ALIGNMENT);
largePage.setBackground(Color.WHITE);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
setMaximumSize(new Dimension(556, 931));
setBackground(Color.LIGHT_GRAY);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new Box.Filler(new Dimension(556, 0), new Dimension(556, 931), new Dimension(556, 931)));
largePage.add(this);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
panel.add(largePage, index);
panel.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
content = 0;
Main.pages.add(this);
}
}
#SuppressWarnings("serial")
class Heading extends JTextArea
{
public boolean type;
public AbstractDocument doc;
public ArrayList<JPanel/*Question*/> questions;
public ArrayList<JPanel/*List*/> list;
public Heading(boolean segment, Page page)
{
type = segment;
setBackground(Color.RED);
setFont(new Font("Arial", Font.BOLD, 20));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 10, 0, Color.WHITE);
setBorder(BorderFactory.createCompoundBorder(out, in));
setLineWrap(true);
setWrapStyleWord(true);
setText("Heading 1 Heading 1 Heading 1 Heading 1");
doc = (AbstractDocument)this.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
page.add(this, 0);
page.content++;
if (type)
{
questions = new ArrayList<JPanel>();
}
else
{
list = new ArrayList<JPanel>();
}
}
}
#SuppressWarnings("serial")
class Question extends JPanel
{
public JPanel questionArea, numberArea, answerArea;
public JLabel number;
public JTextArea question;
public AbstractDocument doc;
public Question(Page page, int pageNum, int index)
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE));
questionArea = new JPanel();
questionArea.setLayout(new BoxLayout(questionArea, BoxLayout.X_AXIS));
questionArea.setBorder(BorderFactory.createMatteBorder(0, 0, 8, 0, Color.WHITE));
numberArea = new JPanel();
numberArea.setLayout(new BorderLayout());
numberArea.setBackground(Color.WHITE);
number = new JLabel(pageNum+". ", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
number.setFont(new Font("Arial", Font.PLAIN, 17));
numberArea.add(number, BorderLayout.NORTH);
questionArea.add(numberArea);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 17));
question.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("Is this the first question?");
doc = (AbstractDocument)question.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
questionArea.add(question);
add(questionArea);
answerArea = new JPanel();
answerArea.setLayout(new BoxLayout(answerArea, BoxLayout.Y_AXIS));
add(answerArea);
page.add(this, index);
page.content++;
}
}
#SuppressWarnings("serial")
class Answer extends JPanel
{
public JPanel letterArea;
public JLabel letter;
public JTextArea answer;
public AbstractDocument doc;
public Answer(Question q, int index)
{
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
letterArea = new JPanel();
letterArea.setLayout(new BorderLayout());
letterArea.setBackground(Color.WHITE);
letter = new JLabel((char)(index+96)+") ", JLabel.RIGHT);
letter.setMinimumSize(new Dimension(150, 20));
letter.setPreferredSize(new Dimension(150, 20));
letter.setMaximumSize(new Dimension(150, 20));
letter.setFont(new Font("Arial", Font.PLAIN, 17));
letterArea.add(letter, BorderLayout.NORTH);
add(letterArea);
answer = new JTextArea();
answer.setFont(new Font("Arial", Font.PLAIN, 17));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE);
answer.setBorder(BorderFactory.createCompoundBorder(out, in));
answer.setLineWrap(true);
answer.setWrapStyleWord(true);
answer.addKeyListener(new KeyListener()
{
#Override
public void keyPressed(KeyEvent arg0)
{
System.out.print(((JTextComponent) arg0.getSource()).getText());
if (arg0.getKeyCode() == KeyEvent.VK_ENTER)
{
String JLabelText = ((JLabel) ((JPanel) ((JPanel) ((Component) arg0.getSource()).getParent()).getComponent(0)).getComponent(0)).getText();
int ansNum = (int)JLabelText.charAt(0)-95;
if (ansNum < 6)
{
Answer k = new Answer((Question) ((JTextArea) arg0.getSource()).getParent().getParent().getParent(), ansNum);
k.answer.grabFocus();
Main.mWindow.repaint();
Main.mWindow.validate();
}
}
}
public void keyReleased(KeyEvent arg0) {}
public void keyTyped(KeyEvent arg0) {}
});
doc = (AbstractDocument)answer.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
answer.setBackground(Color.PINK);
add(answer);
q.answerArea.add(this, index-1);
}
}
public class Main
{
public static Properties config;
public static Locale currentLocale;
public static ResourceBundle lang;
public static JFrame mWindow;
public static JMenuBar menu;
public static JMenu menuFile, menuEdit;
public static JMenuItem itmNew, itmClose, itmLoad, itmSave, itmSaveAs, itmExit, itmCut, itmCopy, itmPaste, itmProperties;
public static JDialog newDoc;
public static JLabel newDocText1, newDocText2;
public static JRadioButton questions, list;
public static ButtonGroup newDocButtons;
public static JButton newDocOk;
public static Boolean firstSegment;
public static JPanel workspace;
public static JScrollPane scroll;
public static ArrayList<Page> pages;
public static void newDocumentForm()
{
//new document dialog
mWindow.setEnabled(false);
newDoc = new JDialog(mWindow, "newDoc");
newDoc.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
newDoc.addWindowListener(new WindowListener ()
{
public void windowActivated(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0)
{
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
});
newDoc.setSize(400, 200);
newDoc.setLocationRelativeTo(null);
newDoc.setResizable(false);
newDoc.setLayout(null);
newDoc.setVisible(true);
newDocText1 = new JLabel("newDocText1");
newDocText1.setBounds(5, 0, 400, 20);
newDocText2 = new JLabel("newDocText2");
newDocText2.setBounds(5, 20, 400, 20);
newDoc.add(newDocText1);
newDoc.add(newDocText2);
firstSegment = true;
questions = new JRadioButton("questions");
questions.setSelected(true);
questions.setFocusPainted(false);
questions.setBounds(10, 60, 400, 20);
questions.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = true;
}
});
list = new JRadioButton("list");
list.setFocusPainted(false);
list.setBounds(10, 80, 400, 20);
list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = false;
}
});
newDoc.add(questions);
newDoc.add(list);
newDocButtons = new ButtonGroup();
newDocButtons.add(questions);
newDocButtons.add(list);
newDocOk = new JButton("ok");
newDocOk.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
newDocOk.doClick();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
newDocOk.setFocusPainted(false);
newDocOk.setBounds(160, 120, 80, 40);
newDocOk.setMnemonic(KeyEvent.VK_ACCEPT);
newDocOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
createNewDocument();
}
});
newDoc.add(newDocOk);
newDocOk.requestFocus();
}
public static void createNewDocument()
{
//dispose of new document dialog
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
//create document display
workspace = new JPanel();
workspace.setLayout(new BoxLayout(workspace, BoxLayout.PAGE_AXIS));
workspace.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
workspace.setBackground(Color.BLACK);
scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getVerticalScrollBar().setUnitIncrement(20);
scroll.setViewportView(workspace);
pages = new ArrayList<Page>();
Page p = new Page(workspace, 1);
new Heading(true, p);
Question q = new Question(p, 1, 1);
new Answer(q, 1);
mWindow.add(scroll, BorderLayout.CENTER);
mWindow.repaint();
mWindow.validate();
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
//create main window
mWindow = new JFrame("title");
mWindow.setSize(1000, 800);
mWindow.setMinimumSize(new Dimension(1000, 800));
mWindow.setLocationRelativeTo(null);
mWindow.setLayout(new BorderLayout());
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mWindow.setVisible(true);
//create menu bar
menu = new JMenuBar();
menuFile = new JMenu("file");
menuEdit = new JMenu("edit");
itmNew = new JMenuItem("new");
itmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
itmNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newDocumentForm();
}
});
itmClose = new JMenuItem("close");
itmClose.setActionCommand("Close");
itmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
itmLoad = new JMenuItem("load");
itmLoad.setActionCommand("Load");
itmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
itmSave = new JMenuItem("save");
itmSave.setActionCommand("Save");
itmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
itmSaveAs = new JMenuItem("saveAs");
itmSaveAs.setActionCommand("SaveAs");
itmExit = new JMenuItem("exit");
itmExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Add confirmation window!
System.exit(0);
}
});
itmCut = new JMenuItem("cut");
itmCut.setActionCommand("Cut");
itmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
itmCopy = new JMenuItem("copy");
itmCopy.setActionCommand("Copy");
itmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
itmPaste = new JMenuItem("paste");
itmPaste.setActionCommand("Paste");
itmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
itmProperties = new JMenuItem("properties");
itmProperties.setActionCommand("properties");
itmProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
menuFile.add(itmNew);
menuFile.add(itmClose);
menuFile.addSeparator();
menuFile.add(itmLoad);
menuFile.addSeparator();
menuFile.add(itmSave);
menuFile.add(itmSaveAs);
menuFile.addSeparator();
menuFile.add(itmExit);
menuEdit.add(itmCut);
menuEdit.add(itmCopy);
menuEdit.add(itmPaste);
menuEdit.addSeparator();
menuEdit.add(itmProperties);
menu.add(menuFile);
menu.add(menuEdit);
//create actionListener for menus
mWindow.add(menu, BorderLayout.NORTH);
mWindow.repaint();
mWindow.validate();
}
}
Why don't you assign String into DocumentFilter
str = str.replaceAll()?
I have a JPanel which contains a JToolbar (including few buttons without text) and a JTable and I need to enable/disable (make internal widgets not clickable). I tried this:
JPanel panel = ....;
for (Component c : panel.getComponents()) c.setEnabled(enabled);
but it doesn't work. Is there a better and more generic solution to enable/disable all internal components in a JPanel?
I have partially solved my problem using JLayer starting from the example here http://docs.oracle.com/javase/tutorial/uiswing/misc/jlayer.html:
layer = new JLayer<JComponent>(myPanel, new BlurLayerUI(false));
.....
((BlurLayerUI)layer.getUI()).blur(...); // switch blur on/off
class BlurLayerUI extends LayerUI<JComponent> {
private BufferedImage mOffscreenImage;
private BufferedImageOp mOperation;
private boolean blur;
public BlurLayerUI(boolean blur) {
this.blur = blur;
float ninth = 1.0f / 9.0f;
float[] blurKernel = {
ninth, ninth, ninth,
ninth, ninth, ninth,
ninth, ninth, ninth
};
mOperation = new ConvolveOp(
new Kernel(3, 3, blurKernel),
ConvolveOp.EDGE_NO_OP, null);
}
public void blur(boolean blur) {
this.blur=blur;
firePropertyChange("blur", 0, 1);
}
#Override
public void paint (Graphics g, JComponent c) {
if (!blur) {
super.paint (g, c);
return;
}
int w = c.getWidth();
int h = c.getHeight();
if (w == 0 || h == 0) {
return;
}
// Only create the offscreen image if the one we have
// is the wrong size.
if (mOffscreenImage == null ||
mOffscreenImage.getWidth() != w ||
mOffscreenImage.getHeight() != h) {
mOffscreenImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
Graphics2D ig2 = mOffscreenImage.createGraphics();
ig2.setClip(g.getClip());
super.paint(ig2, c);
ig2.dispose();
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(mOffscreenImage, mOperation, 0, 0);
}
#Override
public void applyPropertyChange(PropertyChangeEvent pce, JLayer l) {
if ("blur".equals(pce.getPropertyName())) {
l.repaint();
}
}
}
I still have 2 problems:
In the link above events are relative to mouse only. How can I manage the keyboard events?
How can I create a "gray out" effect in place of blur?
It requires a recursive call.
import java.awt.*;
import javax.swing.*;
public class DisableAllInContainer {
public void enableComponents(Container container, boolean enable) {
Component[] components = container.getComponents();
for (Component component : components) {
component.setEnabled(enable);
if (component instanceof Container) {
enableComponents((Container)component, enable);
}
}
}
DisableAllInContainer() {
JPanel gui = new JPanel(new BorderLayout());
final JPanel container = new JPanel(new BorderLayout());
gui.add(container, BorderLayout.CENTER);
JToolBar tb = new JToolBar();
container.add(tb, BorderLayout.NORTH);
for (int ii=0; ii<3; ii++) {
tb.add(new JButton("Button"));
}
JTree tree = new JTree();
tree.setVisibleRowCount(6);
container.add(new JScrollPane(tree), BorderLayout.WEST);
container.add(new JTextArea(5,20), BorderLayout.CENTER);
final JCheckBox enable = new JCheckBox("Enable", true);
enable.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
enableComponents(container, enable.isSelected());
}
});
gui.add(enable, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new DisableAllInContainer();
}
});
}}
I used the following function:
void setPanelEnabled(JPanel panel, Boolean isEnabled) {
panel.setEnabled(isEnabled);
Component[] components = panel.getComponents();
for(int i = 0; i < components.length; i++) {
if(components[i].getClass().getName() == "javax.swing.JPanel") {
setPanelEnabled((JPanel) components[i], isEnabled);
}
components[i].setEnabled(isEnabled);
}
}
you can overlay whole Container / JComponent
GlassPane block by default MouseEvents, but not Keyboard, required consume all keyevents from ToolKit
JLayer (Java7) based on JXLayer (Java6)
can't see reason(s) why not works for you
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class AddComponentsAtRuntime {
private JFrame f;
private JPanel panel;
private JCheckBox checkValidate, checkReValidate, checkRepaint, checkPack;
public AddComponentsAtRuntime() {
JButton b = new JButton();
//b.setBackground(Color.red);
b.setBorder(new LineBorder(Color.black, 2));
b.setPreferredSize(new Dimension(600, 20));
panel = new JPanel(new GridLayout(0, 1));
panel.add(b);
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel, "Center");
f.add(getCheckBoxPanel(), "South");
f.setLocation(200, 200);
f.pack();
f.setVisible(true);
}
private JPanel getCheckBoxPanel() {
checkValidate = new JCheckBox("validate");
checkValidate.setSelected(false);
checkReValidate = new JCheckBox("revalidate");
checkReValidate.setSelected(true);
checkRepaint = new JCheckBox("repaint");
checkRepaint.setSelected(true);
checkPack = new JCheckBox("pack");
checkPack.setSelected(true);
JButton addComp = new JButton("Add New One");
addComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton b = new JButton();
//b.setBackground(Color.red);
b.setBorder(new LineBorder(Color.black, 2));
b.setPreferredSize(new Dimension(400, 10));
panel.add(b);
makeChange();
System.out.println(" Components Count after Adds :" + panel.getComponentCount());
}
});
JButton removeComp = new JButton("Remove One");
removeComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int count = panel.getComponentCount();
if (count > 0) {
panel.remove(0);
}
makeChange();
System.out.println(" Components Count after Removes :" + panel.getComponentCount());
}
});
JButton disabledComp = new JButton("Disabled All");
disabledComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Component c : panel.getComponents()) {
c.setEnabled(false);
}
}
});
JButton enabledComp = new JButton("Enabled All");
enabledComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Component c : panel.getComponents()) {
c.setEnabled(true);
}
}
});
JPanel panel2 = new JPanel();
panel2.add(checkValidate);
panel2.add(checkReValidate);
panel2.add(checkRepaint);
panel2.add(checkPack);
panel2.add(addComp);
panel2.add(removeComp);
panel2.add(disabledComp);
panel2.add(enabledComp);
return panel2;
}
private void makeChange() {
if (checkValidate.isSelected()) {
panel.validate();
}
if (checkReValidate.isSelected()) {
panel.revalidate();
}
if (checkRepaint.isSelected()) {
panel.repaint();
}
if (checkPack.isSelected()) {
f.pack();
}
}
public static void main(String[] args) {
AddComponentsAtRuntime makingChanges = new AddComponentsAtRuntime();
}
}
#Kesavamoorthi
if you want to make it more general:
void setPanelEnabled(java.awt.Container cont, Boolean isEnabled) {
cont.setEnabled(isEnabled);
java.awt.Component[] components = cont.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof java.awt.Container) {
setPanelEnabled((java.awt.Container) components[i], isEnabled);
}
components[i].setEnabled(isEnabled);
}
}