Unable to find the coordinates of the pressed buttons - java

only problem is that whenever i set initial value for the x and y to be greater than 10,it gives bad result.Please help.It works fine for the values less than 10 for x and y.
i have also debugged it and find out whenever the button is pressed after the 10th index it behaves like setting the variable i to 1.i am unable to fix this issue as i am new in java.so i really need help in this.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JFrame;
class butMaddFrame extends JFrame implements ActionListener
{
int x=12;
int y=12;
JButton[][] buttons = new JButton[x][y];
JPanel mPanel = new JPanel();
JPanel bPanel = new JPanel();
JPanel cPanel = new JPanel();
JTextArea scoreKeeper = new JTextArea();
Container c = getContentPane();
int[][] intArray = new int[x][y];
public butMaddFrame()
{
butGen();
score2();
//cPanel.add(scoreKeeper);
bPanel.setLayout(new GridLayout(x,y));
mPanel.setLayout(new BorderLayout());
mPanel.add(bPanel, BorderLayout.CENTER);
// mPanel.add(cPanel, BorderLayout.LINE_END);
c.add(mPanel);
setTitle("ButtonMaddness");
setSize(1000,400);
setLocation(200,200);
setVisible(true);
}
private void butGen()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
{
buttons[i][j] = new JButton(String.valueOf(i)+"x"+String.valueOf(j));
buttons[i][j].setActionCommand("button" +i +"_" +j);
buttons[i][j].addActionListener(this);
bPanel.add(buttons[i][j]);
}
}
private void score()
{
// String string = "";
// for(int i=0;i<x;i++)
// {
// for(int j=0;j<y;j++)
// string += i+"x"+j+" => " +String.valueOf(intArray[i][j]) +"\t";
// string+= "\n";
// }
// scoreKeeper.setText(string);
}
private void score2()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
buttons[i][j].setText(String.valueOf(intArray[i][j]));
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().contains("button"))
{
int i = Integer.parseInt(Character.toString(e.getActionCommand().replaceAll("button","").replaceAll ("_", "").charAt(0)));
int j = Integer.parseInt(Character.toString(e.getActionCommand().replaceAll("button","").replaceAll ("_", "").charAt(1)));
intArray[i][j]++;
// buttons[i][j].setVisible(false);
buttons[i][j].setBackground(Color.black);
System.out.println(e.getActionCommand() +" " +i +" " +j);
}
// score2();
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class buttonMaddness {
public static void main(String[] args)
{
butMaddFrame myFrame = new butMaddFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Your problem is here:
replaceAll("_", "").charAt(0)
because some of your buttons have things like 11_9 for
example. So you get just the first 1 of the number 11.
Just change your actionPerformed method
to this and your bug will be fixed.
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().contains("button")) {
String str = e.getActionCommand().replaceAll("button", "");
System.out.println(str);
String[] v = str.split("_");
int i = Integer.parseInt(v[0]);
int j = Integer.parseInt(v[1]);
/*
int i = Integer.parseInt(Character.toString(e.getActionCommand()
.replaceAll("button", "").replaceAll("_", "").charAt(0)));
int j = Integer.parseInt(Character.toString(e.getActionCommand()
.replaceAll("button", "").replaceAll("_", "").charAt(1)));
*/
intArray[i][j]++;
// buttons[i][j].setVisible(false);
buttons[i][j].setBackground(Color.black);
System.out.println(e.getActionCommand() + " " + i + " " + j);
}
// score2();
}

Related

Swing app freezes after a while when JFreeChart have a lot series

