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());
Related
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...
I am trying to add the contents of two arrays to two TextFields. When you run the program the problem is the current TextFields that I try to display (lines 70 - 83) when the window is redrawn, they only show the last item in their array. Is there any way to add all the items in a stacked list (one ontop of another.)
This is my first class ClassNameSorting
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class ClassNameSorting extends JFrame {
JTextField studentNameInputFirst, studentNameInputLast, studentNamesEneteredLast, studentNamesEnteredFirst;
JButton nextName, sort, backToStart;
JLabel firstName, lastName, classList;
String disp = "";
ArrayList<String> studentNameFirst = new ArrayList<String>();
ArrayList<String> studentNameLast = new ArrayList<String>();
ArrayList<String> sortedStudentNameFirst = new ArrayList<String>();
ArrayList<String> savedUnsortedStudentNameLast = new ArrayList<String>();
Container container = getContentPane();
public ClassNameSorting() {
container.setLayout(new FlowLayout());
studentNameInputFirst = new JTextField(15);
studentNameInputLast = new JTextField(15);
nextName = new JButton("Save");
sort = new JButton("Sort");
firstName = new JLabel("First Name: ");
lastName = new JLabel("Last Name: ");
nextName.setPreferredSize(new Dimension(110, 20));
sort.setPreferredSize(new Dimension(110, 20));
container.add(firstName);
container.add(studentNameInputFirst);
container.add(lastName);
container.add(studentNameInputLast);
container.add(nextName);
container.add(sort);
nextName.addActionListener(new nextNameListener());
sort.addActionListener(new sortListener());
setSize(262, 120);
setVisible(true);
}
private class nextNameListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
studentNameFirst.add(studentNameInputFirst.getText());
studentNameLast.add(studentNameInputLast.getText());
studentNameInputLast.setText(null);
studentNameInputFirst.setText(null);
}
}
private class sortListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
savedUnsortedStudentNameLast = new ArrayList<String>(studentNameLast);
Collections.sort(studentNameLast);
int totalSizeOfArray = studentNameLast.size();
for(int i = 0; i < totalSizeOfArray; i++){
boolean containsYorN = false;
String tempElementForContains = studentNameLast.get(i);
String tempElementFromStudentNameLast = savedUnsortedStudentNameLast.get(i);
containsYorN = savedUnsortedStudentNameLast.contains(tempElementForContains);
if(containsYorN == true){
int tempIndexPos = savedUnsortedStudentNameLast.indexOf(tempElementForContains);
String tempIndexElement = studentNameFirst.get(tempIndexPos);
sortedStudentNameFirst.add(i, tempIndexElement);
}
}
studentNamesEneteredLast = new JTextField();
studentNamesEnteredFirst = new JTextField();
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEneteredLast.setText(studentNameLast.get(i));
}
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEnteredFirst.setText(sortedStudentNameFirst.get(i));
}
studentNamesEneteredLast.setEditable(false);
studentNamesEnteredFirst.setEditable(false);
container.add(studentNamesEneteredLast);
container.add(studentNamesEnteredFirst);
setSize(262, 500);
revalidate();
}
}
}
My second class is: (DrawMainWindow)
import javax.swing.JFrame;
public class DrawMainWindow {
public static void main(String[] args) {
ClassNameSorting drawGui = new ClassNameSorting();
drawGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawGui.setLocationRelativeTo(null);
}
}
The first array is studentNameLast. I am trying to add that to studentNamesEnteredLast text field. The second is sortedStudentNameFirst being added to studentNamesEnteredFirst.
Thanks for the help!
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEneteredLast.setText(studentNameLast.get(i));
}
The text in the JTextField will only reflect the last item of the List. If you wish to append the entire list, create a String from the List and set the text of the JTextField with that String (you might wish to have them separated by some character - below uses a comma)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < totalSizeOfArray; i++){
sb.append(studentNameLast.get(i)).append(",");//comma delim
}
studentNamesEneteredLast.setText(sb.toString());
Not entirely sure what you are after, but a JList or JTable might be more appropriate to display List information
Was able to switch to a GridLayout and then added each last name and then first name together.
Code:
container.setLayout(new GridLayout(totalSizeOfArray+3,2));
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEnteredLast = new JTextField();
studentNamesEnteredFirst = new JTextField();
studentNamesEnteredFirst.setEditable(false);
studentNamesEnteredLast.setEditable(false);
studentNamesEnteredLast.setText(studentNameLast.get(i));
studentNamesEnteredFirst.setText(sortedStudentNameFirst.get(i));
container.add(studentNamesEnteredLast);
container.add(studentNamesEnteredFirst);
}
Example:
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 have my GUI set up the way I want it now I'm trying to output a string called AnswerKey i have predefined in dashReplace() I tried to draw the string and use JLabel but i just can't seem to find the right method of doing such.
import java.awt.*;
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 {
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 badge 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 static 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 HangmanPanel(){
this.setLayout(null);
JLabel heading = new JLabel("Welcome to the Hangman App");
JButton Button = new JButton("Ok");
//Button.addActionListener((ActionListener) this);
JLabel tfLable = new JLabel("Please Enter a Letter:");
//trying to out put predefined string
JLabel AnswerKey = new JLabel(AnswerKey);
JTextField text = new JTextField(10);
//String input = text.getText();
heading.setSize(200, 50);
tfLable.setSize(150, 50);
text.setSize(50, 30);
Button.setSize(60, 20);
heading.setLocation(300, 10);
tfLable.setLocation(50, 40);
text.setLocation(50, 80);
Button.setLocation(100, 85);
this.add(heading);
this.add(tfLable);
this.add(text);
this.add(Button);
}
}
The method is called answerKey, not AnswerKey. In fact, this surely won't compile as you've currently written it - you're trying to assign a variable to something while using that variable as a constructor parameter. It should be:
JLabel AnswerKey = new JLabel(dashReplace(answerKey()).toString());
To make this work, however, you'll need to make the method non-static. Also, having a variable named AnswerKey and a method named answerKey is just crying out for confusion - I'd suggest a better name for the JLabel.
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).