these are my code I've problem with label when i read line from the text filed i can add the labels "_" that they are equal to the size of the word the program road it before.
I've problem creating label , I hope you understand my problem & please if you can can you give me a solution ?
public class HangGame extends JFrame {
JLabel lbl;
JLabel word ;
private String[]myword = new String [20];
Game() {
}
void readfile () {
Properties prob = new Properties();
try{
for(int x=0; x<n; x++){
}
}}
private void initLabelPanel() {
//craete array of labels the size of the word
letterHolderPanel = new JPanel();
int count =0;
//if you run my code I've problem with this array [myword.length()] the compiler can not find it.
wordToFindLabels = new JLabel[myword.length()];
//Initiate each labels text add tp array and to letter holder panel
for (int i = 0; ih; i++) {JLabel lbl = new JLabel("_");
letterHolderPanel.add(lbl);
lbl.setBounds();
}
}
}
myword is an array of Strings, not a single String so you need to replace:
wordToFindLabels = new JLabel[myword.length()];
with
wordToFindLabels = new JLabel[myword.length];
You could rename the variable to, say, mywordArray, to avoid confusion.
Also use a layout manager rather than using absolute positioning(null layout).
See: Doing Without a Layout Manager (Absolute Positioning)
length is property not method change the code accordingly
wordToFindLabels = new JLabel[myword.length];
and now youre code will be
for (int i = 0; i < wordToFindLabels.length; i++) {
String labelValue="";
if(myword[i] != null) {
for (int j = 0; j < myword[i].length(); j++){
labelValue+="_"
}
}
JLabel lbl = new JLabel(labelValue);
wordToFindLabels[i] = lbl;
letterHolderPanel.add(lbl);
lbl.setBounds(30, 60, 20, 20);
}
Related
I want to make ToDoList App. After successfully adding task to do (which contains checkbox, JLabel and date, all putted in a box) i want to remove them dynamically. With adding it's not problem but when i try to remove (ater clicking checked in checkbox) it works only once. Then it either removes not once which are intended or not removing them at all. I am not sure why it's not working so I paste all code below.
JSpinner dateSpin;
Box eventBox, boxBox;
Box[] taskBox = new Box[1000];
JTextField eventName;
Date date;
Checkbox[] doneCheck = new Checkbox[1000];
JLabel taskLabel;
JPanel panel;
JScrollPane scrollPane;
SimpleDateFormat simpleDate;
int i = 0;
public static void main(String[] args) {
new Main();
}
private Main(){
this.setSize(400, 600);
this.setTitle("To-Do List");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
boxBox = Box.createVerticalBox();
scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
eventBox = Box.createHorizontalBox();
eventBox.setBorder(BorderFactory.createEtchedBorder());
JLabel plusSign = new JLabel("+");
plusSign.setFont(new Font("Serafi", PLAIN, 20));
plusSign.setMaximumSize(new Dimension(Integer.MAX_VALUE, plusSign.getMinimumSize().height));
eventBox.add(plusSign);
eventName = new JTextField(20);
eventName.setFont(new Font("Times", Font.ITALIC, 15));
eventName.setMaximumSize(new Dimension(Integer.MAX_VALUE, eventName.getMinimumSize().height));
eventName.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == eventName){
/* to do: saving every task in some file, figure out how to remove
those tasks (checkbox + jlabel) -> whole box from screen or how to send them to "done"
also "done" to do*/
simpleDate = new SimpleDateFormat("E-dd-MM-yyyy");
taskBox[i] = Box.createHorizontalBox();
taskBox[i].setBorder(BorderFactory.createTitledBorder(simpleDate.format(date)));
doneCheck[i] = new Checkbox();
doneCheck[i].addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
int k = 0;
for (int j = 0; j < doneCheck.length; j++) {
if(doneCheck[j].getState()){
//remove(doneCheck[k]);
//System.out.println("?" + i + "?" + k + " " + e.getSource().toString());
System.out.println("xxxxx" + doneCheck[j].getState());
break;
}
System.out.println("oooooo");
k++;
}
System.out.println(doneCheck.length + taskBox[k].toString());
//System.out.println("! " + k + " " + e.getSource().toString());
boxBox.remove(taskBox[k]);
//boxBox.removeAll();
boxBox.revalidate();
boxBox.repaint();
}
});
taskBox[i].add(doneCheck[i]);
String taskName = eventName.getText();
taskLabel = new JLabel(taskName);
taskLabel.setMinimumSize(new Dimension(500,10));
taskLabel.setPreferredSize(new Dimension(300, 10));
taskBox[i].add(taskLabel);
boxBox.add(taskBox[i]);
boxBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, boxBox.getMinimumSize().height + 11));
panel.add(boxBox);
panel.revalidate();
panel.repaint();
i++;
}
}
});
eventBox.add(eventName);
date = new Date();
dateSpin = new JSpinner(new SpinnerDateModel(date, null, null, Calendar.DAY_OF_MONTH));
JSpinner.DateEditor dateEditor = new JSpinner.DateEditor(dateSpin, "dd/MM/yy");
dateSpin.setEditor(dateEditor);
dateSpin.setMaximumSize(new Dimension(Integer.MAX_VALUE, dateSpin.getMinimumSize().height));
dateSpin.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if(e.getSource() == dateSpin){
date = (Date) dateSpin.getValue();
}
}
});
eventBox.add(dateSpin);
panel.add(eventBox, new FlowLayout());
this.add(scrollPane);
this.setVisible(true);
}
You never remove elements from the taskBox and doneCheck arrays.
Now if you mark the first entry as done, your ItemListener will always find this first entry when looping over the doneCheck array.
Marking the entries as done in reverse order (always the last shown entry) will remove one entry after the other.
As to your software design: it's considered bad practice to manage your data in several parallel arrays.
Please consider creating a custom class for the todo items that manages all the elements of a single todo item.
Unless you are initializing doneCheck items somewhere, this:
Checkbox[] doneCheck = new Checkbox[1000];
And this:
int k = 0;
for (int j = 0; j < doneCheck.length; j++) {
if (doneCheck[j].getState()) {
--------^^^^^^^^^^^^
Is probably one the reason it fails: you probably got a NullPointerException somewhere, eg: when value of j > 0. The NPE will probably be catched by the EventDispatchThread which may or may not be kind enough to show it on stderr...
I fail to see why you are using this array, and you can shorten your code and avoid NPE like this:
Checkbox cb = new Checkbox();
cb.addItemListener(event -> {
if (cb.getState()) { // not null!
boxBox.remove(cb);
boxBox.revalidate();
boxBox.repaint();
}
});
doneCheck[i] = cb; // I still don't know why you need that.
My guess is that you have 2 variables global int i = 0 and local int k = 0 in here
public void itemStateChanged(ItemEvent e) {
// int k = 0;//<-------- LOCAL
for (int j = 0; j < doneCheck.length; j++) {
if(doneCheck[j].getState()){
//Either k = j;
boxBox.remove(taskBox[j]);
//remove(doneCheck[k]);
//System.out.println("?" + i + "?" + k + " " + e.getSource().toString());
System.out.println("xxxxx" + doneCheck[j].getState());
break;
}
System.out.println("oooooo");
//k++;//<-- ALWAYS == last j value before the break;
}
System.out.println(doneCheck.length + taskBox[k].toString());
//System.out.println("! " + k + " " + e.getSource().toString());
//boxBox.remove(taskBox[k]);//
//boxBox.removeAll();
boxBox.revalidate();
boxBox.repaint();
}
Every time you call for itemStateChanged int k = 0; will be initialized to 0 and you will be removing element[j] from array of taskBox. As you k++ statement will be equal to the last j value before the break; because it sits after the if(doneCheck[j].getState()){...
Try moving boxBox.remove(taskBox[j]); inside the for loop and using j instead of k.
Hey guys I'm very new to Java and started in July with an intro to Java class.
I am currently working on a project which is a translator with arrays. The main applet shows 10 words in english that when typed into a JTextField outputs the spanish translation of that work. And vice versa. The program also shows a picture associated with that word.
The program is all done in that case, the only portion I am missing currently is that if a user inputs ANY other word than the 20 given words (10 spanish and 10 english) the JTextArea where translations are displayed is supposed to show "That word is not in the dictionary".
I'm having issues creating an ELSE statement that shows this error message. Here is the complete code. I'm not sure what to do to make it so eg
if (textFieldWord.!equals(englishWords[english])){
translate.setText("That word is not in the Dictionary");}
Here is the complete code - - - -
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class DictionaryArrays extends JApplet implements ActionListener{
String[] spanishWords = {"biblioteca","reloj",
"alarma", "volcan", "ventana",
"autobus", "raton", "lago", "vaca", "encendedor"};
String[] englishWords = {"library", "clock", "alarm",
"volcano", "window", "bus", "rat",
"lake","cow","lighter"};
String textFieldWord;
Image[] photos;
ImageIcon icon;
ImageIcon icontwo;
JButton getTranslation;
JTextField entry;
JLabel imageviewer;
TextArea translate;
static int defaultX = 10;
static int defaultY = 10;
static int defaultW = 780;
static int defaultH = 50;
public void init() {
photos = new Image[10];
photos[0] = getImage(getCodeBase(), "library.jpg");
photos[1] = getImage(getCodeBase(), "clock.jpg");
photos[2] = getImage(getCodeBase(), "alarm.jpg");
photos[3] = getImage(getCodeBase(), "volcano.jpg");
photos[4] = getImage(getCodeBase(), "window.jpg");
photos[5] = getImage(getCodeBase(), "bus.jpg");
photos[6] = getImage(getCodeBase(), "rat.jpg");
photos[7] = getImage(getCodeBase(), "lake.jpg");
photos[8] = getImage(getCodeBase(), "cow.jpg");
photos[9] = getImage(getCodeBase(), "lighter.jpg");
final JPanel outer = new JPanel(new BorderLayout());
JPanel inner = new JPanel(new BorderLayout());
JPanel viewer = new JPanel(new BorderLayout());
JPanel visualviewer = new JPanel(new BorderLayout());
// here is the main component we want to see
// when the outer panel is added to the null layout
//JButton toSpanish = new JButton("English to Spanish");
//JButton toEnglish = new JButton("Spanish to English");
final JLabel list = new JLabel("<HTML><FONT COLOR=RED>English</FONT> - library, clock, alarm, volcano, window, bus, rat, lake, cow, lighter"
+"<BR><FONT COLOR=RED>Spanish</FONT> - biblioteca, reloj, alarma, volcan, ventana, autobus, raton, lago, vaca, encendedor<BR>");
translate = new TextArea("Your translation will show here");
imageviewer = new JLabel(icon);
viewer.add("West",translate);
visualviewer.add("East",imageviewer);
inner.add("Center",list);
//inner.add("West",toSpanish);
//inner.add("East", toEnglish);
outer.add("Center", inner);
JPanel c = (JPanel)getContentPane();
final JPanel nullLayoutPanel = new JPanel();
nullLayoutPanel.setLayout(null);
c.add("Center", nullLayoutPanel);
// set the bounds of the panels manually
nullLayoutPanel.add(outer);
nullLayoutPanel.add(viewer);
nullLayoutPanel.add(visualviewer);
outer.setBounds(defaultX, defaultY, defaultW, defaultH);
viewer.setBounds(20, 75, 300, 300);
visualviewer.setBounds(485, 75, 300, 300);
JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
entry = new JTextField("Enter English or Spanish word to translate here");
entry.addActionListener(this);
entry.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
entry.setText("");
}});
getTranslation = new JButton("Translate");
getTranslation.addActionListener(this);
controlPanel.add(entry);
controlPanel.add(getTranslation);
c.add("South", controlPanel);
viewer.setBackground(Color.blue);
controlPanel.setBackground(Color.red);
inner.setBackground(Color.yellow);
visualviewer.setBackground(Color.black);
outer.setBackground(Color.black);
}
public void paint(Graphics g) {
super.paint(g);
}
public void actionPerformed (ActionEvent ae){
if(ae.getSource()==getTranslation){
textFieldWord=(entry.getText().toLowerCase());
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translate.setText(spanishWords[english]);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translate.setText(englishWords[spanish]);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
}
}
Any help would be appreciated guys. If the top paragraph was TLDR. Im trying to make it so typing in ANY other word in the JTextField (entry) other than the 10 english and 10 spanish words will output an error msg of "That word is not in the Dictionary" in the TextArea (translate)
This is (obviously) wrong...
if (textFieldWord.!equals(englishWords[english])){
and should be...
if (!textFieldWord.equals(englishWords[english])){
Try and think of it this way, String#equals returns a boolean, you want to invert the result of this method call, it would be the same as using something like...
boolean doesEqual = textFieldWord.equals(englishWords[english]);
if (!doesEqual) {...
You need to evaluate the result of the method call, but in oder to make that call, the syntax must be [object].[method], therefore, in order to invert the value, you must complete the method call first, then apply the modifier to it ... ! ([object].[method])
Updated...
Now having said all that, let's look at the problem from a different perspective...
You need to find a matching word, in order to do that, you must, at worse case, search the entire array. Until you've search the entire array, you don't know if a match exists.
This means we could use a separate if-else statement to manage the updating of the output, for example...
String translatedWord = null;
int foundIndex = -1;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = englishWords[english];
foundIndex = english;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icon= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icon);
} else {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[english];
foundIndex = spanish;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icontwo);
} else {
translate.setText("That word is not in the Dictionary");
}
Basically, all this does is sets the translatedWord to a non null value when it finds a match in either of the arrays. In this, you want to display the results, else you want to display the error message...
Equally, you could merge your current approach with the above, so when you find a work, you update the output, but also check the state of the translatedWord variable, displaying the error message if it is null...
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = spanishWords[english];
translate.setText(translatedWord);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[spanish];
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
Updated
Okay, you have a logic problem. You're never quite sure which direction you are translating to.
The following basically changes the follow by not translating the work from Spanish IF it was translated to English
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == getTranslation) {
textFieldWord = (entry.getText().toLowerCase());
translate.setText(null);
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++) {
if (textFieldWord.equals(englishWords[english])) {
translatedWord = spanishWords[english];
translate.append(translatedWord + "\n");
icon = new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
for (int spanish = 0; spanish < englishWords.length; spanish++) {
if (textFieldWord.equals(spanishWords[spanish])) {
translatedWord = englishWords[spanish];
translate.append(translatedWord + "\n");
icontwo = new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
if (translatedWord == null) {
translate.append("A Spanish-English match is not in the Dictionary\n");
}
}
}
Now, I would suggest that you replace TextArea with a JTextArea, but you will need to wrap it in a JScrollPane
translate = new JTextArea("Your translation will show here");
viewer.add("West", new JScrollPane(translate));
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Basically, this was really painful to try and use for this very reason...
I'm try to change the text on a JLabel when the Jbutton is clicked but i can't figure it out why it turns the text into empty when i clicked the button. I'm trying to retrieve the data from the database.
heres my label
labelDisplay = new JLabel[7];
for(int z = 0; z<7; z++){
labelDisplay[z] = new JLabel("d");
labelDisplay[z].setForeground(new Color(230,230,230));
if( z%2==0)
labelDisplay[z].setBounds(130,65,160,25);
else
labelDisplay[z].setBounds(130,30,160,25);
}
I'm sure that my class for retrieving date is working i test it out.
heres my actionListener:
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == extendB)
{
ExtensionForm extend = new ExtensionForm();
extend.setVisible(true);
}
else if(e.getSource()== searchB)
{
//get text from the textField
String guest = guestIDTF.getText();
//parse the string to integer for retrieving of date
int id = Integer.parseInt(guest);
GuestsInfo guestInfo = new GuestsInfo(id);
Room roomInfo = new Room(id);
searchB.setText(""+id);
System.out.println(""+guestInfo.getFirstName());
labelDisplay[1].setText(""+id);
String labels[] = {guestInfo.getFirstName()+" "+guestInfo.getLastName(),
""+roomInfo.getRoomNo(),roomInfo.getRoomType(),guestInfo.getTime(),"11:00",
""+guestInfo.getDeposit(),"30"};
labels = new String[7];
for(int z = 0; z<labels.length; z++){
labelDisplay[z].setText(labels[z]);
}
}
}
}
I did put an initial value for the label text, as you can see from my code it's letter "d" but when i clicked the button it turns to empty.The accessor methods there are really working that why i suspect that the error is from my actionListener. Please help me guys
I edit the constructor it should be id not 1.
Heres the code for the actionListener for the button
ButtonHandler bh = new ButtonHandler();
searchB = new JButton("search");
searchB.setBounds(190,30,75,25);
searchB.addActionListener(bh);
labelDisplay[1].setText(""+id);
String labels[] = {guestInfo.getFirstName()+" "+guestInfo.getLastName(),
""+roomInfo.getRoomNo(),roomInfo.getRoomType(), guestInfo.getTime(),
"11:00", ""+guestInfo.getDeposit(),"30"};
labels = new String[7];
for(int z = 0; z<labels.length; z++){
labelDisplay[z].setText(labels[z]);
}
You never set your labels to something valid. Remove labels = new String[7];
Should have checked the code well sorry!
So I have a small amount of objects (10 JLabels) and I want to change their text depending on the users input.
The Initializer for the labels goes like this:
private JLabel j1 = new JLabel();
private JLabel j2 = new JLabel();
private JLabel j3 = new JLabel();
...etc
and continues on to 10.
How do I mass change the text of each JLabel without writing each variable name every time?
I had an idea like below, but I don't know how to access the variable by name from strings.
for(int x=1;x<=10;x++){
String d = (String) x; //this isn't what d equals, it's example.
String label = "j"+x;
label.setText(d); //I know this won't work, but this is what I want to do
}
Is there any way this can be done without errors?
This is an excellent chance to use an array to store your JLabel objects:
private JLabel[] labels = new JLabel[10];
for (int i=0; i<10; i++) {
labels[i] = new JLabel();
}
/* ... */
for (int i=0; i<10; i++) {
labels[i].setText("Hello from label " + i);
}
If you have created the JLabel as an array like JLabel j[10] = new JLabel[10]. Then you can use the for loop to create an instance for each index and then set the text as well.
for(int x=0;x<10;x++){
j[x] = new JLabel();
String d = String.valueOf(x);
String label = "j"+x;
j[x].setText(d);
}
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class vasilisTable extends JFrame {
Object[] split_data_l;
Object[][] split_data;
Object [][] split_data_clone;
Object [][] split_data_reverse;
Object [][] split_data_reverse_num;
String[] temp;
private JTable table;
private JPanel bottom_panel;
private JLabel average;
private JLabel max_dr;
public vasilisTable(String name, String data, int choice)
{
super(name);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //the DISPOSE_ON_CLOSE means that when we press the x button is will close only the table window and not the whole programm
//this.getAccessibleContext().setAccessibleName(name);
//System.out.println(this.getAccessibleContext().getAccessibleName());
setSize(800,600);
String[] columnNames = {"Date", "Open","High","Low","Close",
"Volume", "Adjusted" };//defines the column names
//------ Start of making the arrays that will be used as data for the table creation
split_data_l = data.split( "\n" );
int lngth = split_data_l.length;
split_data = new Object[lngth-1][7];
split_data_clone = new Object[lngth-1][7];
split_data_reverse= new Object[lngth-1][7];
split_data_reverse_num= new Object[lngth-1][7];
double sum = 0;
for(int k=1; k<split_data_l.length; k++) //initializing the three arrays with the data we got from the URLReader
{
temp = split_data_l[k].toString().split(",");
for (int l=0; l<temp.length; l++)
{
split_data[k-1][l] = temp[l];
split_data_clone[k-1][l] = temp[l];
split_data_reverse[k-1][l] = temp[l];
split_data_reverse_num[k-1][l] = temp[l];
}
}
for(int k=split_data_l.length-2; k>=1; k--) // making of the clone array that contains all the last column with colours
{
Double temp = Double.parseDouble(split_data[k][6].toString());
Double temp1 = Double.parseDouble(split_data[k-1][6].toString());
double check =temp-temp1;
if (check>0)
{
String color_temp = "<html><span style = 'color:red'>" + split_data_clone[k-1][6] +"</span></html>" ;
split_data_clone[k-1][6] = color_temp;
}
else
{
String color_temp = "<html><span style = 'color:green'>" +split_data_clone[k-1][6]+"</span></html>" ;
split_data_clone[k-1][6] = color_temp;
}
}
int l = split_data_clone.length;
int m = l-1;
for (int i=0; i<l; i++) //making of the reversed array
{
for (int j = 0; j<=6; j++)
{
split_data_reverse[i][j]=split_data_clone[m][j];
}
m--;
}
m = l-1;
for (int i=0; i<l; i++) //making of the reversed array
{
for (int j = 0; j<=6; j++)
{
split_data_reverse_num[i][j]=split_data[m][j];
}
m--;
}
//------ End of making the arrays that will be used as data for the table creation
//------ Start of calculating the average
for (int i=0; i<lngth-1; i++)
{
Double temp = Double.parseDouble(split_data[i][6].toString());
sum = sum+temp;
//System.out.println("turn "+i+" = "+split_data[i][6]);
}
float avg = (float) (sum/(lngth-1));
avg = Round((float) avg,2);
String avg_str;
avg_str = "<html>Average: <b>"+avg+"</b></html>";
//"<html><b>Average: </b></html>"
//------ End of calculating the average
//------ Start of Calculating the Maximal Drawdown
double high=0;
double low=100000000;
double drawdown=0;
double max_drawdown=0;
int last_high=0;
int last_low=0;
for (int i=0; i<lngth-1; i++)
{
Double temp = Double.parseDouble(split_data_reverse_num[i][6].toString());
//Double temp1 = Double.parseDouble(split_data[i+1][6].toString());
if (temp>high)
{
high = temp;
last_high = i;
//System.out.println("max high = "+temp);
}
else
{
low = temp;
last_low = i;
//System.out.println("max low = "+temp);
}
if (last_low>last_high)
{
drawdown = high-low;
//System.out.println("drawdown = "+drawdown);
}
if (drawdown>max_drawdown)
{
max_drawdown = drawdown;
}
}
//System.out.println("max dr = "+max_drawdown);
String max_dr_str = "<html>Maximal Drawdown: <b>"+max_drawdown+"</b></html>";
//------ End of Calculating the Maximal Drawdown
average = new JLabel(avg_str);
max_dr = new JLabel(max_dr_str);
bottom_panel = new JPanel();
String space = " ";
JLabel space_lbl = new JLabel(space);
bottom_panel.add(average);
bottom_panel.add(space_lbl);
bottom_panel.add(max_dr);
//-------- Start of table creation ---------
if(choice==1)
{
table = new JTable(split_data_clone, columnNames);//creates an instance of the table with chronological order
}else
{
table = new JTable(split_data_reverse, columnNames);//creates an instance of the table with reverse chronological order
}
TableColumn column = null;
for (int i = 0; i < 7; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 0) {
column.setPreferredWidth(100); //third column is bigger
} else if (i == 5) {
column.setPreferredWidth(85); //third column is bigger
}
else if (i == 6) {
column.setPreferredWidth(70); //third column is bigger
}
else {
column.setPreferredWidth(50);
}
}
table.setShowGrid(true);
table.setGridColor(Color.black);
//-------- End of table creation ---------
JPanel table_panel = new JPanel (new BorderLayout());
JScrollPane table_container = new JScrollPane(table); // create a container where we will put the table
//table.setFillsViewportHeight(true); // if the information are not enough it still fill the rest of the screen with cells
table_panel.add(table_container, BorderLayout.CENTER);
table_panel.add(bottom_panel, BorderLayout.SOUTH);
//table_panel.add();
setContentPane (table_panel);
pack(); // here i pack the final result to decrease its dimensions
}
public float Round(float Rval, int Rpl) // this functions rounds the number to 2 decimal points
{
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
}
I am making an application which creates various instances of a class. These instances are actually some windows. After having create multiple of these windows, how can I access one of them and bring it in front? I know the .tofront() method, but how can I specify the window that I want to bring in front?
Above is the code that creates every window. My main problem is that after I have create e.g 5 windows, how can I access one of them?
ps
code that creates each window:
if (sData != null) {
//System.out.println("Success, waiting response");
vasilisTable ftable = new vasilisTable(name, sData, choice);
hashMap.put(name, ftable);
ftable.setVisible(true);
//choice=2;
}
My main problem is that after I have create e.g 5 windows, how can I access one of them?
You have to keep a reference to the relevant objects in variables or an array or a collection or something. The "bring it to the front" function needs to:
figure out what domain object needs to be brought to the front,
lookup its corresponding JFrame, and
call toFront() on it.
Java provides no built-in mechanisms for finding previously created instances of objects.
When you create your various instances of the above JFrame, you can keep track of the created instances, may be store them within a HashMap, then you can pick the right JFrame instance basing on its designated name and bring it to the front. Have a look at the below code for more illustration:
HashMap<String, VasilisTable> hashMap = new HashMap<String, VasilisTable>();
JFrame firstWindow = new VasilisTable("firstWindow",data, choice);
hashMap.put("firstWindow", firstWindow);
JFrame secondWindow = new VasilisTable("secondWindow",data, choice);
hashMap.put("secondWindow", secondWindow);
JFrame thirdWindow = new VasilisTable("thirdWindow",data, choice);
hashMap.put("thirdWindow", thirdWindow);
// To bring a certain window to the front
JFrame window = hashMap.get("firstWindow");
window.setVisible(true);
window.toFront();
Are these JFrame or JWindow objects? If they are you can call -
jframe.setVisible(true);
jframe.toFront();
This is something interesting I found at the API doc.
Places this Window at the top of the stacking order and shows it in
front of any other Windows in this VM. No action will take place if
this Window is not visible. Some platforms do not allow Windows which
own other Windows to appear on top of those owned Windows. Some
platforms may not permit this VM to place its Windows above windows of
native applications, or Windows of other VMs. This permission may
depend on whether a Window in this VM is already focused. Every
attempt will be made to move this Window as high as possible in the
stacking order; however, developers should not assume that this method
will move this Window above all other windows in every situation.
I would recommend you to check out these answers as well.
Java Swing: JWindow appears behind all other process windows, and will not disappear
Java: How can I bring a JFrame to the front?