I'm writing a program which would display incoming data while day. It's getting data about every 600 milliseconds and adding it to the TimeSeries Chart. The problem is: after about 10 minutes of work, GUI starts freezing. But if display only few series of 33 it's become fine. So maybe I am doing something wrong?
How to solve that freezing? My SwingWorker may be weak, or chosen JFreeChart collection.
Any tips might be helpful, thank you!
My short code example:
import java.awt.event.ActionEvent;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.ChartFactory;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.data.xy.XYSeries;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYDataset;
import java.awt.Dimension;
import java.awt.Component;
import javax.swing.JCheckBox;
import org.jfree.chart.ChartPanel;
import java.awt.LayoutManager;
import java.awt.BorderLayout;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import java.awt.event.ActionListener;
import java.awt.Window;
import org.jfree.chart.ui.UIUtils;
import javax.swing.JPanel;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Paint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.SwingWorker;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.ui.ApplicationFrame;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
public class HideSeriesDemo1 extends ApplicationFrame {
public HideSeriesDemo1(final String title) {
super(title);
this.setContentPane(new MyDemoPanel());
}
public static JPanel createDemoPanel() {
return new MyDemoPanel();
}
public static void main(final String[] args) {
final HideSeriesDemo1 demo = new HideSeriesDemo1("JFreeChart: HideSeriesDemo1.java");
demo.pack();
UIUtils.centerFrameOnScreen(demo);
demo.setVisible(true);
}
static class MyDemoPanel extends JPanel implements ActionListener {
final JFreeChart chart;
private JPanel boxPanel;
TimeSeriesCollection seriesArray;
private XYItemRenderer renderer;
private void setLinesVisible() {
for (int i = 0; i < seriesArray.getSeriesCount(); i++) {
renderer.setSeriesVisible(i, true);
JCheckBox box = (JCheckBox) boxPanel.getComponent(i);
box.setSelected(true);
}
}
private void setLinesInvisible() {
for (int i = 0; i < seriesArray.getSeriesCount(); i++) {
renderer.setSeriesVisible(i, false);
JCheckBox box = (JCheckBox) boxPanel.getComponent(i);
box.setSelected(false);
}
}
private XYDataset createNumberedDataSet(int num) {
seriesArray = new TimeSeriesCollection();
for (int i = 0; i < num; i++) {
int num2 = i + 1;
TimeSeries s1 = new TimeSeries("Channel №" + num2);
seriesArray.addSeries(s1);
}
return seriesArray;
}
public MyDemoPanel() {
super(new BorderLayout());
final XYDataset dataset = this.createNumberedDataSet(33);
chart = this.createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
boxPanel = new JPanel();
boxPanel.setLayout(new GridLayout(0, 11));
boxPanel.validate();
for (int i = 0; i < 33; i++) {
int numchik = i + 1;
JCheckBox box1 = new JCheckBox("Channel №" + numchik);
String com = "S" + numchik;
box1.setSelected(true);
box1.setActionCommand(com);
box1.addActionListener(this);
boxPanel.add(box1);
}
boxPanel.validate();
final JButton btn = new JButton("All not sellected");
btn.setVisible(true);
btn.setActionCommand("btn");
btn.addActionListener(this);
boxPanel.add(btn);
final JButton btn2 = new JButton("All sellected");
btn2.setVisible(true);
btn2.setActionCommand("btn2");
btn2.addActionListener(this);
boxPanel.add(btn2);
final JButton btn3 = new JButton("SwingWorker?");
btn3.setVisible(true);
btn3.setActionCommand("btn3");
btn3.addActionListener(this);
boxPanel.add(btn3);
this.add(chartPanel);
this.add(boxPanel, "South");
JPopupMenu pop = chartPanel.getPopupMenu();
pop.add(new JSeparator());
JMenuItem remBtn = new JMenuItem("All not selected");
remBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
setLinesInvisible();
}
});
pop.add(remBtn);
JMenuItem addBtn = new JMenuItem("All visible");
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
setLinesVisible();
}
});
pop.add(addBtn);
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart chart = ChartFactory.createTimeSeriesChart("xDisplay", "Time", "Data", dataset, true, true, false);
final XYPlot plot = (XYPlot) chart.getPlot();
this.renderer = plot.getRenderer();
return chart;
}
#Override
public void actionPerformed(final ActionEvent e) {
int series = -1;
if (e.getActionCommand().equals("btn")) {
this.setLinesInvisible();
System.out.println("set invisible btn pressed");
boxPanel.validate();
// System.out.println("btn pressed");
return;
}
if (e.getActionCommand().equals("btn2")) {
setLinesVisible();
boxPanel.validate();
System.out.println("setBtnVisible pressed");
return;
}
if (e.getActionCommand().equals("btn3")) {
System.out.println("swingworker");
MySwingWorker swi = new MySwingWorker();
swi.execute();
}
for (int i = 0; i<33;i++){
String s="S"+i;
if (e.getActionCommand().equals(s)) {
series = i-1;
}
}
if (series >= 0) {
final boolean visible = this.renderer.getItemVisible(series, 0);
this.renderer.setSeriesVisible(series, !visible);
}
}
private class MySwingWorker extends SwingWorker<Boolean, double[]> {
LinkedList<Double> fifo = new LinkedList<Double>();
public MySwingWorker() {
fifo.add(0.0);
}
#Override
protected Boolean doInBackground() {
while (!isCancelled()) {
try {
Thread.sleep(600);
} catch (InterruptedException ex) {
Logger.getLogger(HideSeriesDemo1.class.getName()).log(Level.SEVERE, null, ex);
}
fifo.add(fifo.get(fifo.size() - 1) + Math.random() - .5);
if (fifo.size() > 1000) {
fifo.removeFirst();
}
double[] array = new double[fifo.size()];
for (int i = 0; i < fifo.size(); i++) {
array[i] = fifo.get(i);
}
System.out.println(array.length + " : " + Arrays.toString(array) + "Array: ");
publish(array);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// eat it. caught when interrupt is called
System.out.println("MySwingWorker shut down." + " name:" + Thread.currentThread().getName());
}
}
return true;
}
#Override
protected void process(List<double[]> chunks) {
double[] mostRecentDataSet = chunks.get(chunks.size() - 1);
for (int i = 0; i < seriesArray.getSeriesCount(); i++) {
TimeSeries series = seriesArray.getSeries(i);
series.addOrUpdate(new Millisecond(), mostRecentDataSet[0] + i);
}
fifo.removeFirst();
System.out.println(" repaint zone " + " name:" + Thread.currentThread().getName());
}
}
}
}

