Clicking on JButton(Bubble Sort) clears the JTextField.Why? - java

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.

Related

Is it possible to split initialize section into different classes?

I have been working on some side project involving MySQL, with will use tree different screens: 'menu, ' add breed', 'browse breed'.
At this point section initialize is getting quite large and I would like to split it into 3 different classes.
Is it possible to initialize for example JPanel outside Window class?
public class Window {
public static void setBreed()
{
for(int i=0; i<16;i++) {
breedLabels[i].setText(breedInfo[i]);
breedLabels[i].setBounds(600,100+i*30,300, 100);
breedLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(breedLabels[i]);
}
}
public static void setText()
{
for(int i=0; i<16;i++) {
textLabels[i].setText(text[i]);
textLabels[i].setBounds(300,100+i*30,300, 100);
textLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(textLabels[i]);
}
}
public static String URL = "jdbc:mysql://localhost:3306/chooseyourpuppy";
public static String user = "root";
public static String password = "";
public static String query = "select * from breeds";
static String [] breedInfo = new String[16];
static String [] text = new String[16];
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
View.connect(URL, user, password, query);
}
public Window() {
initialize();
}
private JFrame frame;
public JPanel addBreed;
public static JPanel viewBreed;
public JPanel menu;
public static JLabel[] textLabels;
public static JLabel[] breedLabels;
private void initialize() {
final int WIDTH = 1280, HEIGHT = 720;
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("MyBREEDS Viewer");
frame.setResizable(false);
frame.setVisible(true);
//header
JPanel red = new JPanel();
red.setBounds(400, 0, 888, 80);
frame.getContentPane().add(red);
red.setBackground(new Color(204, 0, 0));
red.setLayout(null);
JPanel darkGrey = new JPanel();
darkGrey.setBounds(0, 0, 387, 80);
frame.getContentPane().add(darkGrey);
darkGrey.setBackground(new Color(51, 51, 51));
darkGrey.setLayout(null);
JLabel txtpnChoose = new JLabel();
txtpnChoose.setForeground(new Color(240, 240, 240));
txtpnChoose.setBounds(56, 11, 367, 63);
txtpnChoose.setFont(new Font("Verdana", Font.BOLD, 46));
txtpnChoose.setText("Choose your");
txtpnChoose.setBackground(null);
darkGrey.add(txtpnChoose);
JLabel txtpnPuppy = new JLabel();
txtpnPuppy.setBounds(5, 11, 166, 63);
txtpnPuppy.setForeground(new Color(240, 240, 240));
txtpnPuppy.setFont(new Font("Nunito-Bold", Font.BOLD, 46));
txtpnPuppy.setText("puppy");
txtpnPuppy.setBackground(null);
red.add(txtpnPuppy);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, WIDTH, HEIGHT);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
JButton btnMenu = new JButton("Back to menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(menu);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnMenu.setForeground(Color.WHITE);
btnMenu.setBackground(new Color(51, 51, 51));
btnMenu.setFont(new Font("Verdana", Font.BOLD, 18));
btnMenu.setBounds(660, 20, 180, 40);
btnMenu.setBorderPainted(false);
btnMenu.setFocusPainted(false);
red.add(btnMenu);
//menu
menu = new JPanel();
menu.setBackground(Color.WHITE);
layeredPane.add(menu, "name_410359960271086");
menu.setLayout(null);
JButton btnBrowse = new JButton("Browse breeds");
btnBrowse.setBounds(100, 300, 400, 200);
btnBrowse.setFont(new Font("Verdana", Font.PLAIN, 40));
btnBrowse.setBorder(new LineBorder(Color.DARK_GRAY));
btnBrowse.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnBrowse.setBackground(Color.WHITE);
btnBrowse.setRequestFocusEnabled(false);
btnBrowse.setVisible(true);
btnBrowse.setFocusPainted(false);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(viewBreed);
layeredPane.repaint();
layeredPane.revalidate();
setText();
setBreed();
}
});
btnBrowse.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnBrowse.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnBrowse.setBackground(Color.WHITE);
}
});
menu.add(btnBrowse);
addBreed = new JPanel();
layeredPane.add(addBreed, "name_410359942089403");
addBreed.setVisible(false);
addBreed.setBackground(Color.WHITE);
addBreed.setLayout(null);
//view breed window
viewBreed = new JPanel();
layeredPane.add(viewBreed, "name_410359924014670");
viewBreed.setLayout(null);
viewBreed.setVisible(false);
viewBreed.setBackground(Color.WHITE);
ImageIcon previous = new ImageIcon("src/images/previous.png");
ImageIcon previousHover = new ImageIcon("src/images/previousHover.png");
JButton prevBreed = new JButton(previous);
prevBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
prevBreed.setIcon(previousHover);
}
#Override
public void mouseExited(MouseEvent e) {
prevBreed.setIcon(previous);
}
});
prevBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(false);
}
});
prevBreed.setBounds(30, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(prevBreed);
prevBreed.setRequestFocusEnabled(false);
prevBreed.setOpaque(false);
prevBreed.setContentAreaFilled(false);
prevBreed.setBorderPainted(false);
prevBreed.setFocusPainted(false);
ImageIcon next = new ImageIcon("src/images/next.png");
ImageIcon nextHover = new ImageIcon("src/images/nextHover.png");
JButton nextBreed = new JButton(next);
nextBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
nextBreed.setIcon(nextHover);
}
#Override
public void mouseExited(MouseEvent e) {
nextBreed.setIcon(next);
}
});
nextBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(true);
}
});
nextBreed.setBounds(1140, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(nextBreed);
nextBreed.setRequestFocusEnabled(false);
nextBreed.setVisible(true);
nextBreed.setOpaque(false);
nextBreed.setContentAreaFilled(false);
nextBreed.setBorderPainted(false);
nextBreed.setFocusPainted(false);
//add breed window
JButton btnAdd = new JButton("Add new breed");
btnAdd.setBounds(780, 300, 400, 200);
btnAdd.setFont(new Font("Verdana", Font.PLAIN, 40));
btnAdd.setBorder(new LineBorder(Color.DARK_GRAY));
btnAdd.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnAdd.setBackground(Color.WHITE);
btnAdd.setRequestFocusEnabled(false);
btnAdd.setFocusPainted(false);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(addBreed);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnAdd.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnAdd.setBackground(Color.WHITE);
}
});
menu.add(btnAdd);
breedLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
breedLabels[i] = new JLabel(breedInfo[i]);
}
textLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
textLabels[i] = new JLabel(breedInfo[i]);
}
}
}
Is it possible to initialize for example JPanel outside Window class?"
Yes. A different class might contain a method that creates & returns a JPanel.
Other tips:
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.
new Font("Verdana", Font.PLAIN, 20) Use defaults or logical fonts (E.G. Font.SERIF) unless the font is supplied with your app. as an embedded resource.
The loop and array of labels that are added to viewBreed suggest it should be a JList rather than a JPanel
layeredPane.removeAll(); .. Ugh.. Use a CardLayout as shown in this answer.
What is the purpose of the JLayeredPane? I expect it's unnecessary purely on the basis that there is so little use for them.

