Java, runing "textArea = new JTextArea()" taking too much time - java

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();
}
}

Related

How to switch JPanel from different classes with mouseClicked?

I'm learning javax.swing right now and I'm just trying some things out. But now I'm facing a problem I just can't solve. When I click the JLabel for changing the page (jpanel), nothing happens. It won't remove and show the other jpanel.
I also added a
public final HomeGUI getMainFrame() {
return this;
}
and at the mouseClicked(MouseEvent e)
gui.getMainFrame().removeAll();
and I tried it also with
gui.getMainFrame().mainPanel.removeAll();
My GUI:
public class HomeGUI extends JFrame {
private static final long serialVersionUID = 1L;
JPanel mainPanel = new JPanel(new CardLayout());
final CardLayout cl = new CardLayout();
final JPanel mainPanel = new JPanel(cl);
Panel panel;
Page2 page2;
public HomeGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1200, 650);
this.setTitle("Terminal");
this.setLocationRelativeTo(null);
this.setLayout(new BorderLayout(1,1));
panel = new Panel();
panel.Inhalt();
page2 = new Page2();
page2.Inhalt();
this.add(mainPanel);
mainPanel.add(panel, "Seite1");
mainPanel.add(page2, "Seite2");
cl.show(mainPanel, "panel");
}
public static void main(String[] args) {
HomeGUI terminal = new HomeGUI();
terminal.setResizable(false);
terminal.setVisible(true);
}
}
the Panel:
class Panel extends JPanel {
private HomeGUI gui;
Page2 page2;
private static final long serialVersionUID = 1L;
JPanel Panel;
JLabel title = new JLabel("Willkommen");
JLabel bgc = new JLabel("");
JLabel menuStrich = new JLabel();
JLabel menuTitle = new JLabel("Menu");
JLabel menuHome = new JLabel("Home");
JLabel menuSeite2 = new JLabel("Seite2");
public void Inhalt() {
this.setBackground(new Color(230, 230, 230));
this.add(title);
this.add(bgc);
this.setLayout(null);
//Seite1
title.setSize(300, 50);
title.setLocation(300, 20);
title.setFont(new Font("Alba Matter", Font.PLAIN, 48));
//Menu
bgc.setLayout(null);
bgc.setOpaque(true);
bgc.setBackground(new Color(66, 78, 245));
bgc.setSize(280, 650);
bgc.setLocation(0, 0);
bgc.add(menuTitle);
bgc.add(menuStrich);
bgc.add(menuHome);
bgc.add(menuSeite2);
menuTitle.setLocation(90, 10);
menuTitle.setSize(100, 50);
menuTitle.setFont(new Font("Bahnschrift", Font.PLAIN, 38));
menuTitle.setForeground(Color.white);
menuStrich.setLocation(10, 55);
menuStrich.setSize(260, 5);
menuStrich.setBackground(new Color(240, 240, 240));
menuStrich.setOpaque(true);
menuHome.setLocation(30, 70);
menuHome.setSize(200, 50);
menuHome.setFont(new Font("Concert One", Font.PLAIN, 36));
menuHome.setForeground(Color.white);
menuSeite2.setLocation(30, 130);
menuSeite2.setSize(200, 50);
menuSeite2.setForeground(Color.LIGHT_GRAY);
menuSeite2.setFont(new Font("Concert One", Font.PLAIN, 32));
menuSeite2.addMouseListener(new menuSeite2Event());
}
private class menuSeite2Event extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
//show page2
gui.cl.show(gui.mainPanel, "page2");
}
#Override
public void mouseEntered(MouseEvent e) {
menuSeite2.setForeground(Color.CYAN);
}
#Override
public void mouseExited(MouseEvent e) {
menuSeite2.setForeground(Color.LIGHT_GRAY);
}
}
}
class Page2 extends JPanel {
private static final long serialVersionUID = 1L;
JPanel Panel;
JLabel title = new JLabel("Willkommen");
JLabel bgc = new JLabel("");
JLabel menuStrich = new JLabel();
JLabel menuTitle = new JLabel("Menu");
JLabel menuHome = new JLabel("Home");
JLabel menuSeite2 = new JLabel("Seite2");
public void Inhalt() {
this.setBackground(new Color(230, 230, 230));
this.add(title);
this.add(bgc);
this.setLayout(null);
//Seite1
title.setSize(300, 50);
title.setLocation(300, 20);
title.setFont(new Font("Alba Matter", Font.PLAIN, 48));
//Menu
bgc.setLayout(null);
bgc.setOpaque(true);
bgc.setBackground(new Color(66, 78, 245));
bgc.setSize(280, 650);
bgc.setLocation(0, 0);
bgc.add(menuTitle);
bgc.add(menuStrich);
bgc.add(menuHome);
bgc.add(menuSeite2);
menuTitle.setLocation(90, 10);
menuTitle.setSize(100, 50);
menuTitle.setFont(new Font("Bahnschrift", Font.PLAIN, 38));
menuTitle.setForeground(Color.white);
menuStrich.setLocation(10, 55);
menuStrich.setSize(260, 5);
menuStrich.setBackground(new Color(240, 240, 240));
menuStrich.setOpaque(true);
menuHome.setLocation(30, 70);
menuHome.setSize(200, 50);
menuHome.setFont(new Font("Concert One", Font.PLAIN, 36));
menuHome.setForeground(Color.white);
menuHome.addMouseListener(new menuHomeEvent());
menuSeite2.setLocation(30, 130);
menuSeite2.setSize(200, 50);
menuSeite2.setForeground(Color.white);
menuSeite2.setFont(new Font("Concert One", Font.PLAIN, 32));
}
private class menuHomeEvent extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
//show Home
}
#Override
public void mouseEntered(MouseEvent e) {
menuHome.setForeground(Color.CYAN);
}
#Override
public void mouseExited(MouseEvent e) {
menuHome.setForeground(Color.LIGHT_GRAY);
}
}
}
INFO: all classes are in 1 file.