JTextArea is not updating [duplicate]

This question already has answers here:
Why is my JTextArea not updating?
(6 answers)
JTextArea not updating dynamically
(2 answers)
Closed 2 years ago.
I have a code where I'm taking input from user and after clicking on SUBMIT button it executes my logic and shows user a JTextArea on a new frame but the problem is it shows after program executes totally. I have used System.out.println and consoleText.append to see if it's happening on both eclipse and JTextArea but console on eclipse was updating with the code executes but JTextArea only shows when code executes totally.
Here's the code -
MainApp.java
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import com.skillnetinc.marker.utility.InputUtility;
public class MainApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI();
}
});
}
protected static void showGUI() {
JFrame inputFrame = new JFrame("Marker Deletion Script");
inputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inputFrame.setSize(800, 300);// 800 width and 500 height
inputFrame.setLayout(null);// using no layout managers
inputFrame.setVisible(true);// making the frame visible
inputFrame.setLocationRelativeTo(null);
InputUtility.showUserInputFields(inputFrame);
InputUtility.buttonActivity(inputFrame);
}
}
& InputUtility.java
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class InputUtility {
public static JFrame tableFrame;
public static JTextArea markerDesc, consoleText;
public static JLabel labelMarkerDesc;
public static void showUserInputFields(JFrame inputFrame) {
labelMarkerDesc = new JLabel("<html>Marker<br>Description</html>");
labelMarkerDesc.setBounds(50, 115, 100, 30);
markerDesc = new JTextArea(10, 20);
markerDesc.setBounds(150, 15, 300, 230);
markerDesc.setBorder(BorderFactory.createLineBorder(Color.gray));
inputFrame.add(markerDesc);
inputFrame.add(labelMarkerDesc);
}
public static void buttonActivity(JFrame inputFrame) {
JButton submit = new JButton("SUBMIT");
submit.setBounds(520, 50, 150, 40);
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
consoleText = new JTextArea();
consoleText.setEditable(false);
consoleText.setVisible(true);
JScrollPane sp = new JScrollPane(consoleText);
tableFrame = new JFrame("Script Result");
tableFrame.add(sp);
tableFrame.setSize(800, 300);
tableFrame.setVisible(true);
tableFrame.setLocationRelativeTo(null);
testConsole(consoleText);
}
});
inputFrame.add(submit);
}
public static void testConsole(JTextArea consoleText) {
String marker[] = InputUtility.markerDesc.getText().split("\n");
for (int i = 0; i < marker.length; i++) {
String posName = marker[i].split(" ")[0];
File file = new File("\\\\" + posName + "\\C$\\environment\\marker");
consoleText.append("\nChecking for marker inside " + file);
System.out.println("\nChecking for marker inside " + file);
File[] files = file.listFiles();
if (file.canRead()) {
consoleText.append("Found Total " + files.length + " markers inside " + file);
System.out.println("Found Total " + files.length + " markers inside " + file);
}
}
}
}
Input from user will be something like
192.168.75.18 startup.err
192.168.87.99 startup.err
192.168.66.38 startup.err

