Java; Update second ComboBox after selection in first ComboBox - java

I've been trying to get te grips of Java (just because:)). At the moment I'm stuck on a 'calculator'. My intention is to select a overall subject through a ComboBox after which a second ComboBox shows which units can be calculated for said subject.
My problem is that the second ComboBox does not update and I'm having a hard time finding my oversight. Is anyone able to show my where I'm going wrong?
note: The terms for unitstring are placeholders for the time being:).
public class UserInterface implements Runnable{
String unitstring = "Select a subject";
#Override
public void run() {
JFrame frame = new JFrame("Radiation Calculator 2.0");
frame.setPreferredSize(new Dimension(350, 250));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public void createComponents(Container container) {
GridLayout layout = new GridLayout(4, 2);
container.setLayout(layout);
JLabel subject = new JLabel("Select a subject");
String[] subjectStrings = {"Wavelenght", "Radioactive Decay", "Radiation Dose"};
JComboBox subjectsel = new JComboBox(subjectStrings);
subjectsel.addActionListener(this::actionPerformed);
JLabel unit = new JLabel("Select a unit");
String[] unitStrings = {unitstring};
JComboBox unitsel = new JComboBox(unitStrings);
JLabel input = new JLabel("Select a input");
JTextField userinput = new JTextField("");
JButton calculate = new JButton("Calculate");
JTextArea result = new JTextArea("");
container.add(subject);
container.add(subjectsel);
container.add(unit);
container.add(unitsel);
container.add(input);
container.add(userinput);
container.add(calculate);
container.add(result);
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
int print = cb.getSelectedIndex();
System.out.println(print);
unitArray(print);
}
public void unitArray(int x) {
if (x == 0) {
unitstring = "Lambda";
}
if (x == 1) {
unitstring = "Bequerel";
}
if (x == 2) {
unitstring = "Gray";
}
System.out.println(unitstring);
}
}

Related

how do i create a virtual keyboard that can be used to insert values in different jtextfields

So I am trying to create a virtual keyboard that can insert values in a Jtextfield of another Jframe. The problem is that the data is overlapping when editing other text fields. So, I tried renewing the object but it replaced the first Jtextfield value as well. what should i do with this, should i start from scratch or is there any other way? . Since, English is not my first language I am struggling to find the correct terminology to research the problem please enlighten me with your knowledge
import java.awt.*;
import javax.swing.*;
public class OnScreenKeyboard implements ActionListener {
JFrame keyboard;
static String keyboardKeys = "0123456789qwertyuiopasdfghjklzxcvbnm.< ";
JButton[] keys = new JButton[39];
GridLayout gl;
FlowLayout fl;
Dimension buttondimension;
JPanel panel1, panel2;
JToggleButton capslock;
private String message = "";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public OnScreenKeyboard() {
buttondimension = new Dimension(45, 40);
fl = new FlowLayout();
capslock = new JToggleButton("capslock");
panel1 = new JPanel(fl);
panel2 = new JPanel(fl);
char[] key = keyboardKeys.toCharArray();
for (int i = 0; i < 39; i++) {
keys[i] = new JButton(String.valueOf(key[i]));
keys[i].setFont(new Font("Arial", Font.PLAIN, 13));
if (i == 38) {
keys[i].setPreferredSize(new Dimension(100, 30));
} else {
keys[i].setPreferredSize(buttondimension);
}
keys[i].addActionListener(this);
}
keyboard = new JFrame("Keyboard");
keyboard.setSize(720, 220);
keyboard.setLocationRelativeTo(null);
keyboard.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
keyboard.setResizable(false);
Container content = keyboard.getContentPane();
content.setLayout(null);
panel1.setBounds(1, 1, 500, 210);
panel2.setBounds(510, 1, 200, 210);
for (int i = 0; i < 10; i++) {
panel2.add(keys[i]);
}
for (int i = 10; i < 39; i++) {
panel1.add(keys[i]);
}
panel1.add(capslock);
content.add(panel1);
content.add(panel2);
capslock.addActionListener(this);
keyboard.setVisible(true);
}
public static void main(String[] args) {
new OnScreenKeyboard();
}
public void reset(){
message = "";
}
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 36; i++) {
if (e.getSource() == keys[i]) {
setMessage(getMessage() + keys[i].getText());
break;
}
}
if (e.getSource() == capslock) {
if (capslock.isSelected()) {
for (int i = 10; i < 36; i++) {
keys[i].setFont(new Font("Arial", Font.PLAIN, 12));
keys[i].setText(keys[i].getText().toUpperCase());
}
} else if (!capslock.isSelected()) {
for (int i = 10; i < 36; i++) {
keys[i].setFont(new Font("Arial", Font.PLAIN, 13));
keys[i].setText(keys[i].getText().toLowerCase());
}
}
}
setMessage(getMessage());
//JOptionPane.showMessageDialog(null, getMessage());
}
}
this is the frame I am trying to put my values from the keyboard in
public class LoginScreen implements ActionListener, FocusListener {
JFrame frame;
Container content;
FlowLayout fl;
JTextField txtusername, txtpassword;
JLabel lblusername, lblpassword;
JPanel panel1, panel2;
JButton keyboard, signup, signin;
OnScreenKeyboard kyb;
Dimension text;
private void init() {
text =new Dimension(100, 30);
fl = new FlowLayout(FlowLayout.CENTER);
lblusername = new JLabel("enter username");
lblpassword = new JLabel("enter password");
txtusername = new JTextField();
txtpassword = new JPasswordField();
keyboard = new JButton("keyboard");
signup = new JButton("signup");
signin = new JButton("sign in");
panel1 = new JPanel(fl);
panel2 = new JPanel(fl);
keyboard = new JButton("keyboard");
txtusername.setPreferredSize(text);
txtpassword.setPreferredSize(text);
kyb = new OnScreenKeyboard();
}
public LoginScreen() {
init();
frame = new JFrame("BorderLayoutDemo");
frame.setTitle("Registration Form");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(3);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
content = frame.getContentPane();
content.setLayout(new GridLayout(2, 1));
panel1.add(lblusername);
panel1.add(txtusername);
panel1.add(lblpassword);
panel1.add(txtpassword);
panel2.add(signup);
panel2.add(signin);
panel2.add(keyboard);
content.add(panel1);
content.add(panel2);
keyboard.addActionListener(this);
txtusername.addFocusListener(this);
txtpassword.addFocusListener(this);
}
public static void main(String[] args) {
new LoginScreen();
}
#Override
public void actionPerformed(ActionEvent e) {
if (!kyb.keyboard.isVisible()) {
if (e.getSource() == keyboard) {
kyb = new OnScreenKeyboard();
}
}
}
#Override
public void focusGained(FocusEvent e) {
if(txtusername == e.getSource()){
txtusername.setText(kyb.getMessage());
}else if(txtpassword == e.getSource()){
kyb.reset();
txtpassword.setText(kyb.getMessage());
}
}
#Override
public void focusLost(FocusEvent e) {
}
The problem is that it's weird how/when the text is taken from the keyboard.
You use the LoginScreen both as actionListener on the keyboard and as focusListener on the 2 textfields.
The way you implemented it now is that you "type" something in on the keyboard and after that put the focus on 1 of the 2 fields. Only at the moment you click the text from the keyboard is fetched (kyb.getMessage()).
It's especially a problem on the password. If you click on the txtpassword field you first reset the kyb and then fetch the message (which you just reset so is empty).
What felt weird for me is that you don't have a way in the keyboard to notion that you are done typing. So the flow of only getting the message when the focus changes to one of the text fields is wrong.
What I would do is create a new kind of KeyboardListener. This listener is put on the txtusername OR txtpassword depending on who last took focus (so in the focusGained() you should change who is listening to the keyboard).
Then each time a key is "typed" you should notify the listener of the letter and then the txtusername/txtpassword (whichever is listening at that time) should add that letter to its text.
This means that the keyboard itself doesn't need to remember any text. It just figures out which key was pressed and then sends the corresponding letter to the listener.
You should be using a TextAction as your ActionListener. The TextAction has a method getFocusedComponent() which will return the last text component to have focus.
Then in the can add the character to the text field. So the basic code in the actionPerformed(...) method of the TextAction might be something like:
JTextComponent component = getFocusedComponent();
component.replaceSelection( the character to add );

Java swing: managing integers/doubles with Listeners and J*Fields

EDITED
I've probably just stared at the screen for WAYYY too long but I feel the need to submit this question prior to going to sleep incase my delirium remains true...
The problem I'm having is I'm trying to get an int/double from the JTextField textField and convert it to a(n) int/double to use later in a listener, after retrieving it from a listener... ListenForText implements KeyListener, specifically KeyTyped, to obtain, through toString(), and store it in a String txtFldAmnt. After which I will store the result of Integer.parseInt(txtFldAmnt) into fldAmnt (fldAmnt = Integer.pareseInt(txtFldAmnt)) LINE 99 if copied to an editor. Once it's converted into an int I want to be able to manipulate it and then use it again, at LINE 173, to display, in a new window, the fldAmnt. Honestly, I don't really care about whether it's an int or String displayed, but I know a String is required for JTextField. What magic am I missing? Answers are always welcome but I prefer a chance to learn. Also, as I'm fairly new to Java, off topic pointers, criticism, and better ways to implement this code is greatly welcomed :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame{
/**
* wtf is the serial version UID = 1L
*/
private static final long serialVersionUID = 1L;
private JButton wdBtn;
private JButton dpBtn;
private JButton xferBtn;
private JButton balBtn;
private JRadioButton chkRadio;
private JRadioButton savRadio;
private JTextField textField;
private static String txtFldAmnt;
private static int fldAmnt = 0;
private static Double chkBal = 0.00;
private static Double savBal = 0.00;
public static void main(String[] args){
new GUI();
}
public GUI() {
//default location and size
this.setSize(300,182);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("ATM Machine");
//add buttons
wdBtn = new JButton("Withdraw");
dpBtn = new JButton("Deposit");
xferBtn = new JButton("Transfer");
balBtn = new JButton("Show Balance");
chkRadio = new JRadioButton("Checking");
chkRadio.setSelected(false);
savRadio = new JRadioButton("Savings");
savRadio.setSelected(false);
textField = new JTextField("", 20);
final JLabel textLabel = new JLabel("Enter amount: ");
textField.setToolTipText("Enter amount");
//Listener class to pass button listeners
ListenForButton lForButton = new ListenForButton();
wdBtn.addActionListener(lForButton);
dpBtn.addActionListener(lForButton);
xferBtn.addActionListener(lForButton);
balBtn.addActionListener(lForButton);
chkRadio.addActionListener(lForButton);
savRadio.addActionListener(lForButton);
ListenForText textFieldListener = new ListenForText();
textField.addKeyListener(textFieldListener);
//Configure layouts
JPanel PANEL = new JPanel();
PANEL.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2,2, 5, 10));
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(1,2,10,10));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(2,1));
//add buttons to their panels
panel1.add(wdBtn);
panel1.add(dpBtn);
panel1.add(xferBtn);
panel1.add(balBtn);
panel2.add(chkRadio);
panel2.add(savRadio);
panel3.add(textLabel);
panel3.add(textField);
PANEL.add(panel1);
PANEL.add(panel2);
PANEL.add(panel3);
this.add(PANEL);
//this.setAlwaysOnTop(true);
this.setVisible(true);
}
//implement listeners
private class ListenForText implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
txtFldAmnt = (e.toString());
fldAmnt = Integer.parseInt(txtFldAmnt);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
private class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent e){
//maybe do case/switch statements
if (e.getSource() == wdBtn) {
JFrame newFrame = new JFrame("Withdraw Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Withdraw Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == dpBtn) {
JFrame newFrame = new JFrame("Deposit Title");
/*
* Set the newFrame.setSize(300,182); to this comment in the if statement to place
* the window directly over current window
*/
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Deposit Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == xferBtn) {
JFrame newFrame = new JFrame("Transfer Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Transfer Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == balBtn){
JFrame newFrame = new JFrame("Balance Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JTextField newLbl = new JTextField(Integer.toString(fldAmnt));
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
}
}
}
-cheers
EDITED BELOW
Thank for the answers, and I'm sorry for the horrible description... but I found a work around, thoguh I'm not sure if it's appropriate.
with the above example:
fldAmnt = Integer.pareseInt(txtFldAmnt)
i just added a .getText() //Though I rewrote the entire source code
fldAmnt = Integer.pareseInt(txtFldAmnt.getText())
it's worked for me for my entire program.
I wish I didn't have to post my entire code below but I haven't decided on a great place to store all of my code yet.
(SUGGESTIONS ARE WELCOME :D)
but here it is:
import javax.swing.;
import java.awt.GridLayout;
import java.awt.event.;
import javax.swing.border.*;
public class ATM extends JFrame{
//buttons needed
JButton wBtn;
JButton dBtn;
JButton xBtn;
JButton bBtn;
//radios needed
JRadioButton cRadio;
JRadioButton sRadio;
//Text field needed
JTextField txt;
JLabel txtLabel;
static int withdraw = 0;
Double amount = 0.00;
Double cBal = 100.00;
Double sBal = 100.00;
double number1, number2, totalCalc;
public static void main(String[] args){
new Lesson22();
}
public ATM(){
this.setSize(400, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("My Third Frame");
wBtn = new JButton("Withdraw");
dBtn = new JButton("Deposit");
xBtn = new JButton("Transfer");
bBtn = new JButton("Show Balance");
cRadio = new JRadioButton("Checking");
sRadio = new JRadioButton("Savings");
txtLabel = new JLabel("Amount: $");
txt = new JTextField("", 10);
JPanel thePanel = new JPanel();
// Create an instance of ListenForEvents to handle events
ListenForButton lForButton = new ListenForButton();
wBtn.addActionListener(lForButton);
dBtn.addActionListener(lForButton);
xBtn.addActionListener(lForButton);
bBtn.addActionListener(lForButton);
// How to add a label --------------------------
// Creates a group that will contain radio buttons
// You do this so that when 1 is selected the others
// are deselected
ButtonGroup operation = new ButtonGroup();
// Add radio buttons to the group
operation.add(cRadio);
operation.add(sRadio);
// Create a new panel to hold radio buttons
JPanel operPanel = new JPanel();
JPanel btnPanel1 = new JPanel();
JPanel btnPanel2 = new JPanel();
btnPanel1.setLayout(new GridLayout(1,2));
btnPanel2.setLayout(new GridLayout(1,2));
Border btnBorder = BorderFactory.createEmptyBorder();
btnPanel1.setBorder(btnBorder);
btnPanel1.add(wBtn);
btnPanel1.add(dBtn);
btnPanel2.setBorder(btnBorder);
btnPanel2.add(xBtn);
btnPanel2.add(bBtn);
Border operBorder = BorderFactory.createBevelBorder(1);
// Set the border for the panel
operPanel.setBorder(operBorder);
// Add the radio buttons to the panel
operPanel.add(cRadio);
operPanel.add(sRadio);
// Selects the add radio button by default
cRadio.setSelected(true);
JPanel txtPanel = new JPanel();
txtPanel.add(txtLabel);
txtPanel.add(txt);
thePanel.add(btnPanel1);
thePanel.add(btnPanel2);
thePanel.add(operPanel);
thePanel.add(txtPanel);
thePanel.setLayout(new GridLayout(4,2));
this.add(thePanel);
this.setVisible(true);
txt.requestFocus();
}
private class ListenForButton implements ActionListener{
// This method is called when an event occurs
public void actionPerformed(ActionEvent e){
/******************************************************
* THIS IS FOR CHECKING
*****************************************************/
// Check if the source of the event was the button
if(cRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
cBal -= amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel cLabel = new JLabel(Double.toString(cBal));
JLabel CLBL = new JLabel("Checking: ");
panel.add(CLBL);
panel.add(cLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
amount = Double.parseDouble(txt.getText());
cBal += amount;
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (sBal >= 0 && sBal >= amount){
cBal += amount;
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
/******************************************************
* THIS IS FOR SAVINGS
*****************************************************/
if(sRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
if(sBal >= 0 && sBal >= amount){
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel sLabel = new JLabel(Double.toString(sBal));
JLabel SLBL = new JLabel("Savings: ");
panel.add(SLBL);
panel.add(sLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
try{
amount = Double.parseDouble(txt.getText());
sBal += amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (cBal >= 0 && cBal >= amount){
sBal += amount;
cBal -= amount;
}
else if (cBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}
...and by the way can anyone explain this warning message:
The serializable class ATM does not declare a static final serialVersionUID field of type long
If not simply don't bother. I'll keep researching into it when I have time.
This is still not complete, but thank you all for your help!
KeyListener on any JTextComponent is a bad idea.
To monitor changes to a text component, use a DocumentListener, to filter the content that a text component can handle, use a DocumentFilter. See Listening for Changes on a Document, Implementing a Document Filter and DocumentFilter Examples for more details.
In your case, it'd probably better to use a JSpinner or JFormattedTextField as they are designed to handle (amongst other things) numbers
See How to Use Spinners and How to Use Formatted Text Fields for more details

Replacing contents of Jframe with new items returns blank Jframe

I have a start up window that creates a jframe with a drop down box, two text boxes and an OK button. After choosing the drop down menu item and then typing in the two text boxes, another function is called that will replace the contents of the JFrame with other content.
One of the drop down choices is to deposit:
public void deposit(String customerID, String customerPIN) {
Customer customer = validate_info(customerID, customerPIN);
if (!found){
if (pin == null) {
jf.notInDatabase();
} else {
jf.invalidAccount(); // if the customer has not been found but the pin has been set that means the pin was invalid
}
} else {
if (customer != null) {
String result = customer.returnInfo();
jf.depositScreen(result);
After looking around on SO for guidance, this is what I have so far:
public void depositScreen(String phrase) {
getContentPane().removeAll();
JLabel customerInfo = new JLabel(phrase);
customerInfo.setFont(new Font("Futura", Font.PLAIN, 12));
getContentPane().add(customerInfo);
JTextField depositAmount = new JTextField("Please enter the amount you would like to deposit in 00.00 format");
depositAmount.setFont(new Font("Futura", Font.PLAIN, 12));
getContentPane().add(depositAmount);
repaint();
validate();
setVisible(true);
}
So far it's turning up a blank gray box without the labels in it. Where am I going wrong?
Here is an example doing what you want. Notice the order of the validates and invalidates.
import javax.swing.*;
import java.awt.*;
public class SwingSwap{
public static void main(String[] args){
EventQueue.invokeLater(()->buildGui());
}
public static void buildGui(){
JFrame frame = new JFrame("swapping");
final JButton a = new JButton("->B");
final JLabel aLabel = new JLabel("A");
final JButton b = new JButton("->A");
final JLabel bLabel = new JLabel("B");
a.addActionListener(evt->{
EventQueue.invokeLater(()->{
Container cont = frame.getContentPane();
cont.removeAll();
cont.add(b);
cont.add(bLabel);
cont.invalidate();
frame.validate();
frame.repaint();
});
});
b.addActionListener(evt->{
EventQueue.invokeLater(()->{
Container cont = frame.getContentPane();
cont.removeAll();
cont.add(a);
cont.add(aLabel);
cont.invalidate();
frame.validate();
frame.repaint();
});
} );
Container cont = frame.getContentPane();
cont.setLayout(new BoxLayout(cont, BoxLayout.PAGE_AXIS));
cont.add(a);
cont.add(aLabel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

Array in Gui to Increment

Hi i have a trouble in my program because i need to set an array for easy way of incrementing it because it is sales so i declare of my array like this iam not yet done of my program this is my program so far .
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class We extends JFrame
{
public static JPanel panel2 = new JPanel();
public static String totallist,addprod;
public static int grandtotal,ve,xxx,z,x,adding,pay,totalp,totalc,payment;
public static JTextField in = new JTextField(z);
public static JTextField ki = new JTextField(15);
public static double disc,totalbayad,sukli;
public static int benta[] = new int [11];
public static String prod[] = new String[11];
public static void main(String[] args)
{
We frameTabel = new We();
prod[1] = "Palmolive";
prod[2] = "Egg";
prod[3] = "Milo";
prod[4] = "Noodles";
prod[5] = "PancitCanton";
prod[6] = "CornBeef";
prod[7] = "LigoSardines";
prod[8] = "CokeSakto";
prod[9] = "RcBig";
prod[10] = "GibsonLespaulGuitar";
benta[1] = 6;
benta[2] = 5;
benta[3] = 6;
benta[4] = 9;
benta[5] = 10;
benta[6] = 25;
benta[7] = 16;
benta[8] = 6;
benta[9] = 16;
benta[10] = 14000;
}
JFrame frame = new JFrame("Customer");
JFrame prodcho = new JFrame("Unofficial receipt");
JFrame want = new JFrame("Buy AGain");
JFrame ftinda = new JFrame("Item && Prices");
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
JLabel lab = new JLabel("Username :");
JLabel pas = new JLabel("Password :");
JLabel cos;
//JPanel panel = new JPanel();
JButton y1;
JButton y2;
We()
{
super("Enter Your Account !");
setSize(300,200);
setLocation(500,280);
panel.setLayout (null);
txuser.setBounds(90,30,150,20);
pass.setBounds(90,65,150,20);
blogin.setBounds(110,100,80,20);
lab.setBounds(15,28,150,20);
pas.setBounds(15,63,150,20);
panel.add(lab);
panel.add(pas);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin()
{
blogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String puname = txuser.getText();
String ppaswd = pass.getText();
if(puname.equals("vincent") && ppaswd.equals("puge"))
{
setVisible(false);
JPanel panel1 = new JPanel();
frame.setVisible(true);
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout());
cos = new JLabel("Do you have a Customer ?");
y1 = new JButton("Yes");
y2 = new JButton("No");
panel1.setLayout(null);
cos.setBounds(70,30,150,20);
y1.setBounds(80,65,150,20);
y2.setBounds(140,65,150,20);
y1.setSize(55,30);
y2.setSize(55,30);
panel1.add(y1);
panel1.add(y2);
panel1.add(cos);
frame.add(panel1);
y1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
if(source == y1)
{
frame.setVisible(false);
//--------------------------------------
int boundsStart=10;
panel.l2.add(new JLabel("-Product-").setBounds(20,boundsStart,150,20));
boundsStart+=20;
for (int i=1; i<11; i++)
{
panel2.add(new JLabel(i+"."+prod[i]).setBounds(20,boundsStart,150,20));
boundsStart+=20;
}
boundsStart = 30; //reset bounds counter
for (int i=1; i<11; i++)
{
panel2.add(new JLabel(""+benta[i]).setBounds(20,boundsStart,150,20));
boundsStart+=20;
}
//You could then change the other JLabels that came after this point in the same way I just did
//price,ent,law, and qx
//--------------------------------------
JLabel vince = new JLabel("-Product-");
JLabel l1 = new JLabel("1."+prod[1]);
JLabel l2 = new JLabel("2."+prod[2]);
JLabel l3 = new JLabel("3."+prod[3]);
JLabel l4 = new JLabel("4."+prod[4]);
JLabel l5 = new JLabel("5."+prod[5]);
JLabel l6 = new JLabel("6."+prod[6]);
JLabel l7 = new JLabel("7."+prod[7]);
JLabel l8 = new JLabel("8."+prod[8]);
JLabel l9 = new JLabel("9."+prod[9]);
JLabel l10 = new JLabel("10."+prod[10]);
JLabel p1 = new JLabel(""+benta[1]);
JLabel p2 = new JLabel(""+benta[2]);
JLabel p3 = new JLabel(""+benta[3]);
JLabel p4 = new JLabel(""+benta[4]);
JLabel p5 = new JLabel(""+benta[5]);
JLabel p6 = new JLabel(""+benta[6]);
JLabel p7 = new JLabel(""+benta[7]);
JLabel p8 = new JLabel(""+benta[8]);
JLabel p9 = new JLabel(""+benta[9]);
JLabel p10 = new JLabel(""+benta[10]);
JLabel price = new JLabel("-Price-");
JButton ent = new JButton("Enter");
JLabel law = new JLabel("Enter No. of Product");
JLabel qx = new JLabel("Enter Quantity");
ftinda.setVisible(true);
ftinda.setSize(350,350);
ftinda.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ftinda.setLayout(new GridLayout());
panel2.setLayout(null);
vince.setBounds(20,10,150,20);
l1.setBounds(20,30,150,20);
l2.setBounds(20,50,150,20);
l3.setBounds(20,70,150,20);
l4.setBounds(20,90,150,20);
l5.setBounds(20,110,150,20);
l6.setBounds(20,130,150,20);
l7.setBounds(20,150,150,20);
l8.setBounds(20,170,150,20);
l9.setBounds(20,190,150,20);
l10.setBounds(20,210,150,20);
p1.setBounds(230,30,150,20);
p2.setBounds(230,50,150,20);
p3.setBounds(230,70,150,20);
p4.setBounds(230,90,150,20);
p5.setBounds(230,110,150,20);
p6.setBounds(230,130,150,20);
p7.setBounds(230,150,150,20);
p8.setBounds(230,170,150,20);
p9.setBounds(230,190,150,20);
p10.setBounds(230,210,150,20);
price.setBounds(225,10,150,20);
in.setBounds(150,250,150,20);
law.setBounds(20,253,150,20);
qx.setBounds(20,280,150,20);
ki.setBounds(150,280,150,20);
ent.setBounds(220,250,150,20);
in.setSize(42,20);
ki.setSize(42,20);
ent.setSize(65,50);
panel2.add(vince);
panel2.add(l1);
panel2.add(l2);
panel2.add(l3);
panel2.add(l4);
panel2.add(l5);
panel2.add(l6);
panel2.add(l7);
panel2.add(l8);
panel2.add(l9);
panel2.add(l10);
panel2.add(p1);
panel2.add(p2);
panel2.add(p3);
panel2.add(p4);
panel2.add(p5);
panel2.add(p6);
panel2.add(p7);
panel2.add(p8);
panel2.add(p9);
panel2.add(p10);
panel2.add(price);
panel2.add(in);
panel2.add(law);
panel2.add(ent);
panel2.add(qx);
panel2.add(ki);
ftinda.add(panel2);
ent.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
ftinda.setVisible(false);
JPanel panel3 = new JPanel();
JLabel cos1 = new JLabel("Do you want to buy more ?");
JButton yy = new JButton("Yes");
JButton nn = new JButton("No");
panel3.setLayout(null);
cos1.setBounds(70,30,150,20);
yy.setBounds(80,65,150,20);
nn.setBounds(140,65,150,20);
yy.setSize(55,30);
nn.setSize(55,30);
panel3.add(cos1);
panel3.add(yy);
panel3.add(nn);
want.add(panel3);
want.setVisible(true);
want.setSize(300,200);
want.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
want.setLayout(new GridLayout());
addprod = prod[];
adding = benta[];
totalp =
totalc = totalp;
totallist = totallist + addprod +"" +x+ "pcs = "+totalc+"pesos";
nn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ea)
{
Object source1 = ea.getSource();
{
if(source1 == nn)
{
JPanel panel4 = new JPanel();
panel4.setLayout(null);
prodcho.setVisible(true);
prodcho.setSize(300,200);
prodcho.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prodcho.setLayout(new GridLayout());
prodcho.add(panel4);
}
}
}
});
}
});
}
}
});
}
else
{
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
}
As PeterMmm stated arrayLists should be able to solve your predicament. ArrayLists allow you to make an array of any type very easily and has a very nice interface such as
mylist.add(element)
Maroun Maroun also made a valid point that you can approach this much more nicely using a loop so that you can avoid the large amount of repitition in your code, but its not necessary to do so if you are happy with it.
Hopefully the following sample of using ArrayList can help you:
http://javarevisited.blogspot.de/2011/05/example-of-arraylist-in-java-tutorial.html
And if you want more information about arraylist here is the docs:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
My last tip, while looking at your code is to add an actionListener to your button, as currently it does nothing ;)
ent.addActionListener(new ActionListener()
{
#Override
public void actionPerformed( ActionEvent e )
{
//..do stuff here or call a function to do stuff :)
}
});
You might want to check out putting this into a bigger loop. You could set up a loop and then use generic statements to add Labels and size them instead of adding a different Label object for each one. It would cut about 20 lines of code.
EDIT: By loops I was talking about how to deal with setting bounds and adding to the panel. An example would be something like
while(condition)
{
panel.add(new JLabel(information).setBounds(bounds));
}
This gets rid of the repetition of having code like:
JLabel p1 = new JLabel(info);
JLabel p2 = new JLabel(info2);
...
panel1.add(p1);
panel1.add(p2);
...
p1.setBounds(bounds1);
p2.setBounds(bounds2);
...

Highlight one specific row/line in JTextArea

I am trying to highlight just one specific row in JTextArea, but I have no idea as to going about it. I need to get the specific row and then highlight it. I've read the other posts, but I still do not understand how to bring it together to solve my problem...help would be much appreciated.
Try your hands on this code example, and do ask if something is not clear :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextHighlight
{
private JTextArea tarea;
private JComboBox cbox;
private JTextField lineField;
private String[] colourNames = {"RED", "ORANGE", "CYAN"};
private Highlighter.HighlightPainter painter;
private void createAndDisplayGUI()
{
final JFrame frame = new JFrame("Text HIGHLIGHT");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5), "Highlighter JTextArea"));
tarea = new JTextArea(10, 10);
JScrollPane scrollPane = new JScrollPane(tarea);
contentPane.add(scrollPane);
JButton button = new JButton("HIGHLIGHT TEXT");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int selection = JOptionPane.showConfirmDialog(
frame, getOptionPanel(), "Highlighting Options : ", JOptionPane.OK_CANCEL_OPTION
, JOptionPane.PLAIN_MESSAGE);
if (selection == JOptionPane.OK_OPTION)
{
System.out.println("OK Selected");
int lineNumber = Integer.parseInt(lineField.getText().trim());
try
{
int startIndex = tarea.getLineStartOffset(lineNumber);
int endIndex = tarea.getLineEndOffset(lineNumber);
String colour = (String) cbox.getSelectedItem();
if (colour == colourNames[0])
{
System.out.println("RED Colour");
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);
tarea.getHighlighter().addHighlight(startIndex, endIndex, painter);
}
else if (colour == colourNames[1])
{
System.out.println("ORANGE Colour");
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.ORANGE);
tarea.getHighlighter().addHighlight(startIndex, endIndex, painter);
}
else if (colour == colourNames[2])
{
System.out.println("CYAN Colour");
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN);
tarea.getHighlighter().addHighlight(startIndex, endIndex, painter);
}
}
catch(BadLocationException ble)
{
ble.printStackTrace();
}
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
System.out.println("CANCEL Selected");
}
else if (selection == JOptionPane.CLOSED_OPTION)
{
System.out.println("JOptionPane closed deliberately.");
}
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getOptionPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2, 5, 5));
JLabel lineNumberLabel = new JLabel("Enter Line Number : ");
lineField = new JTextField(10);
JLabel colourLabel = new JLabel("Select One Colour : ");
cbox = new JComboBox(colourNames);
panel.add(lineNumberLabel);
panel.add(lineField);
panel.add(colourLabel);
panel.add(cbox);
return panel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextHighlight().createAndDisplayGUI();
}
});
}
}
Here is the output of it :
If you are unable to select TextArea to TextField reason is button click causes the JTextArea to lose focus and thus not show its selection.
on button click event use btnImport.transferFocusBackward(); to resolve issue.
do like that :
this is the text area swing of java
JTextArea area = new JTextArea();
int startIndex = area.getLineStartOffset(2);
int endIndex = area.getLineEndOffset(2);
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);
area.getHighlighter().addHighlight(startIndex, endIndex, painter);

Categories