JOptionPane.showMessageDialog keeps reappearing - java
My code is supposed to ensure that users only enter a binary string. Everything goes right and in order if I enter a correct binary number (1, 0). But when I enter a wrong number (alphabet or number other than 0 and 1) JOptionPane.ShowMessageDialog appears showing the error message, and when I click "OK" or "Cross" Button it reappears again. So to close the app I have to use the process manager to kill "java.exe".
Here is the complete code for my app:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Bn extends JFrame {
private JLabel l1;
private JLabel l2;
private JLabel l3;
private JTextField tf;
private JButton oc;
private JButton hd;
private JButton dc;
public Bn() {
setTitle("Binary Conversion");
setSize(350 , 190);
setResizable(false);
setLocation(720 , 200);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.CENTER, 25, 10));
l1 = new JLabel(">>>>>>>>BINARY CONVERSION<<<<<<<<");
l2 = new JLabel("Enter The Number:");
l3 = new JLabel(" Convert to: ");
tf = new JTextField(25);
oc = new JButton("Octal");
hd = new JButton("Hexa Decimal");
dc = new JButton("Decimal");
add(l1); // Binary conversion
add(l2); // Enter The Number
add(tf); // Text Field
add(l3); // Conver to
add(oc); // Octal
add(hd); // Hexa Decimal
add(dc); // Decimal
oc.addActionListener(new cvr());
hd.addActionListener(new cvr());
dc.addActionListener(new cvr());
setVisible(true);
}
void res()
{
int b = 0;
String num = tf.getText();
int i , l;
l = num.length();
char ch;
do
{
for (i=0 ; i<l ; i++)
{
b = 0;
ch = num.charAt(i);
if (Character.isDigit(ch) && (ch == 48 || ch == 49))
b=1;
else
{
JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)");
}
}
}
while(b != 1);
}
void occ()
{
res();
String num = tf.getText();
long dec = Long.parseLong(num,2);
String oct = Long.toOctalString(dec);
JOptionPane.showMessageDialog(null, "Octal equivalent is: "+ oct);
}
void hdc()
{
res();
String num = tf.getText();
long dec = Integer.parseInt(num,2);
String hex = Long.toHexString(dec);
JOptionPane.showMessageDialog(null, "Hexa Decimal equivalent is: "+ hex);
}
void dcc()
{
res();
String num = tf.getText();
long decimal = 0, temp, i = 0;
temp = Long.parseLong(num);
while (temp != 0) {
long r = temp % 10;
long value = r * (int)Math.pow(2, i);
i++;
decimal = decimal + value;
temp /= 10;
}
JOptionPane.showMessageDialog(null, "Decimal equivalent is: "+ decimal);
}
private class cvr implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == oc)
{
occ();
}
if (e.getSource() == hd)
{
hdc();
}
if (e.getSource() == dc)
{
dcc();
}
}
}
public static void main(String args[])
{
Bn obj = new Bn();
}
}
The code for JOptionPane is located in void res() method. How can I close this Dialog pane so I may reenter the value for input?
Remove the do { } while loop
do
{
for (i=0 ; i < l ; i++)
{
b = 0;
ch = num.charAt(i);
if (Character.isDigit(ch) && (ch == 48 || ch == 49))
b=1;
else
{
JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)");
}
}
}
while(b != 1);
Related
Java: Fixing array "linking" to allow for resetting
Firstly, I know Lists are better in almost(if not all) every way. I have encountered a substantial bug in an encoder program that I am making. In this program, I have a button that resets the "wheels" responsible for encoding(One of the wheels rotates after every letter encoded). I have a final int[][] called wheelsOriginal that is supposed to store the original value of the int[][] called wheels. Both of these arrays are int[9][36]. I would like a way of making wheelsOriginal stay unchanged throughout the program instead of changing with wheels for some reason. Here is a good way to recreate the problem(Sorry for the lengthy intToChar and charToInt methods!): Main class: import java.awt.*; import javax.swing.*; public class mainClass { public static void main(String[] args) { JFrame frame = new JFrame("Encoder"); frame.setBackground(new Color(225,225,225)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Display d = new Display(); frame.add(d); frame.pack(); frame.setResizable(false); frame.setVisible(true); } } Display class: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Display extends JPanel implements ActionListener { static JButton button; static JLabel letter; static int currentKey = -10; static int wheel = 0; static int[][] wheels = { {-3,10,-6,2,20,-7,22,5,23,4,6,-9,3,26,0,15,21,-2,13,14,12,1,17,11,-8,-5,18,8,24,9,25,7,19,16,-4,-1}, {9,22,14,12,18,-3,3,6,16,1,-7,25,24,19,-8,8,21,20,5,-6,-2,26,15,-9,23,10,11,0,-5,4,-4,2,17,-1,13,7}, {18,20,-9,15,12,-6,16,-4,-5,14,24,-7,-8,-3,-1,1,4,7,8,25,10,11,5,6,13,22,19,21,23,-2,3,26,17,9,0,2}, {-3,10,-6,2,20,-7,22,5,23,4,6,-9,3,26,0,15,21,-2,13,14,12,1,17,11,-8,-5,18,8,24,9,25,7,19,16,-4,-1}, {9,22,14,12,18,-3,3,6,16,1,-7,25,24,19,-8,8,21,20,5,-6,-2,26,15,-9,23,10,11,0,-5,4,-4,2,17,-1,13,7}, {25,18,5,8,7,-8,4,11,6,-7,26,21,-1,24,15,23,9,-6,-2,13,16,22,-5,10,17,3,1,-9,0,12,2,19,-4,14,20,-3}, {25,18,5,8,7,-8,4,11,6,-7,26,21,-1,24,15,23,9,-6,-2,13,16,22,-5,10,17,3,1,-9,0,12,2,19,-4,14,20,-3}, {25,18,5,8,7,-8,4,11,6,-7,26,21,-1,24,15,23,9,-6,-2,13,16,22,-5,10,17,3,1,-9,0,12,2,19,-4,14,20,-3}, {9,22,14,12,18,-3,3,6,16,1,-7,25,24,19,-8,8,21,20,5,-6,-2,26,15,-9,23,10,11,0,-5,4,-4,2,17,-1,13,7} }; final static int[][] wheelsOriginal = wheels; public Display() { setPreferredSize(new Dimension(250,200)); setFocusable(true); button = new JButton("Reset"); button.setPreferredSize(new Dimension(225,50)); button.setFont(new Font(button.getFont().getFontName(), button.getFont().getStyle(), 25)); letter = new JLabel(" ", SwingConstants.CENTER); letter.setPreferredSize(new Dimension(225,100)); letter.setFont(new Font(letter.getFont().getFontName(), Font.BOLD, 125)); letter.setForeground(new Color(0,0,0)); addKeyListener( new KeyListener() { public void keyPressed(KeyEvent e) { if(currentKey == -10 && e.getKeyCode() >= 65 && e.getKeyCode() <= 90) { currentKey = e.getKeyCode() - 64; letter.setText(encode() + ""); } else if(currentKey == -10 && e.getKeyCode() >= 48 && e.getKeyCode() <= 57) { currentKey = -1 * (e.getKeyCode() - 48); letter.setText(encode() + ""); } } public void keyReleased(KeyEvent e) { currentKey = -10; letter.setText(" "); } public void keyTyped(KeyEvent e) {} } ); button.addActionListener(this); add(button, TOP_ALIGNMENT); add(letter); } public static char encode() { int key = currentKey; for(int i = 0; i < 9; i++) { key = wheels[i][key + 9]; } for(int i = 8; i >= 0; i--) { key = wheels[i][key + 9]; } rotate(wheels[wheel], isEven(wheel)); if(wheel < 8) { wheel++; } else { wheel = 0; } return((char) key); } public static int[] rotate(int[] wheel, boolean positive) { int revolve; if(positive) { revolve = wheel[wheel.length - 1]; for(int i = wheel.length - 2; i > 0; i--) { wheel[i + 1] = wheel[i]; } wheel[0] = revolve; } else { revolve = wheel[0]; for(int i = 1; i < wheel.length - 1; i++) { wheel[i - 1] = wheel[i]; } wheel[wheel.length - 1] = revolve; } return wheel; } public static boolean isEven(int num) { return (num/2 == Math.abs(num/2)); } public void actionPerformed(ActionEvent e) { if(e.getSource().equals(button)) { reset(); grabFocus(); } } public static void reset() { for(int[] i : wheels) { for(int x : i) { System.out.print(x + " "); } System.out.println(""); } System.out.println(" "); for(int[] i : wheelsOriginal) { for(int x : i) { System.out.print(x + " "); } System.out.println(""); } System.out.println(" "); wheels = wheelsOriginal; for(int[] i : wheels) { for(int x : i) { System.out.print(x + " "); } System.out.println(""); } wheel = 0; letter.setText(" "); currentKey = ' '; System.out.println("Pressed"); } } Whenever a key is pressed, the encoded letter appears in the window. Even pressing the same key over and over again will usually produce different letters. Pressing the reset button should reset the encoder so that pressing the letter 'A' three times should produce S, E, and Q in that order. I also have designed this so that whenever you press the reset button, three large bulks of numbers print in the console. These show the wheels array before reset, the wheelsOriginal array, and the product wheels array in that order. If you press keys and click reset several times, you will notice that wheelsOriginal changes with wheels. Please help...
Your problem is that you are creating wheelsOriginal as reference of wheels instead of copy. Thats why when you change wheels, wheelsOriginal changes as well. final static int[][] wheelsOriginal = wheels; Something like this loop can be used to create a copy of wheels int[][] wheelsOriginal = new int[wheels.length][]; for( int i = 0; i < wheelsOriginal.length; i++ ) { wheelsOriginal[i] = Arrays.copyOf( wheels[i], wheels[i].length ); } Also, for your charToInt and IntToChar methods - you could use the fact that chars are numbers and a->z A->Z 0->9 are grouped together to shorten them significantly I didn't test that - in case you decide to use something like this - think and test yourself public int charToInt( char c ) { if( c >= '0' && c <= '9' ) { return '0' - c; } else if( c >= 'A' && c <= 'Z' ) { return c - 'A' + 1; } else if( c >= 'a' && c <= 'z' ) { return c - 'a' + 1; } else { return -10; } } public char intToChar( int c ) { if( c >= -9 && c <= 0 ){ return (char)('0' - c); } else if( c >= 1 && c <= 26 ){ return (char)(c + 'A' - 1); } else{ return ' '; } }
Main method in different class can't detect button press
I'm making a program for practice and it's basically simulating winning/losing Powerball tickets. Anyways, the main class is in launchPowerBall.java and the button that I am trying to detect when clicked is in PowerBallGUI.java. The button works by itself, however, the main in launchPowerBall.java isn't able to detect it even though I set up myself a few setters and getters. Any clue what alternative I can do instead? Because it seems as though even though I run it through a while(true) loop and I keep pressing the button, there seems to be no detection from the main method. Here's the action listener for the JButton: start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // If the button is pressed, delete text field and replace with new content setButtonPressed(true); outputText.setText(""); outputText.setText(outText); } }); Here's what I'm trying to do for the main method: public static void main(String[] args) throws InterruptedException { // Build the GUI object PowerBallGUI GUI = new PowerBallGUI(); GUI.buildGUI(); //GUI.setTextArea("banana"); // Build the PowerBall object PowerBall roll = new PowerBall(); while(true) { if (GUI.getJButton().getModel().isPressed()) { System.out.println("TEST"); } } } Here's the three files if you need to see my code: 1) https://gist.github.com/anonymous/e5950413470202cd1ac6d24e238ff693 2) https://gist.github.com/anonymous/773e4e4454a79c057da78eed038fade1 3) https://gist.github.com/anonymous/82335e634c1f84607d3021b4d683cc65 Powerball... public class PowerBall { private int[] numbers = {0, 0, 0, 0, 0}; private int[] lotteryNumbers = {0, 0, 0, 0, 0}; private int powerBall; private int lotteryPowerBall; private double balance; private double winnings; /*** Constructor Methods ***/ public PowerBall() { powerBall = 0; balance = 1000; winnings = 0; } /*** Mutator Methods ***/ public void randomize() { int i; int highestNumber = 59; int highestPowerball = 32; int temp = 0; for (i = 0; i < numbers.length; i++) { // Choose a random number temp = (int)(Math.random() * highestNumber); numbers[i] = temp; } // Choose a random Powerball number powerBall = (int)(Math.random() * highestPowerball); // Choose the lottery numbers for (i = 0; i < lotteryNumbers.length; i++) { temp = (int)(Math.random() * highestNumber); lotteryNumbers[i] = temp; } lotteryPowerBall = (int)(Math.random() * highestPowerball); } public void calculate() { int matches = 0; int powerballMatches = 0; if (balance > 0) { // Check to see if there are any matches between the two sets of numbers for (int i = 0; i < numbers.length; i++) { for (int j = 0; j < lotteryNumbers.length; j++) { if (numbers[i] == lotteryNumbers[j]) { matches++; } } } // Check to see if the two different powerball numbers match if (powerBall == lotteryPowerBall) { powerballMatches = 1; } // Calculate the balance/winnings if there were any matches if (matches == 0 && powerballMatches == 0) { balance = balance - 2; winnings = winnings - 2; } else if (matches == 0 && powerballMatches == 1) { balance = balance + 4; winnings = winnings + 4; } else if (matches == 0 && powerballMatches == 0 || matches == 1 && powerballMatches == 0) { balance = balance - 2; winnings = winnings - 2; } else if (matches == 2 && powerballMatches == 1) { balance = balance + 7; winnings = winnings + 7; } else if (matches == 3 && powerballMatches == 0) { balance = balance + 7; winnings = winnings + 7; } else if (matches == 3 && powerballMatches == 1) { balance = balance + 100; winnings = winnings + 100; } else if (matches == 4 && powerballMatches == 0) { balance = balance + 100; winnings = winnings + 100; } else if (matches == 4 && powerballMatches == 1) { balance = balance + 50000; winnings = winnings + 50000; } else if (matches == 5 && powerballMatches == 0) { balance = balance + 1000000; winnings = winnings + 1000000; } else if (matches == 5 && powerballMatches == 1) { balance = balance + 10000000; winnings = winnings + 10000000; } //System.out.println("There is currently " + matches + " number matches."); //System.out.println("There is currently " + powerballMatches + " powerball number matches.\n"); } else { System.out.println("YOU ARE BROKE!"); } } /*** Accessor/Observor Methods ***/ public void displayBalance() { System.out.print("Your balance is at: $"); System.out.printf("%.2f", balance); } public void displayWinnings() { System.out.print("\nYou have currently won: $"); System.out.printf("%.2f", winnings); System.out.println("\n"); } public String toString() { StringBuilder builder = new StringBuilder(); StringBuilder builder2 = new StringBuilder(); if (numbers.length == lotteryNumbers.length) { for (int i = 0; i < numbers.length; i++) { if (i < numbers.length - 1) { builder.append(numbers[i] + ", "); builder2.append(lotteryNumbers[i] + ", "); } else { builder.append(numbers[i] + " + "); builder2.append(lotteryNumbers[i] + " + "); } } } else { return "ERROR: Numbers max set of numbers doesn't match Lottery Numbers max set of numbers!\n"; } return "Your set of numbers were: " + builder + Integer.toString(powerBall) + "\nThe powerball numbers were: " + builder2 + lotteryPowerBall; } } Launcher public class launchPowerBall { public static void main(String[] args) throws InterruptedException { // Build the GUI object PowerBallGUI GUI = new PowerBallGUI(); GUI.buildGUI(); //GUI.setTextArea("banana"); // Build the PowerBall object PowerBall roll = new PowerBall(); while(true) { if (GUI.getJButton().getModel().isPressed()) { System.out.println("TEST"); } } //System.out.println("TOO LATE!"); //while (true) { /*roll.randomize(); System.out.println(roll.toString()); roll.calculate(); roll.displayBalance(); roll.displayWinnings(); Thread.sleep(500); */ //} } } GUI import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.SwingConstants; public class PowerBallGUI { private JButton start = new JButton("Launch the Powerball!"); private boolean buttonPressed = false; private String outText; /*** Constructor Methods ***/ public PowerBallGUI() { #SuppressWarnings("unused") JTextArea outputText = new JTextArea("Press the 'Launch the Powerball' button to start!"); } /*** Setters ***/ /*** Sets the JTextArea object ***/ public void setTextArea (String str) { this.outText = str; } public void setButtonPressed (Boolean bool) { this.buttonPressed = bool; } /*** Getters ***/ public Boolean getButtonPressed() { return this.buttonPressed; } public JButton getJButton() { return this.start; } /*** Builds the GUI ***/ public void buildGUI() { // Create the Java Frame itself JFrame frame = new JFrame("Can YOU win the Powerball? v1.0 (Programmed by: Josh Yang)"); // Sets the default close operation of the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sets the size of the frame frame.setSize(800, 500); // Sets the location of the frame centerGUI(frame); // Allows the frame to be seen frame.setVisible(true); // Disables frame resizing //frame.setResizable(false); // Create the Java Panel itself JPanel panel = new JPanel(); JPanel contentPanel = new JPanel(); JPanel launchPanel = new JPanel(); // Sets the sides of the Java panels panel.setSize(800, 150); // Set the panel background color panel.setBackground(Color.YELLOW); contentPanel.setBackground(Color.YELLOW); launchPanel.setBackground(Color.PINK); // Add the panel onto the frame frame.add(panel, "North"); frame.add(contentPanel, BorderLayout.CENTER); frame.add(launchPanel, BorderLayout.SOUTH); // Set top panel's preferred size dimensions panel.setPreferredSize(new Dimension(800, 100)); // Adds components onto the panel JLabel title = new JLabel("Can YOU win the lottery? v1.0", SwingConstants.CENTER); title.setFont(new Font("Serif", Font.BOLD, 25)); panel.add(title); String text = "Basically, we start you off at $1000 and buy tickets in increments of $2 until you win big (if you do, that is)!"; JLabel description = new JLabel(); description.setText(text); description.setFont(new Font("Serif", Font.PLAIN, 16)); panel.add(description); // ContentPanel area JLabel cDescription = new JLabel("Output: "); contentPanel.add(cDescription); JTextArea outputText = new JTextArea(17, 60); outputText.setBackground(Color.PINK); outputText.setEditable(false); outputText.setText("Press the 'Launch the Powerball' button to start!"); contentPanel.add(outputText); start.setLocation(100, 100); launchPanel.add(start); // Add an action listener to the JButton start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // If the button is pressed, delete text field and replace with new content setButtonPressed(true); outputText.setText(""); outputText.setText(outText); } }); frame.revalidate(); //frame.pack(); } /*** Centers the GUI based on screen size ***/ public static void centerGUI(Window frame) { // Gets the size of the screen Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2); int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2); // Set the frame location based on x and y frame.setLocation(x, y); } }
The simple solution is to take the functionality you're "trying" to execute in the main method and put in the ActionListener... start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // If the button is pressed, delete text field and replace with new content PowerBall roll = new PowerBall(); roll.randomize(); System.out.println(roll.toString()); roll.calculate(); roll.displayBalance(); roll.displayWinnings(); setButtonPressed(true); outputText.setText(""); outputText.setText(outText); } }); If you "really" want to do more work in the main, you will need to generate some kind of observer pattern which can notified when something occurs. You could put one on Powerball so it could notify you of a status change or on the GUI which notify you that the start button was pressed
How to have a proper JTextField IP address in Java?
First of all, I couldn't find any of my question on google. This is the following code that I used. ipAddress = new MaskFormatter("###.###.###.###"); JTextField txtAddress = new JFormattedTextField(ipAddress); But the code above gives user to (must) input exactly 12 characters. How to make the JTextField can be written as "12.10.25.25" ?
I would do it differently: Simply wait for the user to somehow confirm that he has finished entering the address (for example by observing when the field looses focus) and retrieve the value of the field and use one of the many regular expressions that check all properties of valid ip addresses. Looking at the Oracle tutorial here it seems to me that using a JTextFormattedTextField simply is the wrong answer. That class and the corresponding formats are for either locale-based formatting of dates or numbers. I think you should be rather looking into input validation; see here for details; and as said; your validation could be based on the things you find here. Finally: the point is to come up with a consistent user experience. Dont put yourself into a corner by saying: I saw this approach; so I absolutely must use that type of component. Instead, check out the possible options, and go for that one that (given your "budget" of development resources) gives the user the best experience. Example: instead of using 1 JFormattedTextField, you could go for 4 textfields, and even write code that would move the focus automatically forth and back. Many things are possible; it only depends on how much time you are willing to spend.
My homegrown IP address control based on a single JTextField import javax.swing.*; import javax.swing.text.DefaultEditorKit; import java.awt.*; import java.awt.event.*; import java.net.InetAddress; import java.net.UnknownHostException; public class JIp4AddressInput extends JTextField { private final char[] buff = " 0. 0. 0. 0".toCharArray(); private int bpos; private void putnum (int num, int offset) { int a = num/100; num -= a*100; int b = num/10; num -= b*10; buff[offset] = (char)('0'+a); buff[offset+1] = (char)('0'+b); buff[offset+2] = (char)('0'+num); } private void align (int base) { int end = base+3; StringBuffer sb = new StringBuffer(); for (int s=base; s<end; s++) { if (buff[s] != ' ') sb.append(buff[s]); } while (sb.length() > 1 && sb.charAt(0) == '0') sb.delete(0,1); while (sb.length() < 3) sb.insert(0, ' '); try { int num = Integer.parseInt(sb.toString().trim()); if (num > 255) sb = new StringBuffer("255"); if (num < 0) sb = new StringBuffer(" 0"); } catch (NumberFormatException e) { sb = new StringBuffer(" 0"); } for (int s=base; s<end; s++) { buff[s] = sb.charAt(s-base); } } private void alignAll() { align(0); align (4); align(8); align (12); } private void fwd () { bpos = bpos == 15 ? bpos : bpos +1; } private void back () { bpos = bpos == 0 ? bpos : bpos -1; } private void backspace() { back(); if (bpos == 3 || bpos == 7 || bpos == 11) { return; } if (bpos < 15) buff[bpos] = ' '; } private void setChar (char c) { if (bpos == 3 || bpos == 7 || bpos == 11) { fwd(); } if (bpos < 15) buff[bpos] = c; fwd(); } public JIp4AddressInput() { super(); setPreferredSize(new Dimension(110, 30)); setEditable(false); Action beep = getActionMap().get(DefaultEditorKit.deletePrevCharAction); beep.setEnabled (false); setText (new String (buff)); addFocusListener(new FocusListener() { #Override public void focusGained(FocusEvent e) { setText (new String (buff)); setCaretPosition(0); getCaret().setVisible(true); } #Override public void focusLost(FocusEvent e) { alignAll(); setText(new String(buff)); } }); addKeyListener(new KeyAdapter() { #Override public void keyTyped (KeyEvent e) { bpos = getCaretPosition(); char c = e.getKeyChar(); if ((c>= '0' && c<= '9') || c == ' ') { setChar (c); } else if (c == KeyEvent.VK_BACK_SPACE) { backspace(); } else if (c == KeyEvent.VK_ENTER) { alignAll(); } setText(new String(buff)); setCaretPosition(bpos); } }); } //////////////////////////////////////////////////////////////////////////////////////// public InetAddress getAddress() { String[] parts = new String(buff).split("\\."); byte[] adr = new byte[4]; for (int s=0; s<4; s++) adr[s] = (byte)Integer.parseInt(parts[s].trim()); try { return InetAddress.getByAddress(adr); } catch (UnknownHostException e) { return null; } } public void putAddress (InetAddress in) { byte[] adr = in.getAddress(); putnum(adr[0]&0xff, 0); putnum(adr[1]&0xff, 4); putnum(adr[2]&0xff, 8); putnum(adr[3]&0xff, 12); alignAll(); setText (new String(buff)); } }
*new title: JButton array scope (it was:change color of button with button name)
How can is alter the color of the correct button? It is for a small application, this app has 5 buttons from a array.(the name's are a,b,c,d,e) The appearence of the buttons have to alter (change color) when i type in a number in a Jtextfield. I added a name to each button: knop = new JButton(Titel[i]); knop.setName(tel[i]); Here i get the text: public void actionPerformed(ActionEvent e) { String invoer = antwoord.getText(); try { int welke = Integer.parseInt(invoer); if (welke-1 >0 && welke-1<5) { vraag.setText("Goeie keus!"); if (welke == 1){ knop.setBackground(Color.BLUE); } knop.setBackground(Color.red); } But now it only changes the last button to red which is created bij the array. So the question can I select a button by its name? So if (input = 1) alter button 1 to green. in stead of only button 5. I have tried de solution of gile, but i can't get it to work: I get every time a: "AWT-EventQueue-0" java.lang.NullPointerException" package kiesknop; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; //public class Paneel extends JApplet public class Paneel extends JFrame { private JPanel paneel; private JButton knop; public JTextField antwoord; private JLabel vraag; public JButton[] knops; public Paneel() { int [][] numButtons = new int [5][4]; numButtons[0][0] = 50; numButtons[0][1] = 10; numButtons[0][2] = 10; numButtons[0][3] = 10; numButtons[1][0] = 100; numButtons[1][1] = 10; numButtons[1][2] = 30; numButtons[1][3] = 30; numButtons[2][0] = 200; numButtons[2][1] = 10; numButtons[2][2] = 50; numButtons[2][3] = 50; numButtons[3][0] = 300; numButtons[3][1] = 10; numButtons[3][2] = 100; numButtons[3][3] = 100; numButtons[4][0] = 500; numButtons[4][1] = 10; numButtons[4][2] = 200; numButtons[4][3] = 200; String [] Titel = new String [5]; Titel [0] = "*"; Titel [1] = "**"; Titel [2] = "***"; Titel [3] = "****"; Titel [4] = "*****"; String [] tel = new String [5]; tel [0] = "a"; tel [1] = "b"; tel [2] = "c"; tel [3] = "d"; tel [4] = "e"; paneel = new JPanel(); JButton[] knops = new JButton[5]; for (int i = 0; i < 5; i++) { knops[i] = new JButton(Titel[i]); knops[i].setName (tel[i]); knops[i].setBounds(numButtons[i][0],numButtons[i][1], numButtons[i][2], numButtons[i][3]); knops[i].addActionListener(new KnopHandler()); } for (int i = 0; i < 5; i++) { paneel.add(knops[i]); } vraag = new JLabel("Welke knop grootte vind je het mooist?"); vraag.setBounds(100, 400, 250, 20); antwoord = new JTextField(20); antwoord.setBounds(500, 400, 100, 20); antwoord.setEditable(true); antwoord.addActionListener(new AntwoordHandler()); paneel.add (vraag); paneel.add (antwoord); setContentPane (paneel); } public class KnopHandler implements ActionListener { public void actionPerformed(ActionEvent e) { JButton o = (JButton)e.getSource(); String Text = o.getText(); String name = o.getName(); String Label =o.getLabel(); System.out.println("knop gedrukt"); System.out.println(Text); System.out.println(name); System.out.println(Label); } } class AntwoordHandler implements ActionListener { public void actionPerformed(ActionEvent e) { String invoer = antwoord.getText(); try { int welke = Integer.parseInt(invoer); if (welke >0 && welke<5) { vraag.setText("Goeie keus!"); if(welke == 1)// knops[welke].setBackground(Color.BLUE); System.out.println(knops[1]); if(welke == 2) knops[welke].setBackground(Color.BLUE); if(welke == 3) knops[welke].setBackground(Color.BLUE); if(welke == 4) knops[welke].setBackground(Color.BLUE); if(welke == 5) knops[welke].setBackground(Color.BLUE); } else vraag.setText("Geen geldige invoer!"); } catch( NumberFormatException nfe) { if( invoer.equals("")) vraag.setText("Niets ingevuld!"); else vraag.setText("Alleen nummers invoeren!"); } } } public static void main (String arg[]) { JFrame frame = new Paneel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(null); frame.setVisible(true); frame.setSize(900, 500); } } What am i doing wrong ?
You can put buttons in an array JButton[] knops = new JButton[5]; ... knops[i] = new JButton(Titel[i]); ... And then set the background after user entered a number: if (welke == 1){ knops[welke].setBackground(Color.GREEN); }
Your title doesn't match with the given example: you are asking to get a button reference with string name but you are trying to parse the name to an integer. However, if i understood your requirement correctly: I can think of two option: Traverse each button of the button's array you have and compare with their name with your target name: you can get the name of the component(JButton) invoking button.getName(). Instead of using array which require traverse each time to get the target button with matching name, Create a HashMap<key, value>: HashMap<String, JButton>, map the button to their name and use it to get the component on Action Event. HashMap<String, JButton>buttomMap = new HashMap<>(); buttonMap.put("kicker", kickerButton); // kickButton is a button //// Then in actionPerformed() function JButton button = buttonMap.get("kicker"); button.setBackground(Color.BLUE);
Implementing ActionListener in the Following Code Inside
I'm having some trouble with my age calculating program on Java. It works fine when I preset the birth year, birth month and birth date values but when I try to have the user input their own birthdate into the text field and then try to work with those values, I just reach a dead-end. I tried asking on Yahoo Answers and the hint I got was "The return value of getActionCommand() is a string while the result is a JLabel. Can you compare them?" I'm not exactly sure what to do with that hint. Here's what I have and the way I attempted to implement the whole "user input" idea. I'm pretty sure my coding is messy and inefficient, so bear with that please. I'd appreciate any help! //Date: April 11, 2012 //Description: Calculates the age in terms of days depending on your birthdate. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AgeCalculator extends Frame implements ActionListener { JButton equal; JTextField year, month, day; JLabel result, first, second, third; JFrame frame; JPanel panel; static int totaldaysalive; static int daysaliveyr; static int daysalivem; static int birthyr; static int birthm; static int birthd; static int currentyr = 2012; public AgeCalculator(){ gui(); } public void gui(){ frame = new JFrame ("Age Calculator"); panel = new JPanel(new GridBagLayout()); panel.setBackground(Color.LIGHT_GRAY); GridBagConstraints x = new GridBagConstraints(); equal = new JButton ("Get Result"); x.insets = new Insets(3,0,3,0); first = new JLabel("Year "); x.gridx = 0; x.gridx = 0; panel.add(first, x); year = new JTextField(10); x.gridx = 5; x.gridy = 0; x.gridwidth = 3; panel.add(year, x); second = new JLabel ("Month "); x.gridx = 0; x.gridy = 1; panel.add(second,x); month = new JTextField(10); x.gridx = 5; x.gridy = 1; x.gridwidth = 3; panel.add(month,x); third = new JLabel ("Day "); x.gridx = 0; x.gridy = 2; panel.add(third,x); day = new JTextField(10); x.gridx = 5; x.gridy = 2; x.gridwidth = 3; panel.add(day,x); x.gridx = 6; x.gridy = 3; panel.add(equal,x); result = new JLabel (""); x.gridx = 5; x.gridy = 5; panel.add(result,x); frame.add(panel); frame.setVisible(true); frame.setSize(350, 350); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Calc e = new Calc(); equal.addActionListener(e); year.addActionListener(e); month.addActionListener(e); day.addActionListener(e); } class Calc implements ActionListener { public void actionPerformed(ActionEvent e) { try { birthyr = Integer.parseInt(year.getText()); } catch (NumberFormatException a) { result.setText("Illegal data for first field."); result.setForeground(Color.red); return; } try { birthm = Integer.parseInt(month.getText()); } catch (NumberFormatException a) { result.setText("Illegal data for second field."); result.setForeground(Color.red); return; } try { birthd = Integer.parseInt(day.getText()); } catch (NumberFormatException a) { result.setText("Illegal data for third field."); result.setForeground(Color.red); return; } if (e.getActionCommand().equals (equal)){ totaldaysalive = ageCalcYr() + ageCalcM() + birthd; result.setText(Integer.toString(totaldaysalive)); } } public int ageCalcYr(){ for (int i = birthyr; i <= currentyr; i++){ if ((i % 4 == 0) && (!(i % 100 == 0) || (i % 400 == 0))){ daysaliveyr = daysaliveyr + 366; } else { daysaliveyr = daysaliveyr + 365; } } return daysaliveyr; } public int ageCalcM(){ if (birthm == 1){ daysalivem = daysalivem + 0; } else if (birthm == 2){ daysalivem = daysalivem + 30; } else if (birthm == 3){ daysalivem = daysalivem + 60; } else if (birthm == 4){ daysalivem = daysalivem + 90; } else if (birthm == 5){ daysalivem = daysalivem + 120; } else if (birthm == 6){ daysalivem = daysalivem + 150; } else if (birthm == 7){ daysalivem = daysalivem + 180; } else if (birthm == 8){ daysalivem = daysalivem + 210; } else if (birthm == 9){ daysalivem = daysalivem + 240; } else if (birthm == 10){ daysalivem = daysalivem + 270; } else if (birthm == 11){ daysalivem = daysalivem + 300; } else if (birthm == 12){ daysalivem = daysalivem + 330; } return daysalivem; } } public static void main(String[] args) { // TODO Auto-generated method stub AgeCalculator gui = new AgeCalculator(); } #Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub } }
Fast healing: if (e.getActionCommand ().equals ("Get Result")) { // equal)) { totaldaysalive = ageCalcYr () + ageCalcM () + birthd; result.setText (Integer.toString (totaldaysalive)); } If you have some time, I can post you 20 improvements. You extend Frame, impl. ActionListener, but meanwhile AgeCalculator has a JFrame (which is better in a SwingContext than Frame, which is AWT) and has a seperate Actionlistener which is used. Remove the declaration, and the the overriding method in the end. public class AgeCalculator // extends Frame implements ActionListener There follows a block of visual components and other attributes, the later ones are static - which prohibits using of 2 AgeCalculators on the same JVM. That's surely not a restriction by intent. Don't make something static to shut up the compiler. Make everything private, if you aren't sure you want to expose it. Avoid Attributes where possible. When will you ever retouch a Label? JButton equal; JTextField year, month, day; JLabel result, ... ... static int birthd; static int currentyr = 2012; Use simplified addition where appropriate: daysaliveyr += 366; To calc the days for month, pass the birthyr and the birthm as parameter: int totaldaysalive = ageCalcYr (birthyr) + ageCalcM (birthm) + birthd; result.setText (Integer.toString (totaldaysalive)); The livetime of the variable totaldaysalive can be reduced to 2 lines - a very small scope to search for an error, if there is any. public int ageCalcM (int birthm) { int daysalivem = 0; if (birthm == 2) { daysalivem += 30; } else if (birthm == 3) { daysalivem += 60; } In the current state, ageCalcM is a provisorium. Else you could just say daysalivem = (birthm - 1) * 30; Shorter code: public int ageCalcM (int birthm) { if (birthm == 2) { return 30; } else if (birthm == 3) { return 60; } However, such mass manipulation in stupid repetition can be solved with an simple array: public int ageCalcM (int birthm) { int[] mdays = {0, 30, 60, 90, ...}; return mdays [birthm]; } In the main-Method you create an instance 'gui', which is never used. This is all you need: public static void main (String [] args) { new AgeCalculator (); } Gui, btw. is a bad name, if you already have a method of said name. Since that method is never used, just move the whole thing into the ctor. year/month/date don't need the ActionListener. Other layouts are much better suited. We need another calender reform to make your program work. Input should not only be checked to be int, but valid month etc. The actual date isn't used. What is left? import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AgeCalculator { JTextField year, month, day; JLabel result; public AgeCalculator () { JFrame frame = new JFrame ("Age Calculator"); JPanel panel = new JPanel (new GridBagLayout ()); panel.setBackground (Color.LIGHT_GRAY); GridBagConstraints x = new GridBagConstraints (); JButton equal = new JButton ("Get Result"); x.insets = new Insets (3, 0, 3, 0); JLabel first = new JLabel ("Year "); // two times gridx = 0 here? x.gridx = 0; x.gridx = 0; panel.add (first, x); year = new JTextField (10); x.gridx = 5; x.gridy = 0; x.gridwidth = 3; panel.add (year, x); JLabel second = new JLabel ("Month "); x.gridx = 0; x.gridy = 1; panel.add (second, x); month = new JTextField (10); x.gridx = 5; x.gridy = 1; x.gridwidth = 3; panel.add (month, x); JLabel third = new JLabel ("Day "); x.gridx = 0; x.gridy = 2; panel.add (third, x); day = new JTextField (10); x.gridx = 5; x.gridy = 2; x.gridwidth = 3; panel.add (day, x); x.gridx = 6; x.gridy = 3; panel.add (equal, x); result = new JLabel (""); x.gridx = 5; x.gridy = 5; panel.add (result, x); frame.add (panel); frame.setVisible (true); frame.setSize (350, 350); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); Calc e = new Calc (); equal.addActionListener (e); } class Calc implements ActionListener { public void actionPerformed (ActionEvent e) { int birthyr; int birthm; int birthd; try { birthyr = Integer.parseInt (year.getText ()); } catch (NumberFormatException a) { result.setText ("Illegal data for first field."); result.setForeground (Color.red); return; } try { birthm = Integer.parseInt (month.getText ()); } catch (NumberFormatException a) { result.setText ("Illegal data for second field."); result.setForeground (Color.red); return; } try { birthd = Integer.parseInt (day.getText ()); } catch (NumberFormatException a) { result.setText ("Illegal data for third field."); result.setForeground (Color.red); return; } if (e.getActionCommand ().equals ("Get Result")) { // equal)) { int totaldaysalive = ageCalcYr (birthyr) + ageCalcM (birthm) + birthd; result.setText (Integer.toString (totaldaysalive)); } } public int ageCalcYr (int birthyr) { int currentyr = 2012; int daysaliveyr = 0; for (int i = birthyr; i <= currentyr; i++) { if ((i % 4 == 0) && (! (i % 100 == 0) || (i % 400 == 0))) { daysaliveyr += 366; } else { daysaliveyr += 365; } } return daysaliveyr; } public int ageCalcM (int birthm) { int[] mdays = {0, 30, 60, 90, 120}; return mdays [birthm]; } } public static void main (String [] args) { new AgeCalculator (); } }
Since you're using a button to kick off the calculation, only register an action listener on that button. Inside the action performed method read, parse and calculate the age in days.
I think you want to do equal.addMouseListener(e). Of course you'll have to change Calc to implement MouseListener. You'll probably only have to actually write the mouseClicked(MouseEvent) method. All of the others are for more specific things than what you're after. That will respond to a click event on your button. I don't think you want any other listeners. If so, they should be KeyListeners or something other than ActionListeners. On a side note, It's hard for me to see because your indentation is off, but I can't really tell why your int fields are static. I think that's probably unnecessary.