JPanel refreshes everytime the JFrame is resized

Whenever I move my window on the display; the images and text constantly refresh.
Because some content is generated randomly and then drawn, it regenerates and redraws the randomly generated parts on each refresh.
How can I make them only refresh when I want them too?
In this case, when monsterHealth reaches 0.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.image.*;
public class RPGClicker {
static int attackLevel = 1;
static int defenceLevel = 1;
static int hitpointsLevel = 1;
static int xp = 0;
static int gold = 0;
static int dps = 0;
static int clickDamage = attackLevel;
static int health = hitpointsLevel * 100;
static int healthRecovery = 1;
static int room = 1;
public static void main(String[] args) n{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
mainGameScene();
}
});
}
public static void mainGameScene() {
JFrame window;
mainGamePanel mainGameInstance;
window = new JFrame("RPGClicker: An Unknown Quest!");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BorderLayout());
window.setResizable(false);
mainGameInstance = new mainGamePanel();
window.add(mainGameInstance, BorderLayout.CENTER);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.util.*;
class mainGamePanel extends JPanel {
BufferedImage background, user;
public Dimension getPreferredSize() {
return new Dimension(1280, 720);
}
public void paintComponent(Graphics pencil) {
super.paintComponent(pencil);
background = ImageLoader.loadImage("rec/alpha/background0.png");
user = ImageLoader.loadImage("rec/alpha/user.png");
pencil.drawImage(background, 0, 0, null);
pencil.drawImage(user, 100, 450, null);
Monster monster = new Monster();
pencil.drawImage(monster.monsterSprite, 900, 50, null);
pencil.drawString(monster.monsterName, 900, 60);
}
public mainGamePanel() {
}
}
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.util.*;
public class Monster {
static final double BASE_MONSTER_HEALTH = 10;
static double monsterHealth = Math.pow(RPGClicker.room, 2) * BASE_MONSTER_HEALTH;
static double monsterDamage = RPGClicker.room + 1 - RPGClicker.defenceLevel;
BufferedImage monsterSprite;
String monsterName;
Random rand = new Random();
public Monster() {
String monster[] = {"Ork", "Mermaid", "Goblin"};
String monsterType = monster[rand.nextInt(monster.length)];
monsterSprite = ImageLoader.loadImage("rec/alpha/monster/" + monsterType + ".png");
String[] firstName = {"Oliver", "George", "Harry"};
String connection1 = " the ";
String[] secondName = {"Powerful ", "Unstoppable ", "Almighty "};
String connection2 = " of ";
String[] thirdName = {"Death", "America", "Pride"};
monsterName = firstName[rand.nextInt(firstName.length)] + connection1 + secondName[rand.nextInt(secondName.length)] + monsterType + connection2 + thirdName[rand.nextInt(thirdName.length)];
}
}
You're making your painting method do too much. Please understand that:
A painting method (e.g., paintComponent) is for painting and painting only.
Do not read in image files or do any other file I/O within these methods as this will critically slow down rendering, making your GUI seem poorly responsive. Why keep re-reading in images anyway when they only need to be and should be read in once.
Do not put in any program logic, such as Monster creation, within these methods since you do not have full control over when or even if a painting method is fired. Put the logic and object creation elsewhere.

What does it mean when my compiler tells me I'm using unsafe or unchecked operations?

