Runtime Error Java app - java

Hi guys I built this app to show students how a loop works graphically, that was working although not correctly, but I'll address that in a question later. I'm not sure what I did to the applet but now I get this runtime error. How do I fix this? thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}

Make the constructor public.
public Checkerboard() {
...
}
The error appears because the constructor is package-private, e.g. you can't instantiate the class outside it's package.

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

Border Layout looping. JPanel/swing

I'm having trouble with my looping and 'BorderLayout'. When I compile and run this using the driver it seems that the add.west(etc) is being overwritten by the proceeding add.west. I am left only with the 9th component in the 'south' panel, with 'east' and 'west' being completely empty. If I change the "for (int i=0; i<8; i++){" to: "for (int i=0; i<2; i++){" I get ONLY the second element of the required 9 in the 'west' panel. Can anyone please tell me why. Forgive my ignorance. I'm a beginner.
Thankyou.
Joe
This is roughly what it should look like:
(WEST) (EAST)
btn0, label0, label0 btn4, label4, label4
btn1, label1, label1 btn5, label5, label5
btn2, label2, label2 btn6, label6, label6
btn3, label3, label3 btn7, label7, label7
(SOUTH)
btn8, label8, label8
//CODE STARTS HERE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.NumberFormat;
public class CoinPanel extends JPanel{
private JButton buttons[] = new JButton[9];
private JLabel multiplySign[] = new JLabel[9];
private JLabel coinCount[] = new JLabel[9];
String [] names= {"1c", "2c", "5c", "10c", "20c", "50c", "€1", "€2", "Reset"};
int [] values= {1, 2, 5, 10, 20, 50, 100, 200, 0};
public CoinPanel(){
for (int i=0; i<8; i++){
buttons[i] = new JButton(names[i]);
buttons[i].addActionListener(new BtnListener());
coinCount[i] = new JLabel("0", JLabel.CENTER);
coinCount[i].setBorder(BorderFactory.createLineBorder(Color.black));
multiplySign[i] = new JLabel ("x", JLabel.CENTER);
//Layout stuff from here:
setLayout (new BorderLayout());
JPanel west= new JPanel();
west.setBackground(Color.BLACK);
JPanel east= new JPanel();
east.setBackground(Color.RED);
JPanel south= new JPanel();
south.setBackground(Color.BLUE);
if(i<4){
west.add (buttons[i]);
west.add (multiplySign[i]);
west.add (coinCount[i]);
}
else if(i<8){
east.add (buttons[i]);
east.add (multiplySign[i]);
east.add (coinCount[i]);
}
else{
multiplySign[i].setText("TOTAL");
south.add (multiplySign[i]);
south.add (coinCount[i]);
south.add (buttons[i]);
}
add(west, BorderLayout.WEST);
add(east, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
}
setPreferredSize (new Dimension(450,300));
}
//To here^^^
private class BtnListener implements ActionListener{
public void actionPerformed (ActionEvent event){
String [] text = new String[9];
int [] intArray = new int [9];
double sum =0;
for (int i=0; i<(intArray.length-1); i++){
if(event.getSource() == buttons[i]){
text[i] = coinCount[i].getText();
intArray[i]=Integer.parseInt(text[i]);
intArray[i] = ((intArray[i]) +1);
coinCount[i].setText(intArray[i] + "");
}
if(event.getSource() == buttons[8]){
coinCount[i].setText("0");
}
sum += (Integer.parseInt(coinCount[i].getText())*values[i]);
NumberFormat nf = NumberFormat.getCurrencyInstance();
coinCount[8].setText(nf.format(sum/100)+"");
}
}
}
}
//AND THIS IS THE DRIVER:
import javax.swing.*;
public class CoinSorter{
public static void main(String[] args){
JFrame frame = new JFrame ("Coin Counter Example");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
CoinPanel panel = new CoinPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Am I not only adding a single Panel to the three locations?
No, you have too much code in your loop.
1) You are creating 3 new panels every time you execute the loop.
the creation of your 3 west, east and south panels should be done before the loop starts.
2) Then at the end of the loop you are adding each of these panels to your main panel.
the three panels should be added to the main panel outside of the loop.
You can only have 1 component at which location at a time.
By adding another component to the same location (e.g. BorderLayout.WEST), you remove previous one. This is code from BorderLayout class that clearly shows that every time you add a WEST component, member variable west gets new value and old one is lost:
if ("Center".equals(name)) {
center = comp;
} else if ("North".equals(name)) {
north = comp;
} else if ("South".equals(name)) {
south = comp;
} else if ("East".equals(name)) {
east = comp;
} else if ("West".equals(name)) {
west = comp;
} else if (BEFORE_FIRST_LINE.equals(name)) {
firstLine = comp;
} else if (AFTER_LAST_LINE.equals(name)) {
lastLine = comp;
} else if (BEFORE_LINE_BEGINS.equals(name)) {
firstItem = comp;
} else if (AFTER_LINE_ENDS.equals(name)) {
lastItem = comp;
} else {
throw new IllegalArgumentException("cannot add to layout: unknown constraint: " + name);
}
}
}
Same goes for other placements.

