I try to build a basic calculator. I want that textField to work as a calculator (press for example 154 and display to be 154) when I click button numbers. Unfortunalty I don't get the proper result. When I click 9 for example I get 0123456789. I don't know how to pass the button int into and array and then to retrieve as a string.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
public class Buttons {
public static List<JButton> generateButtons(JFrame frame) {
List<JButton> buttons = new ArrayList<>();
int x = 20;
int y = 500;
for (int i = 0; i < 10; i++) {
String str = Integer.toString(i);
buttons.add(new JButton(str));
buttons.get(i).setBounds(x, y, 50, 50);
x += 60;
frame.add(buttons.get(i));
if (x >= 380) {
x = 20;
y = 430;
}
}
return buttons;
}
public static String displayOnTextField(List<JButton> list,JTextField field){
int number = 0;
String str = "";
for (int i = 0; i <list.size(); i++){
String returned = Integer.toString(i);
str += returned;
String finalStr = str;
list.get(i).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
field.setText(finalStr);
}
});
}
return str;
}
}
And main:
import javax.swing.*;
import java.util.List;
public class main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JTextField textField = new JTextField();
List<JButton> list = Buttons.generateButtons(frame);
String displayOnTextField = Buttons.displayOnTextField(list,textField);
frame.setSize(400,600);
textField.setBounds(150,40,150,30);
frame.add(textField);
frame.setLayout(null);
frame.setVisible(true);
}
}
Thank you.
The string you are appending is finalStr, which you build in a loop.
String returned = Integer.toString(i);
str += returned;
String finalStr = str;
If you don't want it to append the preceding characters, don't use +=. You could simply use:
String finalStr = Integer.toString(i);
As you are appending string in a loop which you are getting from a button stored in list as below
String returned = Integer.toString(i);
str += returned;
String finalStr = str;
so for button 0 final string will be 0 for button 1 final string will be 01 and so on
instead you can do as follows:
Change your finalStr strings assignment to
String finalStr = Integer.toString(i);
and in actionPerformed method set text as follows
field.setText(field.getText() + finalStr);
It will work for you...
Related
Please Help. When I run this GUI the numbers run off the frame. I know I have to use JTextArea and append but where do I put that in my code. can someone explain to me in simple terms and show me? I want to make it scroll vertically and horizontally and when I do add the JTextArea I get this error: error: cannot find symbol panel.setMessage(message);
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class prime extends JFrame
{
public static void main(String[] args)
{
prime frame = new prime();
}
private JTextArea panel;
private JPanel inPanel;
private JTextField inField;
public prime()
{
final int width = 500;
final int height = 500;
setSize(width, height);
setTitle("Find Prime Numbers");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JTextArea(20, 10);
add(new JScrollPane(panel), "Center");
inPanel = new JPanel();
inPanel.add(new JLabel("Enter Your Number", SwingConstants.RIGHT));
inField = new JTextField(20);
ActionListener inListener = new TextListener();
inField.addActionListener(inListener);
inPanel.add(inField);
add(inPanel, "South");
setVisible(true);
}
private class TextListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String message = inField.getText();
inField.setText("");
panel.setMessage(message);
}
}
class TextPanel extends JPanel
{
private String message;
private Color backGroundColor;
public TextPanel()
{
message = "";
backGroundColor = Color.white;
}
public TextPanel(String x, Color background)
{
message = x;
backGroundColor = background;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int width = getWidth();
int height = getHeight();
setBackground(backGroundColor);
g2.setColor(Color.black);
Font x = new Font("TimesNewRoman", Font.BOLD,20);
g2.setFont(x);
FontMetrics fm = g2.getFontMetrics(x);
g2.drawString(message,50, 50);
if(!(message.equals("")))
g2.drawString(previousPrime(message),50,78);
}
public void setMessage(String message) {
if (isPrime(Integer.parseInt(message))){
this.message = message + " is a prime number.";
}
else
this.message = message + " is not a prime number.";
repaint();
}
public boolean isPrime(int num){
for(int i = 2; i < num; i++){
if (num % i == 0)
return false;
}
if(num < 2)
return false;
return true;
}
public String previousPrime(String message){
String totalPrimeNum = "";
int finalNum = Integer.parseInt(message.substring(0,message.indexOf(" ")));
int count = 0;
for(int i = 2; i < finalNum; i++){
if(isPrime(i)) {
totalPrimeNum += " " + i;
count++;
}
if(count == 10) {
totalPrimeNum += "\n";
count = 0;
}
}
if (isPrime(Integer.parseInt(message.substring(0,message.indexOf(" ")))))
totalPrimeNum += " " + finalNum;
System.out.println(totalPrimeNum);
return totalPrimeNum;
}}}
Look at what you have and what you want to achieve. You have a method which can verify if a value is a prime or not, but it does not produce any output. You have a JTextArea which allows you to add content to it.
You have a square peg and a round hole. One of these things needs to change. You have control over the setMessage method, but you don't have control over the JTextArea, this would suggest that the setMessage needs to change. While you could pass the JTextArea to the setMessage method, a better solution would be to change the setMessage to return some kind of meaningful value or simply get rid of it in favor of using the isPrime method instead
Take your TestPane and move the functionality used to calculate and test for a prime number to a new class, for example...
public class PrimeCalculator {
public boolean isPrime(int num) {
for (int i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
if (num < 2) {
return false;
}
return true;
}
public String previousPrime(String message) {
StringBuilder totalPrimeNum = new StringBuilder(128);
int finalNum = Integer.parseInt(message.substring(0, message.indexOf(" ")));
int count = 0;
for (int i = 2; i < finalNum; i++) {
if (isPrime(i)) {
totalPrimeNum.append(" ").append(i);
count++;
}
if (count == 10) {
totalPrimeNum.append("\n");
count = 0;
}
}
if (isPrime(Integer.parseInt(message.substring(0, message.indexOf(" "))))) {
totalPrimeNum.append(" ").append(finalNum);
}
System.out.println(totalPrimeNum);
return totalPrimeNum.toString();
}
}
This now makes no assumptions over what you want to do and simply produces output. You can now use these methods and make decisions about how to use the output, for example...
private class TextListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
PrimeCalculator calc = new PrimeCalculator();
String message = inField.getText();
inField.setText("");
String text = message + " is not a prime number\n";
try {
if (calc.isPrime(Integer.parseInt(message))) {
text = message + " is a prime number\n";
}
} catch (NumberFormatException exp) {
text = message + " is not a valid integer\n";
}
panel.append(message);
panel.setCaretPosition(panel.getDocument().getLength());
}
}
Sometimes, you need to rethink your design to support what it is you want to achieve.
The process of verifying and calculating the prime numbers should do just that, they should not do anything else (like update the screen), this way you can decouple the code and re-use it in different ways which you didn't original think of (like outputting to a file or the web)
See How to Use Text Areas and How to Use Scroll Panes for more details
i am writing a program in applet to measure the frequencies of word lengths in a given amount of text and display these frequencies during applet. i have written the program and it debugs without error.
however the output says i have 255 words of every length in the text i input, i have been staring at this for hours with no luck, i am aware that the drawstring method lists these outputs horizontally which i will be fixing at a later time.
i am assuming the problem resides in the analyseText method.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.util.*;
public class StringAnalysis extends Applet implements MouseListener, ActionListener {
Font arielBold;
Label pr_Label;
TextField pr_txt;
int textFieldSize = 15;
Button pr_input1, pr_input2, pr_input3;
String textToAnalyse = ("Nothing has been entered.");
boolean output = false;
String testing ="";
//create array to show respective lengths of words
int [] lengthsOfWords = new int[textFieldSize];
//first we must separate strings from spaces and populate array for comparison
String [] arrayOfWords = new String[textFieldSize];
public void init() {
pr_Label = new Label("Enter the text you wish to analise: ");
add(pr_Label);
pr_txt = new TextField(textFieldSize);
add(pr_txt);
pr_input1 = new Button("Analyse");
pr_input2 = new Button("Reset");
add(pr_input1);
add(pr_input2);
pr_input1.addActionListener(this);
pr_input2.addActionListener(this);
}
public void start (){
setSize(1000, 500);
arielBold = new Font ("Ariel", Font.BOLD, 20);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == pr_input2) {
showStatus("Resseting....");
reset();
}
else if (e.getSource() == pr_input1){
showStatus("Analysing...a");
textToAnalyse = pr_txt.getText();
analyseText(textToAnalyse);
}
}
public void paint(Graphics g) {
String statsToOutput = ("There are:" + "\n" );
int counter = 1;
for (int lengths: lengthsOfWords) {
statsToOutput = statsToOutput +lengthsOfWords[0] + " words of length " + counter + "\n ";
counter ++;
}
if (output = true){
g.drawString(statsToOutput, 25, 200);
g.drawString("The text to be analysed is: " + textToAnalyse, 25, 100);
showStatus("Finished.");
}
else if (output = false){
g.setFont(arielBold);
g.drawString(textToAnalyse,50, 100);
showStatus("Finished.");
}
}
public void analyseText(String text){
///////////////////////////////////////////////////////////////////////////////////////////////////////
int position1 = 0, position2 = 0;
String newWord = "";
String currentLetter;
int pos1 = 0, pos2 = 0;
for ( pos1 = 0; pos1 <= arrayOfWords.length-1; pos1++) {
//Initializes a string object for each address in array
for (position1 = 0; position1 <= text.length()-1; position1++){
//steps through each character in text
currentLetter = Character.toString(text.charAt(position1));
if (currentLetter.matches("[A-Z][a-z][0-9]")) {
//checks if character is alphanumeric using regular expressions (regex)
newWord = newWord + currentLetter;
//if passes regex then ads character to word
}
}
if (newWord.length() > 0) {
pos1 = arrayOfWords.length;
}
arrayOfWords[pos1] = newWord;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
emptyArrayInt(lengthsOfWords);
//now compare each word with rest of array\
for ( pos2 = 0; pos2 <= arrayOfWords.length-1; pos2++) {
position2 = 0;
for (position2 = 0; position2 <= arrayOfWords.length-1; position2++){
if (arrayOfWords[pos2].length() == arrayOfWords[position2].length());
lengthsOfWords[arrayOfWords[pos2].length()] = lengthsOfWords[arrayOfWords[pos2].length()] + 1;
}
}
showStatus("finished analysing.");
output = true;
repaint();
}
public void emptyArrayInt(int[] array) {
int position = 0;
for (position = 0; position <= array.length-1; position ++)
array[position] = 0;
}
public void emptyArrayStr(String[] array) {
int position = 0;
for (position = 0; position <= array.length-1; position ++)
array[position] = "";
}
public void reset() {
pr_txt.setText("");
textToAnalyse = ("Nothing has been entered.");
emptyArrayInt(lengthsOfWords);
emptyArrayStr(arrayOfWords);
//repaint();
showStatus("Reset Successful.");
repaint();
}
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
i would appreciate any help on this please, (I'm desperate).
Let's try section of code :
private Map<String, int> freqWords = new HashMap<String, int>();
public void analyzeText(String text) {
// You can split with another type of delimiter
String regex = ....
String[] inputs = text.split(regex);
for (String s : inputs) {
if(freqWords.containtsKey(s)) {
int frequency = inputs.get(s);
frequency++;
inputs.put(s, frequency);
} else {
inputs.put(s, 1);
}
}
}
Hope that it can help you. The main point here is you should use data structure Map to store the frequency words.
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);
I'm trying to replace setCharAt with something that can be used with a JLabel... I've been on oracle doc's looking for a solution. i don't know if I'm looking for the wrong thing or it just doesn't exists.. if it doesn't exists how could i work around that? i understand my naming convention is off and will be changing them as soon as possible...
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.*;
public class HangmanPanel extends JPanel {
static Boolean FOUND;
private static final long serialVersionUID = -5793357804828609325L;
public static String answerKey() {
//get random array element
String array[] = new String[10];
array[0] = "hamlet";
array[1] = "mysts of avalon";
array[2] = "the iliad";
array[3] = "tales from edger allan poe";
array[4] = "the children of hurin";
array[5] = "the red b" +
"+adge of courage";
array[6] = "of mice and men";
array[7] = "utopia";
array[8] = "chariots of the gods";
array[9] = "a brief history of time";
ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
Collections.shuffle(list);
String s = list.get(0);
return s;
}
public StringBuilder dashReplace(String s) {
//replace non-white space char with dashes and creates StringBuilder Object
String tW = s.replaceAll("\\S", "-");
System.out.print(tW + "\n");
StringBuilder AnswerKey = new StringBuilder(tW);
return AnswerKey;
}
public static int findAndReplace(String s, JLabel answerKey, String sc,
char ch) {
//find position of user input and replace
int pos = -1;
FOUND = false;
while(true){
pos = s.indexOf(sc, pos+1);
if(pos < 0){
break;
}else{
FOUND = true;
//setCharAt dosen't work for JLable
answerKey.setCharAt(pos, ch);
}
}
JLabel AnswerKey2 = new JLabel(answerKey.toString());
return pos;
}
public HangmanPanel(final String s){
this.setLayout(null);
JLabel heading = new JLabel("Welcome to the Hangman App");
JButton Button = new JButton("Ok");
//get input
JLabel tfLable = new JLabel("Please Enter a Letter:");
final JLabel AnswerKey = new JLabel(dashReplace(answerKey()).toString());
final JTextField text = new JTextField(10);
heading.setSize(200, 50);
tfLable.setSize(150, 50);
text.setSize(50, 30);
Button.setSize(60, 20);
AnswerKey.setSize(200, 100);
heading.setLocation(300, 10);
tfLable.setLocation(50, 40);
text.setLocation(50, 80);
Button.setLocation(100, 85);
AnswerKey.setLocation(100,85);
this.add(heading);
this.add(tfLable);
this.add(text);
this.add(Button);
this.add(AnswerKey);
Button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// can't access text
String sc = text.getText();
char ch = sc.charAt(0);
findAndReplace(s, AnswerKey, sc, ch);
}
});
}
}
Why are you trying to use setCharAt(...) with a JLabel. A label is meant to display static text. The only way to change it is to replace the entire string.
I guess you could do something like:
StringBuilder text = label.getText();
text.setCharAt(...);
label.setText( text.toString() );
Another option would be to use a JTextField that looks like a JLabel:
JTextField label = new JTextField(...);
label.setEditable(false);
label.setBorder(null);
label.setOpaque(false);
Then when you need to change the text you could do:
label.select(...);
label.replaceSelection(...);
The only method available for setting text for JLabel components is setText. Also Strings are immutable. Therefore, you can use StringBuilder:
StringBuilder builder = new StringBuilder(answerKey.getText());
builder.setCharAt(pos, ch);
answerKey.setText(builder.toString());
I'm trying to create a program that will take data in from a random access file and sort it based on whichever checkbox the user selects. The data should be sorted by either the bank account number, customer name or balance (when a user clicks that checkbox the data in the text area becomes sorted based on that). Once the data is sorted, it is outputted into the JTextArea. I'm also trying to output the total amount of entries from the file in the text field below the check boxes.
Thanks!
import java.lang.reflect.Array;
import java.nio.file.*;
import java.text.DecimalFormat;
import java.util.Collections;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
import javax.swing.border.Border;
public class GUIBankAcctSorter extends JFrame implements ItemListener {
public static void main(String[] args) {
GUIBankAcctSorter myFrame = new GUIBankAcctSorter();
myFrame.setVisible(true);
Path file = Paths.get("C:\\Java\\Bank.txt");
final String ID_FORMAT = "0000";
final String NAME_FORMAT = " ";
final int NAME_LENGTH = NAME_FORMAT.length();
final String BALANCE_FORMAT = "00000.00";
String delimiter = ",";
String s = ID_FORMAT + delimiter + NAME_LENGTH + delimiter + BALANCE_FORMAT + System.getProperty("line.separator");
final String EMPTY_ACCT = "0000";
String[] array = new String[3];
double balance = 0;
output(s, array, delimiter, balance, EMPTY_ACCT, file);
}
private static final long serialVersionUID = 1L;
private static final int WIDTH = 450;
private static final int HEIGHT = 310;
private static final int X_ORIGIN = 200;
private static final int Y_ORIGIN = 200;
JLabel title = new JLabel("Bank Account Sorter");
JLabel sort = new JLabel("Sort By ");
JLabel total = new JLabel("Total # of Bank Accounts ");
private Container con = getContentPane();
private FlowLayout layout = new FlowLayout();
static JTextArea area = new JTextArea(10, 35);
static JTextField field = new JTextField(5);
JCheckBox cust = new JCheckBox(" Cust # ", false);
JCheckBox bal = new JCheckBox(" Balance ", false);
JCheckBox name = new JCheckBox(" Name ", false);
public static void output(String s, String[] array, String delimiter, double balance, String EMPTY_ACCT, Path file){
String temp = "";
try{
InputStream iStream = new BufferedInputStream(Files.newInputStream(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
while(s != null){
array = s.split(delimiter);
if(!array[0].equals(EMPTY_ACCT)){
balance = Double.parseDouble(array[2]);
area.append("Cust # " + array[0] + "\t" + " Name: " + array[1] + " Balance " + "\t$" + array[2] + "\n");
}
s = reader.readLine();
}
reader.close();
}catch(Exception e){
System.out.println("Message: " + e);
}
field.setText(temp);
}
public GUIBankAcctSorter(){
super("Bank Account Sorter");
Font headFont = new Font("Arial", Font.BOLD, 28);
con.setLayout(layout);
title.setFont(headFont);
con.add(title);
area.setEditable(false);
field.setEditable(false);
con.add(new JScrollPane(area));
cust.addItemListener(this);
bal.addItemListener(this);
name.addItemListener(this);
con.add(sort);
con.add(cust);
con.add(bal);
con.add(name);
con.add(total);
con.add(field);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
int select = e.getStateChange();
if(source == cust){
if(select == ItemEvent.SELECTED){
bal.setSelected(false);
name.setSelected(false);
}
}
if(source == bal){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
name.setSelected(false);
}
}
if(source == name){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
bal.setSelected(false);
}
}
}
}
Here you can see a good example using comparator to sort the object.
Let us suppose:
RowTest is a class that represent a single row of grid.
orderAMT is a class variable/Column/JTextField of Row.
Now the code below show how to sort the List of RowTest according to its attribute orderAMT.
List<RowTest> sortedList = getAllRowsThatNeedToBeSorted();
Comparator comparator = new OrderAMTComparator();
Collections.sort(sortedList, comparator);
public class OrderAMTComparator implements Comparator<RowTest> {
#Override
public int compare(RowTest o1, RowTest o2) {
//Here you can use If condition to check which checkbox is selected and sort the list
//repace getOrderAMT with other fields.
BigDecimal compareRes = o1.getOrderAMT().getBigdecimalValue().subtract(o2.getOrderAMT().getBigdecimalValue());
//You can just return compareRes.compareTo(new BigDecimal(0))
//But Here I want to show that you can check any condition and return -1,1,0 as your
//requirement
if (compareRes.compareTo(new BigDecimal(0)) == -1) {
return -1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 1) {
return 1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 0 ) {
return 0;
}
return compareRes.intValue();
}
}
I hope you have understand this. If not I will elaborate.
Thankyou.
Is there anyway to do it with checkboxes?
Certainly:
Declare an Account class that stores the account number, name & balance.
Add each new Account to a List structure such as ArrayList.
Create a Comparator relevant to each of the 2 fields.
At time of sort, use Collections.sort(list,comparator).
Refresh the text area with the content of the sorted list.
Other tips
Since those check boxes are mutually exclusive, they should really be a ButtonGroup of JRadioButton instances.
Change setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); & setLocationRelativeTo(null) to setLocationByPlatform(true). See this answer for a demo.
Change setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT); for pack() (& use layouts more effectively).