My program compiles fine, but my console spits out the following:
----jGRASP exec: javac -g CreditGraphics.java
Note: CreditGraphics.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
----jGRASP: operation complete.
First, what makes an operation unsafe? And how can a process be "unchecked"? What does "Recompile with -Xlint" mean? I'm using jGrasp and I'm not sure if that's a button or some sort of command? I want to see the details. It doesn't specify what is unsafe or unchecked, but here's my code anyway:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.Properties;
import javax.mail.Header;
import java.util.Enumeration;
import java.util.Properties;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JApplet;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.URLName;
import java.beans.*;
import java.util.ArrayList;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import java.util.Scanner;
import java.awt.image.*;
import java.io.*;
import java.net.URL;
import javax.imageio.*;
import javax.swing.Timer;
public class CreditGraphics {
//first screen variables
public String cardNum;
public JFrame frame;
public JPanel panel;
public JLabel label;
public JTextField text;
public String cardType = "";
public String carddigits;
public boolean cardValid;
public int length;
public String[] cardTypes;
public JComboBox cardTypesDD;
public static ArrayList<Integer> holdDigits = new ArrayList<Integer>();
public static ArrayList<String> holdDigitsChar = new ArrayList<String>();
public static int[] checkDigits;
public static int checkSum = 0;
//second screen variables in verifyScreen;
public JFrame vframe;
public JPanel vpanel;
public JLabel titlelabel;
public GridBagConstraints grid;
public JLabel namelabel;
public JTextField namefield;
public CreditGraphics() {
frame = new JFrame("MES Banking App");
panel = new JPanel();
label = new JLabel();
cardTypes = new String[4];
cardTypes[0] = "Visa";
cardTypes[1] = "American Express";
cardTypes[2] = "Master Card";
cardTypes[3] = "";
cardTypesDD = new JComboBox(cardTypes);
cardTypesDD.setSelectedIndex(3);
text = new JTextField(16);
panel.add(label);
panel.add(cardTypesDD);
panel.add(text);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(500, 500));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
label.setText("<html>Please enter your credit card <br> 'Master Card' 'Visa' or 'American Express'</html>");
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//after CC type is entered, prompt user to enter digits
carddigits = text.getText();//gets credit card number from jtextfield
length = carddigits.length();//sets length of card
validateCard(); //uses credit card number and length to determine if it matches up to brand
//below returns if card is valid
if (cardValid == true) {
label.setText("Card brand is valid");
}
waits(1);
text.setText("");
waits(1);
checkDigits();
}
});
cardTypesDD.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
//where program really starts
while (cardTypesDD.getSelectedIndex() == 3) {
label.setText("First, please select a card type from DD list");
}
cardType = (String) cardTypesDD.getSelectedItem();
System.out.println(cardType);
if (!cardType.equals("")) {
label.setText("Thank you, now please enter your card #");
}
//now go to the jtextfield actionlistener
}});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
new CreditGraphics();
}});
}
public void verifyScreen() {
//destroy old frame
frame.dispose();
//create new frame essentially same as last frame
vframe = new JFrame("MES Banking App");
vpanel = new JPanel();
titlelabel = new JLabel("Verification Page");
namelabel = new JLabel("Name: ");
namefield = new JTextField(20);
//title section
vpanel.setLayout(new GridBagLayout());
grid = new GridBagConstraints();
grid.fill = GridBagConstraints.PAGE_START;
grid.weightx = 0;
grid.gridx = 0;
grid.gridy = 0;
vpanel.add(titlelabel, grid);
//name section
grid.gridy = 1;
grid.insets = new Insets(10, 0, 0, 0);
vpanel.add(namelabel, grid);
grid.gridx = 1;
grid.insets = new Insets(10, 10, 0, 0);
vpanel.add(namefield, grid);
vframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
vframe.getContentPane().add(vpanel);
vframe.pack();
vframe.setVisible(true);
}
public static void waits(int k) {
long time0, time1;
time0 = System.currentTimeMillis();
do {
time1 = System.currentTimeMillis();
} while ((time1 - time0) < k * 1000);
}
public void validateCard() {
//check brand
cardValid = false;
if ((cardType.equals("Visa") && carddigits.substring(0, 1).equals("4")) && (length == 13 || length == 16)) {
label.setText("Thank you, next step");
cardValid = true;
}
if ((cardType.equals("Master Card")) && (carddigits.substring(0, 2).equals("51") || carddigits.substring(0, 2).equals("52") || carddigits.substring(0, 2).equals("53") || carddigits.substring(0, 2).equals("54") || carddigits.substring(0, 2).equals("55")) && (length == 16)) {
label.setText("Thank you, next step");
cardValid = true;
}
if ((cardType.equals("American Express") && carddigits.substring(0, 2).equals("37") && length == 15)) {
label.setText("Thank you, next step");
cardValid = true;
}
if (cardValid != true) {
System.out.println("ERROR");
label.setText("ERROR");
waits(2);
System.exit(0);
}
//end check
}
public void checkDigits() {
label.setText("Checking digits using Luhn's algorithm...");
waits(2);
//check digits
checkDigits = new int[length];
for (int i = 0; i < length; i++) {
checkDigits[i] = Integer.parseInt(carddigits.substring(i, i + 1));
//successfully puts digits into array
}
for (int e = length - 2; e >= 0; e -= 2) {
checkDigits[e] = 2 * checkDigits[e];
}
for (int d = 0; d < length; d++) {
holdDigitsChar.add(String.valueOf(checkDigits[d]));
}
for (int v = 0; v < length; v++) {
if (holdDigitsChar.get(v).length() == 2) {
holdDigits.add(Integer.parseInt(holdDigitsChar.get(v).substring(0, 1)));
holdDigits.add(Integer.parseInt(holdDigitsChar.get(v).substring(1, 2)));
} else {
holdDigits.add(Integer.parseInt(holdDigitsChar.get(v)));
}
}
for (int c = 0; c < holdDigits.size(); c++) {
checkSum += holdDigits.get(c);
}
System.out.println("Check sum:" + checkSum);
if (checkSum % 10 == 0) {
label.setText("Numbers check out, thank you");
waits(2);
verifyScreen();
} else {
System.out.println("ERROR");
System.exit(0);
}
}
}
This usually comes up if you're using collections or some other genericized object without generic parameters. For example:
List l = new ArrayList();
vs.
List<String> l = new ArrayList<>(); //or new ArrayList<String>(); in Java < 7
What this means is that the Java compiler cannot guarantee that you are using those collections in a type-safe way. For example, you should shove a String and an Integer into the ArrayList in the first scenario. At some point when you pull it out, there is a distinct possibility that you may attempt to cast the Integer instance into a String, which would result in a ClassCastException. You could, of course, be really, really, careful and not do this, but the compiler is simply alerting you to the fact that there is no way to guarantee what is inside that list.
To get rid of this warning, use the second method of instantiation. If you are sure that you can get away with this (in some instances it is possible because you can be sure what the collection will contain) you can use the #SuppressWarnings("unchecked") annotation.