I need a method that goes back to the previous screen

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

How to change the result "0" on calculator?

I'm new to Java and I'm trying to make a calculator but I have a problem with the result. It is always "0". I used eclipse with Swing. My codes are like this:
package calculator1;
import java.awt.BorderLayout;
public class MainForm extends JFrame {
private JPanel contentPane;
private JTextField textResult;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainForm frame = new MainForm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
double number1=0;
double number2=0;
String islem="";
/**
* Create the frame.
*/
public MainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 509, 534);
contentPane = new JPanel();
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
textResult = new JTextField();
textResult.setEditable(false);
textResult.setBounds(5, 5, 486, 42);
textResult.setColumns(10);
JButton btn1 = new JButton("1");
btn1.setBounds(45, 105, 80, 80);
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"1");
}
});
JButton btn4 = new JButton("4");
btn4.setBounds(45, 185, 80, 80);
btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"4");
}
});
JButton btn7 = new JButton("7");
btn7.setBounds(45, 265, 80, 80);
btn7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"7");
}
});
JButton btn5 = new JButton("5");
btn5.setBounds(125, 185, 80, 80);
btn5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"5");
}
});
JButton btn8 = new JButton("8");
btn8.setBounds(125, 265, 80, 80);
btn8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"8");
}
});
JButton btn2 = new JButton("2");
btn2.setBounds(125, 105, 80, 80);
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"2");
}
});
JButton btn3 = new JButton("3");
btn3.setBounds(205, 105, 80, 80);
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"3");
}
});
JButton btn6 = new JButton("6");
btn6.setBounds(205, 185, 80, 80);
btn6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"6");
}
});
JButton btn9 = new JButton("9");
btn9.setForeground(Color.BLACK);
btn9.setBounds(205, 265, 80, 80);
btn9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"9");
}
});
JButton btn0 = new JButton("0");
btn0.setBounds(125, 345, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"0");
}
});
JButton btncarp = new JButton("*");
btncarp.setFont(new Font("Tahoma", Font.PLAIN, 35));
btncarp.setBounds(382, 60, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="*";
number1=Double.parseDouble(textResult.getText());
}
});
JButton btnarti = new JButton("+");
btnarti.setFont(new Font("Tahoma", Font.PLAIN, 35));
btnarti.setBounds(285, 265, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="+";
number1=Double.parseDouble(textResult.getText());
}
});
JButton btneksi = new JButton("-");
btneksi.setFont(new Font("Tahoma", Font.PLAIN, 35));
btneksi.setBounds(285, 105, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="-";
number1=Double.parseDouble(textResult.getText());
}
});
JButton btnbolu = new JButton("/");
btnbolu.setFont(new Font("Tahoma", Font.PLAIN, 35));
btnbolu.setBounds(285, 185, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="/";
number1=Double.parseDouble(textResult.getText());
}
});
JButton btnesittir = new JButton("=");
btnesittir.setForeground(new Color(255, 153, 255));
btnesittir.setFont(new Font("Tahoma", Font.PLAIN, 35));
btnesittir.setBounds(285, 345, 80, 80);
btnesittir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
number1=Double.parseDouble(textResult.getText());
number2=Double.parseDouble(textResult.getText());
**double result=0;**
switch (islem) {
case "*":
result=number1*number2;
break;
case "/":
result=number1/number2;
break;
case "+":
result=number1+number2;
break;
case "-":
result=number1-number2;
break;
default:
break;
} //end switch
**textResult.setText(String.valueOf(result));**
islem="";
}
});
contentPane.setLayout(null);
contentPane.add(textResult);
contentPane.add(btn1);
contentPane.add(btn4);
contentPane.add(btn7);
contentPane.add(btn5);
contentPane.add(btn8);
contentPane.add(btn2);
contentPane.add(btn3);
contentPane.add(btn6);
contentPane.add(btn9);
contentPane.add(btn0);
contentPane.add(btncarp);
contentPane.add(btnesittir);
contentPane.add(btnarti);
contentPane.add(btneksi);
contentPane.add(btnbolu);
}
}
What can I write instead of "double result=0;" ?
Or maybe I need to change something else?
You seem to have some serious logic issues, take a look at...
number1 = Double.parseDouble(textResult.getText());
number2 = Double.parseDouble(textResult.getText());
How are these two numbers ever going to be different, you've taken the value from same source (textResult)
You are setting islem to "" every time the user presses a numeric key, so if the user presses 1+2, islem is now ""...
The question now is, how to fix it...
You need to change your logic, rather than waiting till the user presses the = button, you could perform each calculation as the enter the values...
This would mean that you would need some kind of method which could maintain a running result and carry out the required calculations
For example...
protected void performOperation(double value) {
switch (islem) {
case "*":
result *= value;
break;
case "/":
result /= value;
break;
case "+":
result += value;
break;
case "-":
result -= value;
break;
default:
result = value;
} //end switch
islem = "";
textResult.setText(String.valueOf(result));
}
What this does, is takes a value to be calculated, determines what calculation needs to be performed (if any), updates the textResult field and rests the calculate modifier...
You could need to change all your numeric buttons to call this method with the appropriate value, for example...
JButton btn1 = new JButton("1");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performOperation(1);
}
});
Now, in your original code, all of your modifier buttons did nothing...this is because you kept registering there actions to btn0 instead, so you need to fix that...
JButton btneksi = new JButton("-");
//...
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="-";
number1=Double.parseDouble(textResult.getText());
}
});
They should now set the calculation modifier that they need to use...
JButton btncarp = new JButton("*");
//...
btncarp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem = "*";
}
});
Which should fix the core issues you seem to be having...
You may also want to take a look at How to Use Actions for more details
I just tried to point out your issues that your code has, and
I am sure there are other better ways to solve calculator problem with
less code and more concise
First Major issue, your variable naming is Terrible
For example you named * button , btncarp which does not make sense for whoever will read your code.
Second issue, you add your action listener to button 0 in * , / , and - operation
like
JButton btncarp = new JButton("*"); <---- your button name is btncarp
....
....
btn0.addActionListener(new ActionListener() { <----you add action listener to btn0?!!!
public void actionPerformed(ActionEvent e) {
......
......
}
});
Third issue you never assigned your number1 value , so it turns zero all them time
try this
btnarti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem = "+";
number1 = Double.parseDouble(textResult.getText());
textResult.setText(" ");
}
});
Explanation: you will read number1 value and clear the result box and make it ready for second value that you will read inside your operation method
Fourth: you can read your second number which is number2 in = opration ActionListener section and no need to read number1 at that place
like
btnesittir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
number2=Double.parseDouble(textResult.getText());
....
....
}
}
Please choose some sensible name for your variables
Note: your code is almost ok except the issue that I pointed out and you read your number1 and number2 variables in wrong places

