Diskuze: Java Swing - Clicker
V předchozím kvízu, Online test znalostí Java, jsme si ověřili nabyté zkušenosti z kurzu.
Atrament:1.1.2016 18:40
No těžko radit bez ukázky jediného řádku kódu Jak vytváříš ten JDialog?
Atrament:1.1.2016 19:04
Aha takže tam máš třídu co dědí od JDialogu. Předpokládám, že v ní máš standardní konstruktor co bere jako parametry ten JFrame odkud ho voláš(parent) a boolean hodnotu jestli ten JDialog má být modální(modal). Když už máš tu instanci toho JFrame (parent) tak bys toho mohl využít. Udělej si ve třídě toho JFrame public metodu getLevel() vracející hodnotu té proměnné level a pak můžeš ten level získat v konstruktoru JDialogu pomocí prostého
parent.getLevel();
Možností je samozřejmě víc. Tahle mi přijde v tvém případě asi nejjednodušší.
pocitac770:2.1.2016 12:17
OOP je nadstavba základu, ovšem stále hodně důležitá znalost. Vše, co se týká okenních aplikací vyžaduje často buď řekněme střední znalosti OOP, případně hodně dobrou schopnost improvizovat... Takže hybaj si to přečíst
Atrament:2.1.2016 12:44
Bez OOP se v Javě nikam moc nedostaneš, Java je na OOP postavená.
+20 Zkušeností
+2,50 Kč
Tohle bude asi nejlepší.
HlavniJFrame:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package klikacihra;
import java.io.File;
import javax.swing.JOptionPane;
/**
*
* @author HREJsi.cz
*/
public class HlavniJFrame extends javax.swing.JFrame {
/**
* Creates new form HlavniJFrame
*/
public HlavniJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
bunkaJLabel = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
numOfClicksJLabel = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
levelJLabel = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
doDalsiUrovneJLabel = new javax.swing.JLabel();
hlaskaJLabel = new javax.swing.JLabel();
menuJButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Klikací hra");
bunkaJLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/klikacihra/images/bunka1.png"))); // NOI18N
bunkaJLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addClick(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("Number of clicks:");
numOfClicksJLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
numOfClicksJLabel.setForeground(new java.awt.Color(255, 51, 51));
numOfClicksJLabel.setText("0");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel2.setText("Úroveň:");
levelJLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
levelJLabel.setForeground(new java.awt.Color(255, 51, 51));
levelJLabel.setText("1");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel3.setText("Do další úrovně:");
doDalsiUrovneJLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
doDalsiUrovneJLabel.setForeground(new java.awt.Color(255, 51, 51));
doDalsiUrovneJLabel.setText("25");
hlaskaJLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
hlaskaJLabel.setForeground(new java.awt.Color(0, 0, 153));
hlaskaJLabel.setToolTipText("");
menuJButton.setText("Menu");
menuJButton.setEnabled(false);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, menuJButton, org.jdesktop.beansbinding.ELProperty.create("enabledProp"), menuJButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"), "enabledProp");
bindingGroup.addBinding(binding);
menuJButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
openMenu(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numOfClicksJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(levelJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(doDalsiUrovneJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(128, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(bunkaJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hlaskaJLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(menuJButton)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(numOfClicksJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(levelJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(doDalsiUrovneJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(bunkaJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(hlaskaJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(menuJButton)))
.addContainerGap(24, Short.MAX_VALUE))
);
bindingGroup.bind();
pack();
}// </editor-fold>
int clicks;
int level = 1;
int pointsToNextLevel = 25;
int remainingpoints = 25;
int evstage = 0;
String[] hlasky = {"Probouzíš svoji buňku k životu!","Ty růžové kroužky, to jsou oči?","<html>Rozklikni \"menu\" pro další <br />mutaci</html>","Evoluce přichází!","Oči navíc, kdo by to nechtěl...","Děťátko!","Další potvůrka!"};
public int getLevel() {
return level;
}
private void addClick(java.awt.event.MouseEvent evt) {
clicks += 1;
numOfClicksJLabel.setText(Integer.toString(clicks));
remainingpoints -= 1;
doDalsiUrovneJLabel.setText(Integer.toString(remainingpoints));
if (remainingpoints == 0) {
level += 1;
evstage += 10;
pointsToNextLevel *= 2;
remainingpoints = pointsToNextLevel;
levelJLabel.setText(Integer.toString(level));
bunkaJLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource( "/klikacihra/images/bunka" + level + ".png")));
hlaskaJLabel.setText(hlasky[level - 2]);
if (level >= 4) {
menuJButton.setEnabled(true);
//Zde je ukládání
String cesta = "";
cesta = System.getenv("APPDATA") + File.separator + "EvClickFiles";
File fCesta = new File(cesta);
if (!fCesta.isDirectory())
{
if (!fCesta.mkdirs())
{
System.out.printf("Nepodařilo se vytvořit složku %s, zkontrolujte prosím svá oprávnění.", cesta);
}
}
File fDatabaze = new File(cesta + File.separator + "databaze.dat");
//Konec ukládání
}
}
}
private void openMenu(java.awt.event.MouseEvent evt) {
if (level < 4) {
JOptionPane.showMessageDialog(null, "Toto je menu je přístupné až od úrovně 4!");
} else {
MenuJDialog osobaJDialog = new MenuJDialog(this, true);
osobaJDialog.setLocationRelativeTo(null);
osobaJDialog.setVisible(true);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(HlavniJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HlavniJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HlavniJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HlavniJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new HlavniJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel bunkaJLabel;
private javax.swing.JLabel doDalsiUrovneJLabel;
private javax.swing.JLabel hlaskaJLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel levelJLabel;
private javax.swing.JButton menuJButton;
private javax.swing.JLabel numOfClicksJLabel;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration
}
a MenuJDialog:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package klikacihra;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
/**
*
* @author HREJsi.cz
*/
public class MenuJDialog extends javax.swing.JDialog {
/**
* Creates new form MenuJDialog
*/
public MenuJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
JjProgressBar = new javax.swing.JProgressBar();
JButton = new javax.swing.JButton();
saveJButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Menu");
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setText("MENU");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("Evolution stage:");
JjProgressBar.setValue(30);
JButton.setText("Close");
JButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
close(evt);
}
});
saveJButton.setText("Uložit pokrok");
saveJButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
save(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(98, 98, 98)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(JjProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(JButton)
.addGap(47, 47, 47)
.addComponent(saveJButton)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(JjProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 234, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JButton)
.addComponent(saveJButton)))
);
pack();
}// </editor-fold>
private void close(java.awt.event.MouseEvent evt) {
dispose();
}
private void save(java.awt.event.MouseEvent evt) {
int level = HlavniJFrame.level; //Tady je chyba.
File fDatabaze = new File(System.getenv("APPDATA") + File.separator + "EvClickFiles");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fDatabaze + File.separator + "save.txt")))
{
bw.write("Test");
bw.flush();
}
catch (Exception e)
{
System.err.println("Do souboru se nepovedlo zapsat.");
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MenuJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MenuJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MenuJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MenuJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
MenuJDialog dialog = new MenuJDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton JButton;
private javax.swing.JProgressBar JjProgressBar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JButton saveJButton;
// End of variables declaration
}
Atrament:2.1.2016 13:59
Všimni si řádku
MenuJDialog osobaJDialog = new MenuJDialog(this, true);
v HlavniJFrame
tam pašuješ instanci toho HlavniJFrame do toho MenuJDialog - to je to slovicko
'this'. Když se pak podíváš do konstruktoru MenuJDialog, tak tam vidíš tu
instanci pod jménem parent. Takže můžeš udělat to co jsem ti prve
navrhoval. V HlavniJFrame udělej public metodu getLevel() co bude vracet level
a v MenuJDialog přidej:
private int level;
a v konstruktoru proveď:
public MenuJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
this.level = parent.getLevel(); //tady získáš ten level z HlavniJFrame
initComponents();
}
a máš vystaráno.
Atrament:3.1.2016 14:10
Ve standardní Javě pokud vím ne, ale vsadím se že existují nějaké knihovny co to mají.
Neaktivní uživatel:3.1.2016 14:14
diky bohu NE ... duvodem je puvod nazvu funkce ... neni to jak si vetsina
lidi mysli evaluate ... je to neco mnohem temnejsiho ... je to slovo evil...ja
vim, neni to poznat, ale ver mi eval() je zlo... a ted vazne, java ma ambice byt
kvalitni platformou a jazykem, snazi se byt bezpecna co to jde, a eval() je
neco, co bezpecne neni, pokud ale potrebujes eval() jen k vyhodnocovani vyrazu
(logickych) mas nekolik moznosti, dokonce jsem uz jednou byl u toho, kdyz to
tady nekdo pozadoval, muzes zapatrat ... pro predstavu, je tu moznost knihovny
co to pekne a bezpecne udela za tebe, je tu moznost javascriptoveho enginu,
ktery ten eval umi (to je ta zla moznost), ale je tu projekt na GitHubu, ktery
tohle javascriptove jadro osekal do minima a tak ted vyhodnocuje jen logicke
vyrazy, neda se tedy zneuzit tak snadno (to je ta dobra moznost) ..
nebo si napsat vlastni parser (to je ta tezka moznost)
Potřebuju poradit...
Kreslím na Graphics pomocí drawImage(), která jako první parametr bere
proměnnou typu Image. Vždycky jsem si myslel, že bude stačit cesta k
souboru, ale asi ne. Nevíte někdo jak pracovat s dat. typem Image?
Zobrazeno 19 zpráv z 19.