Beginner Scoring program button development in Java

I'm trying to add a "green team" to an example scoring GUI I found online. For some reason, the code compiles, but it runs with only the original two teams. I've tried playing around with the sizes/locations somewhat clumsily, and since no change was observed with these modications (NO change at ALL), I admit that I must be missing some necessary property or something. Any help? Here's the code:
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonDemo_Extended3 implements ActionListener{
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
int greenScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;
JButton redButton, blueButton, greenButton,resetButton;
public JPanel createContentPane (){
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(0, 0);
titlePanel.setSize(500, 500);
totalGUI.add(titlePanel);
redLabel = new JLabel("Red Team");
redLabel.setLocation(300, 0);
redLabel.setSize(100, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel);
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(900, 0);
blueLabel.setSize(100, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(600, 0);
greenLabel.setSize(100, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(500, 30);
totalGUI.add(scorePanel);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(40, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(60, 0);
greenScore.setSize(40, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
blueScore = new JLabel(""+blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(40, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(2600, 70);
totalGUI.add(buttonPanel);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(30, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(150, 0);
blueButton.setSize(30, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
greenButton = new JButton("Green Score!");
greenButton.setLocation(250, 0);
greenButton.setSize(30, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 100);
resetButton.setSize(50, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if(e.getSource() == redButton)
{
redScoreAmount = redScoreAmount + 1;
redScore.setText(""+redScoreAmount);
}
else if(e.getSource() == blueButton)
{
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText(""+blueScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
redScoreAmount = 0;
blueScoreAmount = 0;
greenScoreAmount = 0;
redScore.setText(""+redScoreAmount);
blueScore.setText(""+blueScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended demo = new ButtonDemo_Extended();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024, 768);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
import javax.swing.*;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonDemo_Extended3 implements ActionListener{
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
int greenScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;
JButton redButton, blueButton, greenButton,resetButton;
public JPanel createContentPane (){
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.setLocation(0, 0);
titlePanel.setSize(500, 500);
redLabel = new JLabel("Red Team");
redLabel.setLocation(300, 0);
redLabel.setSize(100, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel, 0 );
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(900, 0);
blueLabel.setSize(100, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel, 1);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(600, 0);
greenLabel.setSize(100, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(500, 30);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(40, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(60, 0);
greenScore.setSize(40, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
blueScore = new JLabel(""+blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(40, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(2600, 70);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(30, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(150, 0);
blueButton.setSize(30, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
greenButton = new JButton("Green Score!");
greenButton.setLocation(250, 0);
greenButton.setSize(30, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 100);
resetButton.setSize(50, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
totalGUI.add(buttonPanel);
totalGUI.add(scorePanel);
totalGUI.add(titlePanel);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if(e.getSource() == redButton)
{
redScoreAmount = redScoreAmount + 1;
redScore.setText(""+redScoreAmount);
}
else if(e.getSource() == blueButton)
{
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText(""+blueScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
redScoreAmount = 0;
blueScoreAmount = 0;
greenScoreAmount = 0;
redScore.setText(""+redScoreAmount);
blueScore.setText(""+blueScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended3 demo = new ButtonDemo_Extended3();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024, 768);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You have to use a layout manager in order to display your widgets. In this case I used a FlowLayout(). Also, make sure that you add the elements first in the panel and then you add the panel to its parent panel.
Now, the code works as you probably want, but again you should use a particular layout in order to arrange the panels inside the frame.
If I run your code unmodified, I see just the "Red Team" label, and some buttons which are too small to read the text (and some of them only appear when moused over).
If you comment out all the null layouts:
//buttonPanel.setLayout(null);
then all three buttons and labels appear properly.
Doing without a layout manager, and using absolute positioning, is possible (see the Java Swing tutorial page on this exact topic) but not usually recommended. There is a lot of information on using layout managers in the Laying Out Components Within a Container lesson of the Swing tutorials.

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