It does not add to an arrayList for some reasons

I've got this strange thing, I'm trying to add to the ArrayList but it does not add, it get the values and everything. Please check the code and brigthen me up.
The class where I am trying to add:
public class ManualProductGUI extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField barcodeField;
private JTextField idField;
private JTextField nameField;
private JTextField priceField;
private JTextField quantityField;
private JTextField infoField;
BasketContainer bc = new BasketContainer();
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
ManualProductGUI dialog = new ManualProductGUI();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public ManualProductGUI() {
setTitle("Product search");
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
barcodeField = new JTextField();
barcodeField.setText("Enter barcode");
barcodeField.setBounds(10, 11, 157, 20);
contentPanel.add(barcodeField);
barcodeField.setColumns(10);
barcodeField.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
barcodeField.setText("");
}
});
barcodeField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int barcode = Integer.parseInt(barcodeField.getText());
ProductCtr prodCtr = new ProductCtr();
Product prod = prodCtr.searchProductByBarcode(barcode);
buildFields(prod);
}
});
infoField = new JTextField();
infoField.setEditable(false);
infoField.setBounds(177, 133, 86, 20);
contentPanel.add(infoField);
infoField.setColumns(10);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("Add");
okButton.setActionCommand("Add");
buttonPane.add(okButton);
okButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addToBasket();
setVisible(false);
dispose();
}
});
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
cancelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setVisible(false);
dispose();
}
});
buttonPane.add(cancelButton);
}
}
}
private void addToBasket()
{
int barcode = Integer.parseInt(barcodeField.getText());
ProductCtr prodCtr = new ProductCtr();
Product prod = prodCtr.searchProductByBarcode(barcode);
bc.addProduct(prod);
}
}
And here is a part of the Container class:
private ArrayList<Product> listOfItems;
public BasketContainer()
{
listOfItems = new ArrayList<>();
}
public void addProduct(Product prod)
{
listOfItems.add(prod);
}
public ArrayList<Product> getProducts()
{
return listOfItems;
}
It prints out the info on the screen, but it does not add. Am I missing something?
Thank you.
You create a new instance of BasketContainer every time, so that new instances will have a new clear ArrayList.
To fix it you should create your BasketContainer instance somewhere (maybe in an init block?) and save the reference, then use it to add the elements.
You're creating a new BasketContainer within the scope of the method.
BasketContainer bc = new BasketContainer();
bc.addProduct(prod);
The addToBasket method should call addProduct on a field of the class it's in.

