I need some help about Java GUI. I want to add 10 numbers to memory from JTextField. And when it's done JButton must gonna be disable and program must show me a message dialog. How can I do this?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Uygulama extends JFrame {
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Uygulama frame = new Uygulama();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Uygulama() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 233, 140);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(48, 13, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
JButton btnHesapla = new JButton("HESAPLA");
btnHesapla.addActionListener(new ActionListener() {int counter = 0;
public void actionPerformed(ActionEvent arg0) {
while(counter < 9) {
counter++;
if(counter == 10) {
buton.setEnabled(false);}
}
});
btnHesapla.setBounds(58, 48, 97, 25);
contentPane.add(btnHesapla);
}
}
Add an ActionListener to your JButton if using Swing, and inside that, you'll increment a global variable by one. Then you ask if the variable is == 10 and do yourButton.setEnabled(false) or yourButton.setEnabled(counter < 10) if you're not using an if. You already have your listener set up, so it's only a matter of adding a variable you'll increment inside it and a call to setEnabled of your button.
Here's a working example with an ArrayList used to store the numbers. No need to use a global count variable here because the size of the ArrayList already tells us how many numbers we have stored :-)
public class NumbersApplication extends JFrame {
private JPanel contentPane;
private JTextField textField;
private List<Integer> numbers;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NumbersApplication frame = new NumbersApplication();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public NumbersApplication() {
numbers = new ArrayList<>();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 233, 140);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(48, 13, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
JButton btnHesapla = new JButton("HESAPLA");
btnHesapla.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int number = Integer.parseInt(textField.getText());
numbers.add(number);
btnHesapla.setEnabled(numbers.size() < 10);
System.out.println(number + " has been added to memory.");
if (numbers.size() == 10) {
System.out.println("Your numbers are: " + numbers);
}
}
});
btnHesapla.setBounds(58, 48, 97, 25);
contentPane.add(btnHesapla);
}
}
Related
I need a method so that when the user presses the nextCustomerBtn it will load the previous screen.
Any help would be much appreciated.
This is the extract from class MenuPage
JButton nextCustomerBtn = new JButton("Next Customer");
nextCustomerBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
nextCustomerBtn.setBounds(364, 306, 127, 29);
contentPane.add(nextCustomerBtn);
}
This is the code for the previous screen.
public class Restaurant extends JFrame {
private JPanel contentPane;
private JTextField restaurantTxt;
private JTextField numDiners;
private JTextField numDinersTxt;
private JTextField tableNumTxt;
private JTextField numTable;
private JButton numTableSubBtn;
private JButton proceedMenuBtn;
MenuPage parent;
/**
* Launch the application.
*/
////
public static String tableNumber;
public static String dinerNumber;
////
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Restaurant frame = new Restaurant();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Restaurant() {
super("Restaurant");
parent = new MenuPage();
initGUI();
// numTable = new JTextField("NewUser", 10);
}
public void initGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 840, 368);
contentPane = new JPanel();
contentPane.setBackground(new Color(100, 149, 237));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
restaurantTxt = new JTextField();
restaurantTxt.setHorizontalAlignment(SwingConstants.CENTER);
restaurantTxt.setEditable(false);
restaurantTxt.setText("Matthew's Restaurant");
restaurantTxt.setBounds(340, 23, 191, 20);
contentPane.add(restaurantTxt);
restaurantTxt.setColumns(10);
numDiners = new JTextField("", 10);
numDiners.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) { //method to only allow the textfield to accept numbers, backspace or delete.
char c=e.getKeyChar();
if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
e.consume(); // consume will not allow the user to enter anyhting but a number.
if (e.getKeyCode() == 10) {
JOptionPane.showMessageDialog(Restaurant.this, "Please select a meal");
}
}
}
});
numDiners.setBounds(448, 89, 83, 26);
contentPane.add(numDiners);
numDiners.setColumns(10);
JButton numDinersSubBtn = new JButton("Submit");
numDinersSubBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dinerNumber = numDiners.getText();
numDiners.setText(""); // this sets the textfield to be blank when the submit button is entered.
}
});
numDinersSubBtn.setBounds(612, 89, 83, 29);
contentPane.add(numDinersSubBtn);
numDinersTxt = new JTextField();
numDinersTxt.setEditable(false);
numDinersTxt.setText("Number of diners ?");
numDinersTxt.setBounds(251, 89, 130, 26);
contentPane.add(numDinersTxt);
numDinersTxt.setColumns(10);
tableNumTxt = new JTextField();
tableNumTxt.setEditable(false);
tableNumTxt.setText("Table number ?");
tableNumTxt.setBounds(252, 164, 130, 26);
contentPane.add(tableNumTxt);
tableNumTxt.setColumns(10);
numTable = new JTextField("", 10);
numTable.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c=e.getKeyChar();
if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
e.consume();
//method to only allow the textfield to accept numbers, backspace or delete
if (e.getKeyCode() == 10) { // consume will not allow the user to enter anyhting but a number.
//tableNumber = numTable.getText();
//System.out.println("enter pressed");
}
}
}
});
numTable.setBounds(448, 164, 83, 26);
contentPane.add(numTable);
numTable.setColumns(10);
numTableSubBtn = new JButton("Submit");
numTableSubBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tableNumber = numTable.getText();
numTable.setText("");
}
});
numTableSubBtn.setBounds(612, 164, 83, 29);
contentPane.add(numTableSubBtn);
proceedMenuBtn = new JButton("Proceed to menu");
proceedMenuBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuPage nw = new MenuPage(); // the new visual class window has been created and called MenuPage. The proceedMenuBtn
nw.NewScreen(); // takes the user to the NewScreen.
}
});
proceedMenuBtn.setBounds(608, 265, 135, 29);
contentPane.add(proceedMenuBtn);
JTextPane txtpnWelcomeToMatthews = new JTextPane();
txtpnWelcomeToMatthews.setEditable(false);
txtpnWelcomeToMatthews.setText("Welcome to Matthew's Restaurant\n\nTo get started with your dining experience please enter the number of diners and the table number of your choice.\n\nPress Submit when done.\n\nPress proceed to menu.\n\nEnjoy.");
txtpnWelcomeToMatthews.setBounds(20, 38, 183, 256);
contentPane.add(txtpnWelcomeToMatthews);
}
}
I'm trying to create a sort of log of all the keys hit, at the moment I just need to figure out how to either:
Link the position of the "text" to the scroll bar to the right
OR
Add a different component which is suited better to hold large amounts of multiple line text.
What am I doing wrong here? Thanks!
public class MacroMakerGui extends JFrame {
public static final long serialVersionUID = 1L;
public static JPanel contentPane;
public static JTextField textField = new JTextField();;
public static MacroKeyListener keylistener = new MacroKeyListener(textField);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MacroMakerGui frame = new MacroMakerGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MacroMakerGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 126, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnNewButton = new JButton("Record Macro");
btnNewButton.setBounds(10, 220, 99, 30);
contentPane.add(btnNewButton, null);
textField.setBounds(10, 189, 99, 20);
contentPane.add(textField);
textField.setColumns(10);
JEditorPane editorPane = new JEditorPane();
editorPane.setBounds(10, 11, 84, 153);
contentPane.add(editorPane);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(93, 11, 17, 153);
contentPane.add(scrollBar);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnNewButton.addKeyListener(keylistener);
}
});
}
}
Instead of JScrollBar, use JScrollPanel. Add that to the contentPane, and add your editorPane as a chiled of the JScrollPanel.
public class Sort_BenchMark extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnBubbleSort;
private JLabel label_1;
private JButton btnGenerate;
private JButton btnSelectionSort;
private JLabel lblSs;
private JLabel lblStatus;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Sort_BenchMark frame = new Sort_BenchMark();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sort_BenchMark()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField("Enter ");
textField.setForeground(Color.GRAY);
textField.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
});
textField.setBounds(29, 30, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
label_1 = new JLabel("");
label_1.setBounds(334, 20, 120, 30);
contentPane.add(label_1);
btnBubbleSort = new JButton("Bubble Sort");
btnBubbleSort.setBounds(204, 20, 120, 30);
contentPane.add(btnBubbleSort);
btnSelectionSort = new JButton("Selection Sort");
btnSelectionSort.setBounds(204, 70, 120, 30);
contentPane.add(btnSelectionSort);
lblSs = new JLabel("");
lblSs.setBounds(334, 70, 120, 30);
contentPane.add(lblSs);
lblStatus = new JLabel("");
lblStatus.setBounds(75, 87, 93, 23);
contentPane.add(lblStatus);
final JRadioButton rdbtnAvgCase = new JRadioButton("Avg Case");
rdbtnAvgCase.setBounds(29, 150, 109, 23);
contentPane.add(rdbtnAvgCase);
ButtonGroup b = new ButtonGroup();
b.add(rdbtnAvgCase);
btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnBubbleSort.setEnabled(true);
btnSelectionSort.setEnabled(true);
final String s = textField.getText();
if(s.contentEquals(""))
{
lblStatus.setText("Enter length");
}
else
{
lblStatus.setText("Ready");
if(rdbtnAvgCase.isSelected())
{
btnBubbleSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
btnBubbleSort.setEnabled(false);
label_1.setText("done");
btnBubbleSort.setEnabled(true);
}
});
t1.start();
}
});
btnSelectionSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t3 = new Thread(new Runnable()
{
#Override
public void run()
{
btnSelectionSort.setEnabled(false);
lblSs.setText("done");
btnSelectionSort.setEnabled(true);
}
});
t3.start();
}
});
}
}
}
});
btnGenerate.setBounds(64, 62, 88, 25);
contentPane.add(btnGenerate);
}
}
The above code is about Swing.
The actual code how i designed is:-(In the frame)
Select the Average Case (RadioButton)
Enter any number in textfield (Enter)
click on generate
click on any sort button(Bubble Sort and Selection Sort)
Now, whats the problem is, If I click on BubbleSort the text field gets cleared. But it should not happen as per I designed. Can anyone suggest me the solution so that text field wont get clear after entered anything in it?
These lines here:
#Override
public void focusGained(FocusEvent e) {
textField.setText(""); //HERE
textField.setForeground(Color.BLACK);
}
in the focus listener code says that when you click in the textfield then set its text to a empty string.
Firstly, horrible nested ActionPerformed you've got there.
That aside, Vincent Ramdhanie is right as to where the problem is originating. The reason why it only happens when you click a certain button, is because when you disable a button, then it cannot have focus, which forces the focus to be on something else, which in the disable-btnBubbleSort's case, appears to be your textfield.
Instead of btnSelectionSort.setEnabled(false) and btnSelectionSort.setEnabled(true), try using setVisible(false) and setVisible(true).
If that doesn't work, drop the onfocus-part, and do something with a mouse-click event instead.
I'm sorry for posting this but, I can't find out why my Array of JButtons won't display in my ButtonsPanel. After adding them, I tried using my code in a separate class to test my code and it worked!, but why don't my buttons show up in this class?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class WordGui extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JLabel lblNewLabel_1;
private JPanel buttonPanel;
private JTextArea txtrShuffleHistory;
private Word word ;
private boolean val;
private JButton btnGo;
private JButton button;
private JButton btnShuffleText;
private JPanel panel_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
com.jtattoo.plaf.noire.NoireLookAndFeel.setTheme("Small-Font","","05:Bageo,Dexter");
UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WordGui frame = new WordGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WordGui() {
setTitle("Word App Gui");
setResizable(false);
setBounds(new Rectangle(100, 100, 600, 200));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 719, 394);
contentPane = new JPanel();
contentPane.setBounds(new Rectangle(100, 100, 600, 200));
contentPane.setSize(new Dimension(600, 250));
contentPane.setPreferredSize(new Dimension(600, 250));
contentPane.setBorder(new LineBorder(new Color(204, 0, 255), 5, true));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(204, 0, 255), 3, true));
panel.setBounds(10, 11, 683, 45);
contentPane.add(panel);
panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(204, 0, 255), 3, true));
panel_1.setBounds(140, 59, 553, 286);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel = new JLabel("Enter a new word here:");
lblNewLabel.setBounds(10, 11, 183, 14);
panel_1.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(224, 8, 157, 20);
panel_1.add(textField);
textField.setColumns(10);
btnGo = new JButton("Go");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(ev.getSource()== btnGo){
assignWord(textField.getText());
}
}
});
btnGo.setBounds(391, 7, 57, 23);
panel_1.add(btnGo);
JLabel lblOriginalText = new JLabel("Original Text:");
lblOriginalText.setBounds(10, 36, 84, 14);
panel_1.add(lblOriginalText);
lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setToolTipText("This is the original text entered\r\n");
lblNewLabel_1.setHorizontalTextPosition(SwingConstants.CENTER);
lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_1.setBorder(new LineBorder(new Color(204, 0, 255), 3, true));
lblNewLabel_1.setBounds(90, 36, 358, 79);
panel_1.add(lblNewLabel_1);
JLabel lblShuffledText = new JLabel("Shuffled Text:");
lblShuffledText.setBounds(10, 126, 110, 14);
panel_1.add(lblShuffledText);
buttonPanel = new JPanel();
buttonPanel.setBorder(new LineBorder(new Color(204, 0, 255), 4, true));
buttonPanel.setBounds(10, 147, 533, 56);
panel_1.add(buttonPanel);
buttonPanel.setLayout(new GridLayout(1, 0, 0, 0));
btnShuffleText = new JButton("Shuffle Text");
btnShuffleText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(ev.getSource() == btnShuffleText){
shuffle();
}
}
});
btnShuffleText.setBounds(90, 214, 196, 39);
panel_1.add(btnShuffleText);
button = new JButton("Reset");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(ev.getSource() == button){
textField.setText("");
getGoBtn().setEnabled(true);
getShuffleBtn().setEnabled(false);
getButtonPanel().removeAll();
}
}
});
button.setBounds(294, 214, 196, 39);
panel_1.add(button);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBounds(10, 59, 128, 258);
contentPane.add(scrollPane);
txtrShuffleHistory = new JTextArea();
txtrShuffleHistory.setToolTipText("View Shuffle History");
txtrShuffleHistory.setText("Shuffle History\r\n=================");
txtrShuffleHistory.setEditable(false);
scrollPane.setViewportView(txtrShuffleHistory);
JButton btnClear = new JButton("Clear");
btnClear.setBounds(10, 322, 126, 23);
contentPane.add(btnClear);
valid();
}
public void valid(){
JTextField field = new JTextField();
while(val == false){
int result = JOptionPane.showConfirmDialog(null,field, "Enter a Text?", JOptionPane.OK_CANCEL_OPTION);
if(result == JOptionPane.OK_OPTION){
String s = field.getText();
assignWord(s);
}
else if(result == JOptionPane.CANCEL_OPTION){
getResetBtn().setEnabled(false);
getShuffleBtn().setEnabled(false);
val = true;
}
}
}
public void assignWord(String s){
try{word = new Word(s);
val = true;
getTextLabel().setText("<html><body><font size = 30 >"+s+"</font></body></html>");
getTextArea().append("\nOriginal Word :"+s+"\n=================");
getGoBtn().setEnabled(false);
getResetBtn().setEnabled(true);
getShuffleBtn().setEnabled(true);
}
catch(RuntimeException e){JOptionPane.showMessageDialog(getParent(),e.getMessage()); val = false;}
}
public void shuffle(){
word.shuffle();
getButtonPanel().removeAll();
String temp = word.getShuffledText();
JButton[] buttons = new JButton[word.getText().length()];
for(int x = 0; x < word.getShuffledText().length(); x++){
buttons[x] = new JButton(""+temp.charAt(x));
getBody().add(buttons[x]);
buttons[x].setVisible(true);
}
getTextArea().append("\n"+word.getShuffledText());
}
public JLabel getTextLabel() {
return lblNewLabel_1;
}
public JPanel getButtonPanel() {
return buttonPanel;
}
public JTextArea getTextArea() {
return txtrShuffleHistory;
}
public JTextField getTextField() {
return textField;
}
public JButton getGoBtn() {
return btnGo;
}
public JButton getResetBtn() {
return button;
}
public JButton getShuffleBtn() {
return btnShuffleText;
}
public JPanel getBody() {
return panel_1;
}
}
I have the shuffle method which does the adding of JButtons, I'm sorry for posting this long long code, but can somebody compile this and figure out why the buttons wont show ? I tried changing the panels layout but still doesn't work,
here's the supporting class
import java.util.*;
public class Word {
private String text;
private List<Character> charList;
private String shuffled;
public Word(String str) {
if (str.length() < 3) {
throw new RuntimeException("Word must be more than 2 characters...");
}
if(invalid(str)) {
throw new RuntimeException("Word must not be composed of a single character...");
}
text = str.toUpperCase();
charList = getChars();
shuffle();
}
private boolean invalid(String s) {
int count = 1;
for (int i = 1; i < s.length(); i++) {
if (Character.toLowerCase(s.charAt(0)) == Character.toLowerCase(s.charAt(i)))
count++;
}
return (count == s.length());
}
private ArrayList<Character> getChars() {
ArrayList<Character> tempList = new ArrayList<Character>();
for (int i = 0; i < text.length(); i++) {
tempList.add(text.charAt(i));
}
return tempList;
}
public void shuffle() {
String orig = shuffled;
String tempShuffled;
do {
Collections.shuffle(charList);
tempShuffled = listToString();
} while (tempShuffled.equals(orig) || tempShuffled.equals(text));
shuffled = tempShuffled;
}
private String listToString() {
String strTemp = "";
for (Character ch: charList) {
strTemp += ch;
}
return strTemp;
}
public String toString() {
return text;
}
public String getShuffledText() {
return shuffled;
}
public String getText(){
return text;
}
}
You're using absolute positioning (null layout) for the JPanel panel_1. Each component in the JButton array buttons will have a default size of 0 x 0 so will not appear.
Swing was designed to use a layout manager so its recommended to always use one.
It removes the need to set component dimensions and locations. Use one for panel_1, such as GridLayout.
Also invoke
panel_1.revalidate();
panel_1.repaint();
after adding all of the buttons from the array.
Aside: Java naming conventions show that variables use camelCase such as panelOne instead of panel_1.
panel_1.setLayout(null);
Here, you're basically left with absolute positioning, so you'll need to set size and position for each of your JButtons. Use setBounds
Something strange happened to me. For some reason, it takes a long time(1.60900 seconds) till it runs the following line:
textArea = new JTextArea();
I declared textArea variable as globally.
This only happens in one window (Jframe). In others it does not happen.
public class FAQ extends JFrame
{
/*--------attributes--------*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel;
private JScrollPane scrollPaneInput;
private JScrollPane scrollPaneQuestions;
private JPanel paneQuestions;
private JPanel paneSelectOrNewFAQ;
private JButton btnEditSelection;
private JButton btnNewFAQ;
public JTextArea textArea;
private JLabel lblQuestions;
public JList list;
private User user;
private FAQ currentWindow;
private int selectedFaq = 0;
private DatabaseManager DManager;
private Vector<FAQ_class> Faqs = new Vector<FAQ_class>();
private JButton btnNewButton;
/*--------methods--------*/
public FAQ(User _user,DatabaseManager DM)
{
setResizable(false);
DManager = DM;
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent arg0) {
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
Menu menu = new Menu(user,DManager);
menu.setVisible(true);
}
});
currentWindow = this;
user = _user;
addGui();
if(!user.rule.equals("patient"))
{
btnEditSelection.setEnabled(true);
btnNewFAQ.setEnabled(true);
}
loadFaqs();
}//end of FAQ
public void loadFaqs()
{
Faqs = DManager.getQuestionsList();
Vector<String> temp = new Vector<String>();
for(int i = 0 ; i < Faqs.size();i++)
{
temp.addElement(Faqs.get(i).question);
}
list.setListData(temp);
}
public void addGui()
{
setTitle("FAQ - Online medical help");
setIconImage(Toolkit.getDefaultToolkit().getImage(FAQ.class.getResource("/Images/question.png")));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 708, 438);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 0, 0, 0));
addPanel();
addPanes();
addButtons();
addGroupLayout();
addJTextArea();
}//end of addGui
public void addPanel()
{
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(panel);
}//end of addPanel
public void addPanes()
{
scrollPaneInput = new JScrollPane();
scrollPaneInput.setBounds(327, 0, 365, 398);
paneQuestions = new JPanel();
paneQuestions.setBounds(0, 0, 317, 38);
paneQuestions.setBackground(new Color(154, 205, 50));
}//end of addScrollPanes
public void addButtons()
{
}//end of addButtons
public void addJTextArea()
{
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(new Font("Courier New", Font.PLAIN, 14));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
scrollPaneInput.setViewportView(textArea);
}//end of addJTextArea
public void addGroupLayout()
{
lblQuestions = new JLabel("Questions");
lblQuestions.setHorizontalAlignment(SwingConstants.CENTER);
lblQuestions.setBounds(0, 0, 317, 38);
lblQuestions.setForeground(new Color(255, 255, 255));
lblQuestions.setFont(new Font("Tahoma", Font.BOLD, 22));
panel.setLayout(null);
scrollPaneQuestions = new JScrollPane();
scrollPaneQuestions.setBounds(0, 37, 317, 318);
list = new JList();
list.setSelectionBackground(new Color(154, 205, 50));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
try
{
for(int i = 0; i<Faqs.size();i++)
{
if(!list.isSelectionEmpty())
if(Faqs.get(i).question.equals(list.getSelectedValue().toString()))
{
textArea.setText(Faqs.get(i).answer);
selectedFaq = i;
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
scrollPaneQuestions.setViewportView(list);
panel.add(scrollPaneQuestions);
panel.add(paneQuestions);
paneQuestions.setLayout(null);
paneQuestions.add(lblQuestions);
panel.add(scrollPaneInput);
paneSelectOrNewFAQ = new JPanel();
paneSelectOrNewFAQ.setBounds(0, 348, 317, 50);
btnEditSelection = new JButton("Edit Selected");
btnEditSelection.setBounds(68, 11, 131, 40);
btnEditSelection.setEnabled(false);
btnEditSelection.addActionListener(new ActionListener() {
//open EditFAQ to edit FAQ
public void actionPerformed(ActionEvent e) {
if(!list.isSelectionEmpty())
{
EditFAQ faq = new EditFAQ(user,Faqs.get(selectedFaq),currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
else
{
JOptionPane.showMessageDialog(null,"You must select for the list first.");
}
}
});
btnEditSelection.setIcon(new ImageIcon(FAQ.class.getResource("/Images/tool.png")));
btnNewFAQ = new JButton("New FAQ");
btnNewFAQ.setBounds(203, 11, 114, 40);
btnNewFAQ.setEnabled(false);
btnNewFAQ.addActionListener(new ActionListener() {
//open EditFAQ to make new FAQ
public void actionPerformed(ActionEvent e) {
EditFAQ faq = new EditFAQ(user,null,currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
});
btnNewFAQ.setMinimumSize(new Dimension(95, 23));
btnNewFAQ.setMaximumSize(new Dimension(95, 23));
btnNewFAQ.setPreferredSize(new Dimension(95, 23));
btnNewFAQ.setIcon(new ImageIcon(FAQ.class.getResource("/Images/add.png")));
btnNewButton = new JButton("");
btnNewButton.setBounds(0, 10, 42, 41);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnNewButton.setIcon(new ImageIcon(FAQ.class.getResource("/Images/left.png")));
panel.add(paneSelectOrNewFAQ);
paneSelectOrNewFAQ.setLayout(null);
paneSelectOrNewFAQ.add(btnNewButton);
paneSelectOrNewFAQ.add(btnEditSelection);
paneSelectOrNewFAQ.add(btnNewFAQ);
}//end of addGroupLayout
}//end of class
Something strange happened to me. For some reason, it takes a long time(5 second~) till it runs the following line: Run this class and give me the result:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTextArea;
public class JTextAreaRunningTime {
JTextArea textArea;
public JTextAreaRunningTime(){
long startTime = System.currentTimeMillis();
textArea = new JTextArea();
long endTime = System.currentTimeMillis();
NumberFormat nf = new DecimalFormat("#0.00000");
String totalTime = nf.format((endTime-startTime)/1000d);
System.out.println("Execution time is " + totalTime + " seconds");
}
public static void main (String...argW){
new JTextAreaRunningTime();
}
}