Output a matrix in JTextArea [duplicate]

This question already has answers here:
how to convert a matrix in string in order to output it in JTextArea
(4 answers)
Closed 9 years ago.
I am trying to output a matrix in JTextArea, but I have problems with converting the matrix into string in order to output it...
My whole class is:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.*;
class ConvertMatrix extends JFrame implements ActionListener
{
JLabel rows = new JLabel ("Numri i rreshtave"+'\n');
JTextField inrows = new JTextField (5);
JLabel columns = new JLabel ("Numri i kolonave eshte");
JTextField incolumns = new JTextField (5);
JLabel matrix = new JLabel("Matrica ka formen");
JTextField inmatrix = new JTextField(30);
JButton mat = new JButton("Afisho matricen");
JTextArea matric = new JTextArea(10,21);
int x;
int y;
int[][] matrica = new int [x][y];
public ConvertMatrix ()
{
super ("Matrica e konvertuar");
setSize(300, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Container content = getContentPane();
content.setLayout(new FlowLayout ());
content.setBackground(Color.pink);
content.add(rows);
rows.setForeground(Color.blue);
content.add(inrows);
content.add(columns);
columns.setForeground(Color.red);
content.add(incolumns);
content.add(matrix);
content.add(inmatrix);
matrix.setForeground(Color.gray );
content.add(mat);
content.add(matric);
mat.addActionListener(this);
setContentPane(content);
}
public void mbushMatricen(int x, int y){
for (int i =0; i<x; i++)
for (int j=0; j<y; j++)
matrica[i][j]=(int) ((double) Math.random()*10);
}
public void actionPerformed(ActionEvent event)
{
String rresht = inrows.getText();
int rreshtii = Integer.parseInt(rresht);//kthimi i stringut ne integer
String shtyll = incolumns.getText();
int shtylle = Integer.parseInt(shtyll);
mbushMatricen(rreshtii,shtylle);
String matricaString = "";
for( int i=0; i<rreshtii; i++){
for( int j=0; j<shtylle; j++){
matricaString += matrica[i][j] + " ";
}
matricaString += "\n";
}
matric.setText(matricaString);
}
public static void main(String []args)
{ ConvertMatrix m = new ConvertMatrix();
}
}
the problem is that it gives me these error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at ConvertMatrix.mbushMatricen(ConvertMatrix.java:87)
at ConvertMatrix.actionPerformed(ConvertMatrix.java:98)
where line 87 is: matrica[i][j]=(int) ((double) Math.random()*10);
where line 98 is: mbushMatricen(rreshtii,shtylle);
I have also tried these method:
public void actionPerformed(ActionEvent event)
{
String rresht = inrows.getText();
int rreshtii = Integer.parseInt(rresht);//kthimi i stringut ne integer
String shtyll = incolumns.getText();
int shtylle = Integer.parseInt(shtyll);
mbushMatricen(rreshtii,shtylle);
StringBuilder matricaString = new StringBuilder();
for( int i=0; i<rreshtii; i++)
for( int j=0; j<shtylle; j++)
matricaString.append(Character.toString(matrica[i][j]));
matric.setText(matricaString.toString());
}
but is said to me: The method toString(char) in the type Character is not applicable for the arguments (int)
PLEASE CAN YOU HELP ME...I am a beginner in java
This worked well:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.*;
public class ConvertMatrix extends JFrame implements ActionListener{
JLabel rows = new JLabel ("Numri i rreshtave"+'\n');
JTextField inrows = new JTextField (5);
JLabel columns = new JLabel ("Numri i kolonave eshte");
JTextField incolumns = new JTextField (5);
JLabel matrix = new JLabel("Matrica ka formen");
JTextField inmatrix = new JTextField(30);
JButton mat = new JButton("Afisho matricen");
JTextArea matric = new JTextArea(10,21);
int x;
int y;
double[][] matrica;
public ConvertMatrix (){
super ("Matrica e konvertuar");
setSize(300, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Container content = getContentPane();
content.setLayout(new FlowLayout ());
content.setBackground(Color.pink);
content.add(rows);
rows.setForeground(Color.blue);
content.add(inrows);
content.add(columns);
columns.setForeground(Color.red);
content.add(incolumns);
content.add(matrix);
content.add(inmatrix);
matrix.setForeground(Color.gray );
content.add(mat);
content.add(matric);
mat.addActionListener(this);
setContentPane(content);
}
public void mbushMatricen(int x, int y){
matrica = new double[x][y];
for (int i =0; i<x; i++){
for (int j=0; j<y; j++){
matrica[i][j]=((double) Math.random()*10);
}
}
}
public void actionPerformed(ActionEvent event){
String rresht = inrows.getText();
int rreshtii = Integer.parseInt(rresht);//kthimi i stringut ne integer
String shtyll = incolumns.getText();
int shtylle = Integer.parseInt(shtyll);
mbushMatricen(rreshtii,shtylle);
String matricaString = "";
for(int i=0; i<rreshtii; i++){
for( int j=0; j<shtylle; j++){
matricaString += matrica[i][j] + " ";
}
matricaString += "\n";
}
matric.setText(matricaString);
}
public static void main(String []args){
ConvertMatrix m = new ConvertMatrix();
}
}
You should use DecimalFormat class
import java.text.DecimalFormat;
formatter = new DecimalFormat("#0");
matricaString += formatter.format(matrica[i][j]) + " ";
DecimalFormat

Categories