How to stop JDialog from closing when you hit the Enter key?

I am trying to stop my JDialog from closing when the Enter key is pushed. I have already tried using getRootPane().setDefaultButton(null); but it is still not working. I am calling this constructor for my JDialog from the main JFrame. Here is my code:
public class CustomSaleDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField txtScanBarcode;
private JTextField txtNumSold;
private String barcode;
private int numTickets;
public void setNumTickets(int num) {
numTickets = num;
}
public void setBarCode(String code) {
barcode = code;
}
public int getNumTickets() {
return numTickets;
}
public String getBarCode() {
return barcode;
}
public CustomSaleDialog(JFrame f) {
getRootPane().setDefaultButton(null); //This is what I tried
setTitle("Custom Sale");
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
JLabel lblMakeACustom = new JLabel("Make a Custom Sale");
lblMakeACustom.setFont(new Font("Tahoma", Font.PLAIN, 25));
lblMakeACustom.setHorizontalAlignment(SwingConstants.CENTER);
lblMakeACustom.setBounds(10, 11, 414, 44);
contentPanel.add(lblMakeACustom);
}
{
JLabel lblScanTicket = new JLabel("Scan Ticket");
lblScanTicket.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblScanTicket.setBounds(20, 73, 102, 20);
contentPanel.add(lblScanTicket);
}
{
JLabel lblNumberOfTickets = new JLabel("Number of Tickets Being Sold");
lblNumberOfTickets.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblNumberOfTickets.setBounds(20, 136, 262, 25);
contentPanel.add(lblNumberOfTickets);
}
{
txtScanBarcode = new JTextField();
txtScanBarcode.setBounds(132, 73, 284, 20);
contentPanel.add(txtScanBarcode);
txtScanBarcode.setColumns(10);
}
{
txtNumSold = new JTextField();
txtNumSold.setBounds(292, 141, 124, 20);
contentPanel.add(txtNumSold);
txtNumSold.setColumns(10);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
barcode = txtScanBarcode.getText();
String numTickets = txtNumSold.getText();
int numTicketsInt = 0;
if (barcode.length() > 0
&& numTickets.matches("[0-9]+")
&& numTickets.length() >= 1) {
numTicketsInt = Integer.parseInt(numTickets);
setBarCode(barcode);
setNumTickets(numTicketsInt);
}
setVisible(false);
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setLocationRelativeTo(f);
setVisible(true);
}
}
And you forget to remove...
getRootPane().setDefaultButton(okButton);
This...
is why you don't use null layouts
Set focusable method or something like this that focuses to false.
remove this line getRootPane().setDefaultButton(okButton); it should work :)

this.dispose() is not working to close a JFrame

