I have looked at many of the other threads that are related to this, however none of the suggested fixes worked.
I have tried doing contentPanel.revalidate(); and contentPanel.repaint();, after adding it. I have tried adding both the JScrollPane and JTextArea to the contentPanel, and I have tried individually. I have tried changing from a JTextArea to a JTextPane, however none of that worked. The JTextArea shows up fine without the JScrollPane, but when I add it, the JTextArea completely disappears.
I am using a null layout, and I think that could be the issue, but if there is a solution that doesn't involve changing the layout, I would much prefer that. If there is no way to fix it other that changing the layout, please let me know. Thanks.
Here is the code (It is a JDialog window that is a popup off of the main window):
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class TransactionsDialog extends JDialog
{
private static final long serialVersionUID = 6939141004692809959L;
private final JPanel contentPanel = new JPanel();
private SimpleDateFormat monthDate = new SimpleDateFormat("MMMM");
private JTextArea txtTransactions;
private JComboBox<String> comboStartMonth;
private JComboBox<Integer> comboStartDay;
private JComboBox<Integer> comboStartYear;
private JComboBox<String> comboEndMonth;
private JComboBox<Integer> comboEndDay;
private JComboBox<Integer> comboEndYear;
private JCheckBox chckbxStartDate;
private JCheckBox chckbxEndDate;
/**
* Create the dialog.
*/
public TransactionsDialog(BankAccount account)
{
setResizable(false);
/**
* Populating (Day, Month, Year) Arrays.
*/
ArrayList<String> monthList = new ArrayList<String>();
for(int month = 0; month < 12; month++)
{
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
String monthName = monthDate.format(calendar.getTime());
monthList.add(monthName);
}
ArrayList<Integer> dayList = new ArrayList<Integer>();
for(int day = 1; day <= 31; day++)
{
dayList.add(day);
}
ArrayList<Integer> yearList = new ArrayList<Integer>();
for(int year = 1980; year <= Calendar.getInstance().get(Calendar.YEAR); year++)
{
yearList.add(year);
}
setTitle("Transactions of " + account);
setBounds(100, 100, 404, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
comboStartMonth = new JComboBox<String>();
comboStartMonth.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
comboStartMonth.setModel(new DefaultComboBoxModel<String>(monthList.toArray(new String[monthList.size()])));
comboStartMonth.setEnabled(false);
comboStartMonth.setBounds(100, 8, 118, 20);
contentPanel.add(comboStartMonth);
comboStartDay = new JComboBox<Integer>();
comboStartDay.setModel(new DefaultComboBoxModel<Integer>(dayList.toArray(new Integer[dayList.size()])));
comboStartDay.setEnabled(false);
comboStartDay.setBounds(228, 8, 71, 20);
comboStartDay.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboStartDay);
comboStartYear = new JComboBox<Integer>();
comboStartYear.setModel(new DefaultComboBoxModel<Integer>(yearList.toArray(new Integer[yearList.size()])));
comboStartYear.setSelectedIndex(comboStartYear.getItemCount() - 1);
comboStartYear.setEnabled(false);
comboStartYear.setBounds(309, 8, 71, 20);
comboStartYear.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboStartYear);
comboEndMonth = new JComboBox<String>();
comboEndMonth.setModel(new DefaultComboBoxModel<String>(monthList.toArray(new String[monthList.size()])));
comboEndMonth.setEnabled(false);
comboEndMonth.setBounds(100, 34, 119, 20);
comboEndMonth.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboEndMonth);
comboEndDay = new JComboBox<Integer>();
comboEndDay.setModel(new DefaultComboBoxModel<Integer>(dayList.toArray(new Integer[dayList.size()])));
comboEndDay.setEnabled(false);
comboEndDay.setBounds(228, 34, 71, 20);
comboEndDay.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboEndDay);
comboEndYear = new JComboBox<Integer>();
comboEndYear.setModel(new DefaultComboBoxModel<Integer>(yearList.toArray(new Integer[yearList.size()])));
comboEndYear.setSelectedIndex(comboEndYear.getItemCount() - 1);
comboEndYear.setEnabled(false);
comboEndYear.setBounds(309, 34, 71, 20);
comboEndYear.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboEndYear);
txtTransactions = new JTextArea();
txtTransactions.setFont(new Font("Courier New", Font.PLAIN, 11));
txtTransactions.setEditable(false);
txtTransactions.setBounds(10, 63, 368, 187);
JScrollPane txtTScrollPane = new JScrollPane(txtTransactions);
contentPanel.add(txtTScrollPane);
contentPanel.revalidate();
contentPanel.repaint();
chckbxStartDate = new JCheckBox("Start Date:");
chckbxStartDate.setBounds(6, 7, 89, 23);
chckbxStartDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(chckbxStartDate.isSelected())
{
comboStartMonth.setEnabled(true);
comboStartDay.setEnabled(true);
comboStartYear.setEnabled(true);
}
else
{
comboStartMonth.setEnabled(false);
comboStartDay.setEnabled(false);
comboStartYear.setEnabled(false);
}
listTransactions(account);
}
});
contentPanel.add(chckbxStartDate);
chckbxEndDate = new JCheckBox("End Date:");
chckbxEndDate.setBounds(6, 33, 89, 23);
chckbxEndDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(chckbxEndDate.isSelected())
{
comboEndMonth.setEnabled(true);
comboEndDay.setEnabled(true);
comboEndYear.setEnabled(true);
}
else
{
comboEndMonth.setEnabled(false);
comboEndDay.setEnabled(false);
comboEndYear.setEnabled(false);
}
listTransactions(account);
}
});
contentPanel.add(chckbxEndDate);
listTransactions(account);
}
private void listTransactions(BankAccount account)
{
LocalDateTime startTime;
LocalDateTime endTime;
String startMonthName = (String) comboStartMonth.getSelectedItem();
int startDay = (int) comboStartDay.getSelectedItem();
int startYear = (int) comboStartYear.getSelectedItem();
String endMonthName = (String) comboEndMonth.getSelectedItem();
int endDay = (int) comboEndDay.getSelectedItem();
int endYear = (int) comboEndYear.getSelectedItem();
if(chckbxStartDate.isSelected())
{
int startMonth = Month.valueOf(startMonthName.toUpperCase()).getValue();
try
{
startTime = LocalDateTime.of(startYear, startMonth, startDay, 0, 0);
}
catch(DateTimeException e)
{
txtTransactions.setText("INVALID DATE");
return;
}
}
else
{
startTime = null;
}
if(chckbxEndDate.isSelected())
{
int endMonth = Month.valueOf(endMonthName.toUpperCase()).getValue();
try
{
endTime = LocalDateTime.of(endYear, endMonth, endDay, 23, 59);
}
catch(DateTimeException e)
{
txtTransactions.setText("INVALID DATE");
return;
}
}
else
{
endTime = null;
}
ArrayList<Transaction> transactionList = account.getTransactions(startTime, endTime);
String output = "";
int maxAmountDigits = 1;
for(Transaction t : transactionList)
{
String stringAmount = String.format("%.2f", t.getAmount());
if(stringAmount.length() > maxAmountDigits)
maxAmountDigits = stringAmount.length();
}
output += String.format("%-10s %-8s %-" + (maxAmountDigits + 1) + "s %s\n", "Date", "Time", "Amount", "Description");
//https://stackoverflow.com/questions/37791455/java-string-format-adding-spaces-to-integers
output += String.format("%0" + 100 + "d\n", 0).replace("0", "-");
for(Transaction t : transactionList)
{
output += String.format("%d.%02d.%02d %02d:%02d:%02d $%-" + maxAmountDigits + ".2f %s\n", t.getTransactionTime().getYear(),
t.getTransactionTime().getMonthValue(),
t.getTransactionTime().getDayOfMonth(),
t.getTransactionTime().getHour(),
t.getTransactionTime().getMinute(),
t.getTransactionTime().getSecond(),
t.getAmount(),
t.getDescription());
}
txtTransactions.setText(output);
}
}
contentPanel.setLayout(null);
First you set the layout to null:
JScrollPane txtTScrollPane = new JScrollPane(txtTransactions);
contentPanel.add(txtTScrollPane);
//contentPanel.revalidate();
//contentPanel.repaint();
Then you add the scrollpane to the content panel. However, you didn't use setBounds() on the scrollpane and the default size of a component is (0, 0) so there is nothing to paint.
However, the solution is not to add the setBounds(...). The solution is to not use a null layout. It may seem easier with a null layout but then you get into problems like this and components don't work properly when used in a scrollpane.
So the proper solution is to fix your code and use Layout Managers. Swing was designed to be used with layout managers. Then the layout manager will set the size and location of the component so you don't have to worry about it.
The revalidate() and repaint() is only used when adding components to a visible GUI to invoke the layout manager so they are not needed.
Also when creating the text area do something like:
//txtTransactions = new JTextArea();
txtTransactions = new JTextArea(5, 20);
This will let the text area determine its own preferred size based on the rows/columns and font of the text area. Then the layout manager can do a better job.
Related
Am struggling to get it working, have three tables trying to get all column values from all JTable(s) (Three tables) by clicking button "Read All Values".
When I use Vector data = tableModel.getDataVector();, returns only all columns values of the last table initiated.
Please give me directions, Thanks.
CODE:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
public class readAllJTableItem {
private JFrame frame;
private static JTextArea textAreaSD;
private static JTextArea textAreaPI;
private static JTextArea textAreaVL;
private TitledBorder textAreaTitleBorder = new TitledBorder(new EtchedBorder(), "Item(s)");
private static JCheckBox checkBoxTypeOne;
private static JCheckBox checkBoxTypeTwo;
private static JCheckBox checkBoxTypeThree;
//Table items
private JScrollPane scrollTableSD;
private JScrollPane scrollTablePI;
private JScrollPane scrollTableVL;
private JTable itemsTableSD;
private JTable itemsTablePI;
private JTable itemsTableVL;
private DefaultTableModel tableModel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
readAllJTableItem window = new readAllJTableItem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public readAllJTableItem() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 872, 587);
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ArrayList<String> addItems = new ArrayList<String>();
final int stedCntLpt_1[] = {0,1,2,3,4,5,6,7,8,9,10,11}; //total = 12
final int stedCntLpt_2[] = {0,1,2,3,4,5,6,7,8,9,10,12,13}; //total = 13
final int stedCntLpt_3[] = {0,1,3,7,14,15,16,17}; //total = 8
//Type-1 (0-11)
addItems.add(0, "Column-01"); addItems.add(1, "Column-02"); addItems.add(2, "Column-03"); addItems.add(3, "Column-04");
addItems.add(4, "Column-05"); addItems.add(5, "Column-06"); addItems.add(6, "Column-07"); addItems.add(7, "Column-08");
addItems.add(8, "Column-09"); addItems.add(9, "Column-10"); addItems.add(10, "Column-11"); addItems.add(11, "Column-12");
addItems.add(12, "Column-13"); addItems.add(13, "Column-14");
addItems.add(14, "Column-15"); addItems.add(15, "Column-16"); addItems.add(16, "Column-17"); addItems.add(17, "Column-18");
//1
JButton btnNewButton_1 = new JButton("Read All Values");
btnNewButton_1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//if (checkBoxTypeOne.isSelected() == true){
//This is were you get the cell values of each JTable
//#camickr's code...
DefaultTableModel model1 = (DefaultTableModel)itemsTableSD.getModel();
Vector data1 = model1.getDataVector();
System.out.println(data1.toString());
//}
}
});
btnNewButton_1.setBounds(281, 487, 125, 23);
frame.getContentPane().add(btnNewButton_1);
checkBoxTypeOne = new JCheckBox("SD");
checkBoxTypeOne.setBounds(685, 196, 87, 23);
frame.getContentPane().add(checkBoxTypeOne);
checkBoxTypeOne.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
callRenderTable(textAreaSD, scrollTableSD, itemsTableSD, addItems, stedCntLpt_1, 3, 12);
} else {
textAreaSD.setVisible(true);
scrollTableSD.setVisible(false);
};
}
});
checkBoxTypeTwo = new JCheckBox("PI");
checkBoxTypeTwo.setBounds(682, 288, 44, 23);
frame.getContentPane().add(checkBoxTypeTwo);
checkBoxTypeTwo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
callRenderTable(textAreaPI, scrollTablePI, itemsTablePI, addItems, stedCntLpt_2, 4, 13);
} else {
textAreaPI.setVisible(true);
scrollTablePI.setVisible(false);
};
}
});
checkBoxTypeThree = new JCheckBox("VL");
checkBoxTypeThree.setBounds(685, 374, 55, 23);
frame.getContentPane().add(checkBoxTypeThree);
checkBoxTypeThree.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
callRenderTable(textAreaVL, scrollTableVL, itemsTableVL, addItems, stedCntLpt_3, 2, 8);
} else {
textAreaVL.setVisible(true);
scrollTableVL.setVisible(false);
};
}
});
textAreaSD = new JTextArea();
textAreaSD.setBounds(43, 166, 608, 87);
textAreaSD.setBorder(textAreaTitleBorder);
textAreaSD.setBackground(new Color(240,240,240));
textAreaSD.setEditable(false);
textAreaSD.setVisible(true);
frame.getContentPane().add(textAreaSD);
scrollTableSD = new JScrollPane();
scrollTableSD.setBounds(43, 166, 608, 87);
scrollTableSD.setVisible(false);
frame.getContentPane().add(scrollTableSD);
textAreaPI = new JTextArea();
textAreaPI.setBounds(43, 256, 608, 103);
textAreaPI.setBorder(textAreaTitleBorder);
textAreaPI.setBackground(new Color(240,240,240));
textAreaPI.setEditable(false);
textAreaPI.setVisible(true);
frame.getContentPane().add(textAreaPI);
scrollTablePI = new JScrollPane();
scrollTablePI.setBounds(43, 256, 608, 103);
scrollTablePI.setVisible(false);
frame.getContentPane().add(scrollTablePI);
textAreaVL = new JTextArea();
textAreaVL.setBounds(43, 362, 608, 71);
textAreaVL.setBorder(textAreaTitleBorder);
textAreaVL.setBackground(new Color(240,240,240));
textAreaVL.setEditable(false);
textAreaVL.setVisible(true);
frame.getContentPane().add(textAreaVL);
scrollTableVL = new JScrollPane();
scrollTableVL.setBounds(43, 362, 608, 71);
scrollTableVL.setVisible(false);
frame.getContentPane().add(scrollTableVL);
itemsTableSD = new JTable();
scrollTableSD.setViewportView(itemsTableSD);
itemsTablePI = new JTable();
scrollTablePI.setViewportView(itemsTablePI);
itemsTableVL = new JTable();
scrollTableVL.setViewportView(itemsTableVL);
}
private void callRenderTable(JTextArea textArea, JScrollPane scrollTable, JTable itemsTable, ArrayList<String> addItems, int itemIndexNo[], int loopCount, int totCount){
textArea.setVisible(false);
scrollTable.setVisible(true);
//DefaultTableModel tableModel = new DefaultTableModel(){
tableModel = new DefaultTableModel(){
public Class<?> getColumnClass(int column){
switch(column){
case 0:
return String.class;
case 1:
return Boolean.class;
case 2:
return String.class;
case 3:
return Boolean.class;
case 4:
return String.class;
case 5:
return Boolean.class;
default:
return String.class;
}
}
int row = 0;
int column = 1;
boolean[] canEdit = new boolean[]{false, true, false, true, false, true};
#Override
public boolean isCellEditable(int row, int column) {
if (row == 0 && column == 1){
return false;}
return canEdit[column];
}
};
//Assign the model to table
itemsTable.setModel(tableModel);
tableModel.addColumn("Items");
tableModel.addColumn("Select");
tableModel.addColumn("Items");
tableModel.addColumn("Select");
tableModel.addColumn("Items");
tableModel.addColumn("Select");
//The row
int indIncr = 0;
for(int i = 0; i <= loopCount; i++){
tableModel.addRow(new Object[0]);
for(int j = 0; j <= 2; j++){
if (j == 0 && indIncr < totCount){
tableModel.setValueAt(addItems.get(itemIndexNo[indIncr]), i, j);
tableModel.setValueAt(true, i, j+1);
indIncr = indIncr + 1;}
if (j == 1 && indIncr < totCount ){
tableModel.setValueAt(addItems.get(itemIndexNo[indIncr]), i, j+1);
tableModel.setValueAt(true, i, j+2);
indIncr = indIncr + 1;}
if (j == 2 && indIncr < totCount){
tableModel.setValueAt(addItems.get(itemIndexNo[indIncr]), i, j+2);
tableModel.setValueAt(true, i, j+3);
indIncr = indIncr + 1;}
}
}
}
}
You only have one variable "tableModel" so how do you expect that variable to reference 3 table models?
You have 3 variables to reference each of your 3 tables.
So you need code like:
DefaultTableModel model1 = (DefaultTableModel)itsTableSD.getModel();
DefaultTableModel model2 = (DefaultTableModel)itsTablePI.getModel();
DefaultTableModel model3 = (DefaultTableModel)itsTableVL.getModel();
Now you can use the getDataVector() method on each of the table models.
Also, get rid of your static variables. In general variables should not be static.
I'm trying to make a program that load 4 images, put it in 4 labels and change the icons of each label in the frame regarding the random number in the list, like if it was blinking the images. It need to blink each image in the order that is sorted in comecaJogo() but when I press the btnComecar in the actionPerformed all imagens seems to change at the same time:
Here is my logic class:
public class Logica {
List<Integer> seqAlea = new ArrayList<Integer>();
List<Integer> seqInsere = new ArrayList<Integer>();
int placar = 0;
boolean cabouGame = false;
Random geraNumero = new Random();
int numero;
Timer timer = new Timer(1500,null);
public void comecaJogo() {
for (int i = 0; i < 4; i++) {
numero = geraNumero.nextInt(4) + 1;
seqAlea.add(numero);
}
}
public void piscaImagen(ImageIcon img1, ImageIcon img1b, JLabel lbl) {
timer.addActionListener(new ActionListener() {
int count = 0;
#Override
public void actionPerformed(ActionEvent evt) {
if(lbl.getIcon() != img1){
lbl.setIcon(img1);
} else {
lbl.setIcon(img1b);
}
count++;
if(count == 2){
((Timer)evt.getSource()).stop();
}
}
});
timer.setInitialDelay(1250);
timer.start();
}
}
In the frame:
public class Main extends JFrame implements ActionListener {
JLabel lblImg1 = new JLabel();
JButton btnImg1 = new JButton("Economize Energia");
final URL resource1 = getClass().getResource("/br/unip/IMGs/img1.jpg");
final URL resource1b = getClass().getResource("/br/unip/IMGs/img1_b.png");
ImageIcon img1 = new ImageIcon(resource1);
ImageIcon img1b = new ImageIcon(resource1b);
JButton btnImg2 = new JButton("Preserve o Meio Ambiente");
JLabel lblImg2 = new JLabel("");
final URL resource2 = getClass().getResource("/br/unip/IMGs/img2.jpg");
final URL resource2b = getClass().getResource("/br/unip/IMGs/img2_b.jpg");
ImageIcon img2 = new ImageIcon(resource2);
ImageIcon img2b = new ImageIcon(resource2b);
JButton btnImg3 = new JButton("N\u00E3o \u00E0 polui\u00E7\u00E3o!");
JLabel lblImg3 = new JLabel("");
final URL resource3 = getClass().getResource("/br/unip/IMGs/img3.jpg");
final URL resource3b = getClass().getResource("/br/unip/IMGs/img3_b.jpg");
ImageIcon img3 = new ImageIcon(resource3);
ImageIcon img3b = new ImageIcon(resource3b);
JButton btnImg4 = new JButton("Recicle!");
JLabel lblImg4 = new JLabel("");
final URL resource4 = getClass().getResource("/br/unip/IMGs/img4.jpg");
final URL resource4b = getClass().getResource("/br/unip/IMGs/img4_b.jpg");
ImageIcon img4 = new ImageIcon(resource4);
ImageIcon img4b = new ImageIcon(resource4b);
Logica jogo = new Logica();
JButton btnComecar = new JButton("Come\u00E7ar");
public static void main(String[] args) {
Main window = new Main();
window.setVisible(true);
}
public Main() {
lblImg1.setIcon(img1b);
lblImg1.setBounds(78, 48, 250, 200);
add(lblImg1);
btnImg1.setBounds(153, 259, 89, 23);
btnImg1.addActionListener(this);
add(btnImg1);
setBounds(100, 100, 800, 600);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnImg2.setBounds(456, 272, 186, 23);
btnImg2.addActionListener(this);
lblImg2.setIcon(img2b);
lblImg2.setBounds(421, 61, 250, 200);
add(btnImg2);
add(lblImg2);
btnImg3.setBounds(114, 525, 186, 23);
btnImg3.addActionListener(this);
lblImg3.setIcon(img3b);
lblImg3.setBounds(78, 314, 250, 200);
add(lblImg3);
add(btnImg3);
btnImg4.setBounds(456, 525, 186, 23);
btnImg4.addActionListener(this);
lblImg4.setIcon(img4b);
lblImg4.setBounds(421, 314, 250, 200);
add(lblImg4);
add(btnImg4);
btnComecar.setBounds(68, 14, 89, 23);
btnComecar.addActionListener(this);
add(btnComecar);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(btnImg1)) {
jogo.piscaImagen(img1, img1b, lblImg1);
} else if (e.getSource().equals(btnComecar)) {
jogo.comecaJogo();
System.out.println(jogo.seqAlea);
for (int i = 0; i < jogo.seqAlea.size(); i++) {
switch (jogo.seqAlea.get(i)) {
case 1:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img1, img1b, lblImg1);
break;
case 2:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img2, img2b, lblImg2);
break;
case 3:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img3, img3b, lblImg3);
break;
case 4:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img4, img4b, lblImg4);
break;
}
}
}
}
}
Thanks for the help!
one at time, like a memory game :)
There are multitudes of ways this might work, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements ActionListener {
JButton btnImg1 = new JButton();
JButton btnImg2 = new JButton();
JButton btnImg3 = new JButton();
JButton btnImg4 = new JButton();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new Main();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public Main() {
JPanel buttons = new JPanel(new GridLayout(2, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
buttons.add(btnImg1);
buttons.add(btnImg2);
buttons.add(btnImg3);
buttons.add(btnImg4);
add(buttons);
JButton play = new JButton("Play");
add(play, BorderLayout.SOUTH);
play.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
List<JButton> sequence = new ArrayList<>(Arrays.asList(new JButton[]{btnImg1, btnImg2, btnImg3, btnImg4}));
Collections.shuffle(sequence);
Timer timer = new Timer(1000, new ActionListener() {
private JButton last;
#Override
public void actionPerformed(ActionEvent e) {
if (last != null) {
last.setBackground(null);
}
if (!sequence.isEmpty()) {
JButton btn = sequence.remove(0);
btn.setBackground(Color.RED);
last = btn;
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setInitialDelay(0);
timer.start();
}
}
This just places all the buttons into a List, shuffles the list and then the Timer removes the first button from the List until all the buttons have been "flashed".
Now this is just using the button's backgroundColor, so you'd need to create a class which allows you to associate the JButton with "on" and "off" images, these would then be added to the List and the Timer executed in a similar manner as above
Hello I have to finish a project but I can't get further. The project is about having jlabels with icons generated dynamically on two sides (left and right) .
The icons are in different order on each side and there is a one to one icon relationship.
As an example one picture : link
Now you can draw lines from the left to the right between those pictures and after clicking on the check button it should tell you if its true or false :
Again one picture : link
My question is how can I compare the icons to know which combination is the right one and after comparing the drawings?
I already created two lists to know the component combination of the drawings.
Here is the code so far -
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class CatSameCoins{
public static JLabel label;
public ActionListener btn1Listener;
public ActionListener btn2Listener;
public ActionListener btn3Listener;
public ActionListener btn4Listener;
public ActionListener btn5Listener;
public ActionListener btn6Listener;
public JButton btn1;
public JButton btn2;
public JButton btn3;
public JButton btn4;
public JButton btn5;
public JButton btn6;
public JButton btnCheck;
public ArrayList<String> listto = new ArrayList<String>();
public ArrayList<String> listfrom = new ArrayList<String>();
public static boolean drawing = false;
public static List<Shape> shapes = new ArrayList<Shape> ();
public static Shape currentShape = null;
static Component fromComponent;
private JLabel lblCheck;
public void drawLine(Component from , Component to){
listfrom.add(from.getName()); //first list with component names from where the drawing start
listto.add(to.getName()); //second list with component names where the drawing ends
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX()+from.getWidth()/2; //get middle
fromPoint.y = from.getY()+from.getHeight()/2; //get middle
toPoint.x = to.getX()+to.getWidth()/2;
toPoint.y = to.getY()+to.getHeight()/2;
currentShape = new Line2D.Double (fromPoint, toPoint);
shapes.add (currentShape);
label.repaint();
drawing = false;
}
public CatSameCoins(){
JFrame frame = new JFrame ();
frame.getContentPane().setLayout(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
listfrom.removeAll(listfrom);
drawing= false;
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("btn1");
btn1.setBounds(21, 88, 45, 97);
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
btn1.removeActionListener(this);
}
};
btn1.addActionListener(btn1Listener);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("btn2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
btn2.removeActionListener(this);
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("btn3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
btn3.removeActionListener(this);
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("btn4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn4);
drawing = false;
btn4.removeActionListener(this);
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("btn5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn5);
drawing = false;
btn5.removeActionListener(this);
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("btn6");
btn6.setBounds(407, 307, 45, 91);
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn6);
drawing = false;
btn6.removeActionListener(this);
}
}
};
btn6.addActionListener(btn6Listener);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0;i< listfrom.size();i++){
System.out.println(listfrom.get(i)+" - "+listto.get(i));
}
lblCheck.setText("False");
//if().... lblCheck.setText("True")
//else lblCheck.setText("False")
/*if(btn6.getIcon().toString().equals(btn1.getIcon().toString())){
System.out.println("yes");
}
else{
System.out.println("neah");
}*/
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel (){
protected void paintComponent ( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
g2d.setPaint ( Color.black);
g2d.setStroke(new BasicStroke(5));
for ( Shape shape : shapes )
{
g2d.draw ( shape );
repaint();
}
}
} ;
label.setSize(500,500);
frame.getContentPane().add (label);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize ( 500, 500 );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
public static void main ( String[] args )
{
new CatSameCoins();
}
}
Would really appreciate for any help ;) .
Its done,
Solution : you can try it just change icon names for the second hashmap
I know this is not the best solution but at least i tried. I will try to improve it.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class Hashmap {
private JLabel label;
private ActionListener btn1Listener;
private ActionListener btn2Listener;
private ActionListener btn3Listener;
private ActionListener btn4Listener;
private ActionListener btn5Listener;
private ActionListener btn6Listener;
private JButton btn1;
private JButton btn2;
private JButton btn3;
private JButton btn4;
private JButton btn5;
private JButton btn6;
private JButton btnCheck;
private JButton btnNext;
private boolean drawing = false;
private Shape currentShape = null;
private Component fromComponent;
private JLabel lblCheck;
private List<Shape> shapes = new ArrayList<Shape>();
private HashMap<String, String> userLines = new HashMap<String, String>();
private HashMap<String, String> resultLines = new HashMap<String, String>();
private HashMap<String, String> icons = new HashMap<String, String>();
public void drawLine(Component from, Component to) {
userLines.put(from.getName(), to.getName());
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX() + from.getWidth() / 2; // get middle
fromPoint.y = from.getY() + from.getHeight() / 2; // get middle
toPoint.x = to.getX() + to.getWidth() / 2;
toPoint.y = to.getY() + to.getHeight() / 2;
currentShape = new Line2D.Double(fromPoint, toPoint);
shapes.add(currentShape);
label.repaint();
drawing = false;
}
#SuppressWarnings("serial")
public Hashmap() {
loadIcons();
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
drawing = false;
userLines.clear();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("1");
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
}
};
btn1.addActionListener(btn1Listener);
btn1.setBounds(21, 88, 45, 97);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn4);
drawing = false;
btn4.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn5);
drawing = false;
btn5.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("6");
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn6);
drawing = false;
btn6.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn6.addActionListener(btn6Listener);
btn6.setBounds(407, 307, 45, 91);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (resultLines.equals(userLines) && !userLines.isEmpty()) {
lblCheck.setText("true");
} else {
lblCheck.setText("false");
}
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
btnNext = new JButton("next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userLines.clear();
resultLines.clear();
shapes.removeAll(shapes);
drawing = false;
changeCombination();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
btnNext.setBounds(335, 435, 117, 25);
frame.getContentPane().add(btnNext);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.black);
g2d.setStroke(new BasicStroke(3));
for (Shape shape : shapes) {
g2d.draw(shape);
repaint();
}
}
};
label.setSize(frame.getWidth(), frame.getHeight());
frame.getContentPane().add(label);
frame.setVisible(true);
}
private void loadIcons() {
icons.clear();
icons.put("money/coin2/1_Cent.png", "money/coin2/1_Cent.png");
icons.put("money/coin2/5_Cent.png", "money/coin2/5_Cent.png");
icons.put("money/coin2/10_Cent.png", "money/coin2/10_Cent.png");
icons.put("money/coin2/20_Cent.png", "money/coin2/20_Cent.png");
icons.put("money/coin2/50_Cent.png", "money/coin2/50_Cent.png");
icons.put("money/coin2/2_Euro.png", "money/coin2/2_Euro.png");
icons.put("money/coin2/1_Euro.png", "money/coin2/1_Euro.png");
}
public void changeCombination() {
Random randLeftSide = new Random();
Random randRightSide = new Random();
while (resultLines.size() < 3) {
int left = randLeftSide.nextInt(3 - 1 + 1) + 1;
int right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("leftside: "+left+"rightside: "+y);
while (resultLines.containsKey(String.valueOf(left))) {
if (resultLines.size() > 3) {
break;
} else {
left = randLeftSide.nextInt(3 - 1 + 1) + 1;
// System.out.println("leftside : "+left);
}
}
while (resultLines.containsValue(String.valueOf(right))) {
if (resultLines.size() > 3) {
break;
} else {
right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("rightside: "+right);
}
}
resultLines.put(String.valueOf(left), String.valueOf(right));
}
// System.out.println("TOTAL MAP: "+resultLines.toString());
changeImages();
}
private void changeImages() {
List<Integer> randomIcon = new ArrayList<Integer>(); //creating array list for the icon random numbers
List<Integer> randomLines = new ArrayList<Integer>(); //creating array list for the lines random numbers
for (int i = 0; i < resultLines.size(); i++) {
int randomIndexIcon = new Random().nextInt(icons.size()); //generate random number for the icons from the hashmap
while (randomIcon.contains(randomIndexIcon)) { //while the list contains the random number generate a new one to prevent printing same pictures
randomIndexIcon = new Random().nextInt(icons.size());
}
randomIcon.add(randomIndexIcon); //add to the array list of the icon random numbers the generated random number
int randomIndexResult = new Random().nextInt(resultLines.size()); //generate random number for the lines
while (randomLines.contains(randomIndexResult)) { //while for second list to prevent generating same numbers
randomIndexResult = new Random().nextInt(resultLines.size());
}
randomLines.add(randomIndexResult); //add to the array list of the lines random numbers the generated random number
Object iconValue = icons.values().toArray()[randomIndexIcon]; //this is to get the icon string
Object valueLeft = resultLines.keySet().toArray()[randomIndexResult]; //this is to get the random key value from the resultLines map (left side)
if (valueLeft.equals("1")) { //check conditions
btn1.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("2")) {
btn2.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("3")) {
btn3.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
Object valueRight = resultLines.values().toArray()[randomIndexResult]; //get the values from the hashmap (right side)
if (valueRight.equals("4")) { //check conditions
btn4.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("5")) {
btn5.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("6")) {
btn6.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
}
}
public static void main(String[] args) {
new Hashmap();
}
}
i have this code that i made and i`m having a problem with the program.
This program is a Word counter with a interface that i created.
It counts how many times i wrote in test.txt word "Vlad Enache" *(my name) . The problem is i don't know how can i make this to search for multiple words , let`s say Vlad Enache, and word dog and cat. And i wanna know how can i define these words from user input in another frame with fields.
Thanks:)
import java.awt.Color;
import java.awt.EventQueue;
import java.io.*;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.JTextArea;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class Andreea {
private JFrame frame;
private JTextField textField;
private JButton btnNewButton;
private JLabel lblNewLabel;
private JTextArea txtrVlad;
private JMenuBar menuBar_2;
private JMenu menu;
private JMenuItem menuItem;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Andreea window = new Andreea();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Read from file
* #throws IOException
*/
public int ReadFromFile() throws IOException{
BufferedReader br;
Scanner ob;
br = new BufferedReader(new FileReader("D:/test.txt"));
ob = new Scanner("PULA");
String str=ob.next();
String str1="",str2="";
int count=0;
while((str1=br.readLine())!=null)
{
str2 +=str1;
}
int index = str2.indexOf(str);
while (index != -1) {
count++;
str2 = str2.substring(index + 1);
index = str2.indexOf(str);
}
return count;
}
/**
* Create the application.
* #throws IOException
*/
public Andreea() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws IOException
*/
private void initialize() throws IOException {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.setBounds(100, 100, 497, 399);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBackground(new Color(255, 255, 255));
textField.setForeground(new Color(0, 204, 204));
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setEditable(false);
textField.setFont(new Font("Georgia", Font.BOLD | Font.ITALIC, 20));
textField.setBounds(129, 190, 223, 45);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnCount = new JButton("Count");
btnCount.setFont(new Font("Verdana", Font.BOLD | Font.ITALIC, 10));
btnCount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int count=0;
try {
count = ReadFromFile();
} catch (IOException e) {
e.printStackTrace();
}
String str="";
str += count;
textField.setText(str + " Times" );
}
});
btnCount.setBounds(60, 270, 130, 45);
frame.getContentPane().add(btnCount);
btnNewButton = new JButton("Reseteaza Counter");
btnNewButton.setFont(new Font("Verdana", Font.BOLD | Font.ITALIC, 10));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(null);
}
});
btnNewButton.setBounds(293, 267, 130, 45);
frame.getContentPane().add(btnNewButton);
lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("C:/...."));
lblNewLabel.setBounds(0, 0, 480, 179);
frame.getContentPane().add(lblNewLabel);
txtrVlad = new JTextArea();
txtrVlad.setText("\u00A9 2014 Vlad Enache (4594)");
txtrVlad.setBounds(310, 338, 204, 22);
frame.getContentPane().add(txtrVlad);
menuBar_2 = new JMenuBar();
frame.setJMenuBar(menuBar_2);
menu = new JMenu("New menu");
menuBar_2.add(menu);
menuItem = new JMenuItem("New menu item");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
menu.add(menuItem);
}
}
Here is one possible solution. Note that this code assume one token per line. You can go back to String.indexOf if it is not the case.
public int[] ReadFromFile(final String[] tokens) throws IOException
{
final int[] counters = new int[tokens.length];
BufferedReader br;
br = new BufferedReader(new FileReader("D:/test.txt"));
String str1 = "";
while ((str1 = br.readLine()) != null)
{
for (int i = 0; i < tokens.length; i++)
if (str1.contains(tokens[i]))//if the line contains the token
counters[i]++;// increase counter for the index of the token
}
return counters;
}
...
public void actionPerformed(ActionEvent arg0)
{
//final String[] tokens = new String[] { "Vlad Enache", "dog", "cat" };
final String[] tokens = textField.getText().split(", ");//get token directly from JTextfield.
// Would make more sense to use a different JtextField for input and output.
//This is just an example
try
{
int[] count;
count = ReadFromFile(tokens);
final StringBuilder sb = new StringBuilder();//storing the result in a stringbuilder
/* to display the utterance of each token
for (int i = 0; i < count.length; i++)
sb.append(tokens[i] + " is repeated " + count[i] + " times\n");
textField.setText(sb.toString());//displaying result
*/
//to sum up all count value
int sum = 0;
for(int c : count)
sum+=c;
textField.setText(sum+" times");
}
catch (IOException e)
{
e.printStackTrace();
}
}
final String[] tokens = textField.getText().split(", ");
i got this that get`s token directly from JTextfield.
let`s say i got textField_1 in another form that it is in another class. how to use final String[] tokens = textField_1.getText().split(", ");??????
The question is, I try to make second textfield (textFieldGen) to print out the exact result likes console. Currently, second textfield shows one string only.
This is my first coding on java GUI.
(extra info, I built it using Eclipse with WindowBuilder + GEF )
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.TextField;
import java.awt.Label;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class PassGenerator {
private JFrame frmPasswordGenerator;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PassGenerator window = new PassGenerator();
window.frmPasswordGenerator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PassGenerator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmPasswordGenerator = new JFrame();
frmPasswordGenerator.setTitle("Password Generator");
frmPasswordGenerator.setBounds(100, 100, 419, 229);
frmPasswordGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPasswordGenerator.getContentPane().setLayout(null);
final TextField textFieldGen = new TextField();
final TextField textFieldPass = new TextField();
textFieldPass.setBounds(74, 60, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldPass);
Label labelPass = new Label("Password Length:");
labelPass.setBounds(74, 33, 177, 21);
frmPasswordGenerator.getContentPane().add(labelPass);
Button genButton = new Button("Generate");
genButton.setBounds(262, 60, 86, 23);
frmPasswordGenerator.getContentPane().add(genButton);
// Add action listener to button
genButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
//System.out.println("You clicked the button");
String getTxt = textFieldPass.getText();
boolean y = true;
do{
try{
int c = Integer.parseInt(getTxt);
Random r = new Random();
String[] alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","w","x","y","z"};
int nc = 0-c;
int c2 = c/2;
int nc2 = 0-c2;
int ncm = (nc+1)/2;
if (c%2 == 0){
for(int x = nc2; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
}
else {
for(int x = ncm; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
y = false;
}
catch (NumberFormatException e1 ){
int messageType = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(null, "Please Enter Integer only", "Error!!", messageType);
y = false;
}
}while (y);
}
});
Label labelGen = new Label("Generated Password:");
labelGen.setBounds(74, 109, 149, 21);
frmPasswordGenerator.getContentPane().add(labelGen);
textFieldGen.setBounds(74, 136, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldGen);
Button copyButton = new Button("Copy");
copyButton.setBounds(262, 136, 86, 23);
frmPasswordGenerator.getContentPane().add(copyButton);
}
}
Use textFieldGen.setText (textFieldGen.getText () + "\n" + Integer.toString(numNum))
I don't see why you are setting the contents of the text field twice. I would just do:
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
//textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
//textFieldGen.setText(Integer.toString(numNum));
textFieldGen.setText(alpha + Integer.toString(numNum));
In general it is not a good practice to replace the entire text when all you want to do is append some characters to the text field. If you don't like the above then you can do:
textField.setText(alpha);
...
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), Integer.toString(numNum), null);
Edit:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
JTextField textField = new JTextField(20);
add( textField );
textField.setText( "testing: " );
try
{
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), "1", null);
}
catch(Exception e) {}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}