create your own swing component

A software component is required which allows to find a given word in a given passage, whenever the component find the desired word in the passage the components will invoke all the listener that are attached to it that it has find the desired word.
This component must be used from a Swing UI based application showing user a text field to take a word and a text area for passage. There must be a label which will update its value showing count that how many times the given word has been found within the given passage.
this is my code it's displya gui but count field is not changed or set.
import java.awt.EventQueue;
public class compomentex implements ActionListener{
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
compomentex window = new compomentex();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public interface wordsearcherinterface
{
public void wordsearch();
}
public class wordsearcher implements wordsearcherinterface
{
public String word;
public String paragraph;
public void addwordsearch(wordsearcherinterface obj)
{
obj.wordsearch();
}
public void wordsearch()
{
//if(event.getSource()==Check)
String word;
String Words;
String [] Words2;
int disp=0;
word=textField.getText();
Words=textArea.getText();
Words2=Words.split(" ");
for(int i=0;i<Words2.length;i++)
{
if(Words2[i].equals(word))
{
disp++;
}
}
String show;
show=disp+"";
textField_1.setText(show);
if(disp==0)
{
JOptionPane.showMessageDialog(null, "The Word is not present int Passage");
}
}
}
* Create the application.
public compomentex() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblWord = new JLabel("WORD");
lblWord.setBounds(29, 81, 46, 14);
frame.getContentPane().add(lblWord);
textField = new JTextField();
textField.setBounds(121, 78, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblPassage = new JLabel("PASSAGE");
lblPassage.setBounds(29, 143, 46, 14);
frame.getContentPane().add(lblPassage);
JTextArea textArea = new JTextArea();
textArea.setBounds(97, 161, 196, 90);
frame.getContentPane().add(textArea);
JButton btnCheck = new JButton("CHECK");
btnCheck.setBounds(326, 213, 98, 23);
frame.getContentPane().add(btnCheck);
JLabel lblSeeker = new JLabel("SEEKER");
lblSeeker.setBounds(161, 11, 46, 14);
frame.getContentPane().add(lblSeeker);
JLabel lblCount = new JLabel("COUNT");
lblCount.setBounds(349, 81, 46, 14);
frame.getContentPane().add(lblCount);
textField_1 = new JTextField();
textField_1.setBounds(325, 106, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Thanks in advance
There are lots of issues in your code. I have mentioned corrected code below. Please correct.
First - actionPerformed method is empty.
#Override
public void actionPerformed(ActionEvent arg0) {
new wordsearcher().wordsearch();
}
Second - instance variable textArea is not initialized.
textArea = new JTextArea();
Third - ActionListener is not added on button btnCheck
btnCheck.addActionListener(this);

Categories