When I add:
this.dispose();
The window is not closing, what can I do?.
I use Eclipse with windowsBuilder.
I want to close the actual window to open another window.
My code:
public class Ventana_login extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7948060398287723741L;
private JPanel contentPane;
private JTextField txtUsuario;
private JPasswordField txtContrasena;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ventana_login frame = new Ventana_login();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Ventana_login() {
setTitle("Sistema Gestor de Eventos v1.0");
setResizable(false);
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);
JLabel lblBienvenidoAlSistema = new JLabel("Bienvenido");
lblBienvenidoAlSistema.setHorizontalAlignment(SwingConstants.CENTER);
lblBienvenidoAlSistema.setFont(new Font("Tahoma", Font.BOLD, 16));
lblBienvenidoAlSistema.setBounds(10, 11, 424, 14);
contentPane.add(lblBienvenidoAlSistema);
JLabel lblUsuario = new JLabel("Usuario");
lblUsuario.setHorizontalAlignment(SwingConstants.RIGHT);
lblUsuario.setBounds(96, 79, 70, 14);
contentPane.add(lblUsuario);
JLabel lblContrasena = new JLabel("Contrase\u00F1a");
lblContrasena.setHorizontalAlignment(SwingConstants.RIGHT);
lblContrasena.setBounds(96, 109, 70, 14);
contentPane.add(lblContrasena);
txtUsuario = new JTextField();
txtUsuario.setBounds(176, 76, 150, 20);
contentPane.add(txtUsuario);
txtUsuario.setColumns(10);
JButton btnIniciarSesion = new JButton("Iniciar Sesi\u00F3n");
btnIniciarSesion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Dato_login d_lgn = new Dato_login();
Logica_login l_lgn = new Logica_login();
d_lgn.setUsuario(txtUsuario.getText());
char[] contrasenaChar = txtContrasena.getPassword();
String contrasenaClean = new String(contrasenaChar);
d_lgn.setContrasena(contrasenaClean);
Dato_login d_lgn2 = l_lgn.login(d_lgn.getUsuario(), d_lgn.getContrasena());
if (Logica_login.resultado) {
Ventana_menu v_menu = new Ventana_menu();
v_menu.setVisible(true);
v_menu.setLocationRelativeTo(null);
Ventana_menu.lblPerfilActual.setText(d_lgn2.getPerfil());
Ventana_menu.lblApellidoActual.setText(d_lgn2.getApellido());
Ventana_menu.lblNombreActual.setText(d_lgn2.getNombre());
Ventana_menu.lblUsuarioActual.setText(d_lgn2.getUsuario());
if (Ventana_menu.lblPerfilActual.getText().equals("Portero")) {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(false);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(false);
Ventana_menu.btnReportes.setEnabled(true);
} else {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(true);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(true);
Ventana_menu.btnReportes.setEnabled(true);
}
this.dispose();
} else {
JOptionPane.showMessageDialog(contentPane, "Acceso Denegado", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Exception:\n" + e, "Error: Ventana_login", JOptionPane.ERROR_MESSAGE);
}
}
});
btnIniciarSesion.setBounds(176, 163, 150, 30);
contentPane.add(btnIniciarSesion);
I will assume by window you mean JFrame:
then do:
myJframe.dispatchEvent(new WindowEvent(myJframe, WindowEvent.WINDOW_CLOSING));

How to filter out some data from array list to list field in java

I'm trying to filter data in my array list according to my comboBox selected item wise. I still can't solve this problem.
public class FoodItem {
private String name;
private String type;
public FoodItem(String n,String t){
name=n;
type=t;
}
public String getType(){
return type;
}
public String getName(){
return name;
}
}
sample.java
<code>
public class A2Demo extends JFrame {
private JPanel contentPane;
private JTextField txtName;
List listFoodItem = new List();
JComboBox comboType = new JComboBox();
FoodItem[] foodItems;
private final JTextField txtBudget = new JTextField();
private final JButton btnBudget = new JButton("Search Budget");
private final JTextField textField = new JTextField();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
A2Demo frame = new A2Demo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public A2Demo() {
textField.setBounds(93, 247, 134, 28);
textField.setColumns(10);
txtBudget.setBounds(183, 11, 86, 20);
txtBudget.setColumns(10);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 334);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
foodItems=new FoodItem[2];
foodItems[0]=new FoodItem("Chicken Cutlet","Main");
foodItems[1]=new FoodItem("Chendol","Dessert");
comboType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
comboType.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
JOptionPane.showMessageDialog(null,comboType.getSelectedItem());
}
});
comboType.setBounds(32, 11, 93, 20);
contentPane.add(comboType);
for(int i=0; i<foodItems.length; i++)
comboType.addItem(foodItems[i].getType());
listFoodItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
txtName.setText(listFoodItem.getSelectedItem());
}
});
listFoodItem.setBounds(37, 63, 330, 125);
contentPane.add(listFoodItem);
JLabel lblName = new JLabel("Name");
lblName.setBounds(37, 217, 46, 14);
contentPane.add(lblName);
txtName = new JTextField();
txtName.setBounds(93, 214, 134, 20);
contentPane.add(txtName);
txtName.setColumns(10);
contentPane.add(txtBudget);
btnBudget.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, comboType.getSelectedItem()+ " "+txtBudget.getText());
}
});
btnBudget.setBounds(280, 10, 127, 23);
contentPane.add(btnBudget);
contentPane.add(textField);
}
}
i want to display food name in the list. but combobox changeing to different type my list need to change according l

JButtons Wont Display?

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

Categories