JFrame の特定の要素をクリックすると、JLabel の背景が変更される Java プログラムを作成しようとしています。背景を変更するためにイベント処理メソッドが呼び出す関数は、イベントから呼び出された場合は機能しませんが、イベントとは関係なくどこかでメソッドを呼び出すと機能します。そのようなイベント処理メソッドを使用しても機能しないため、MouseRelease イベントの背景を変更する方法を知っている人はいますか?
private void MouseReleaseEvent(java.awt.event.MouseEvent evt) {
// Do some random stuff, like a println.
// This println works as a normal println statement should.
System.out.println("Hello World!");
// Now let's try the method that changes the background.
// This method will not work within this event handler, but trying it outside
// of it does work.
changeBackground();
}
- 注:上記のコードは、私の問題を示すためのものです。実際には私のコードの一部ではありません。私は友人と一緒にプログラムに取り組んでいるので、コードをリリースしません。彼はコードをリリースしたくないと思っています。
編集:私を助けようとしているすべての人の要求に従って、NetBeans プロジェクトワークスペースを FileDropper に zip ファイルでアップロードしました。これは、ここからダウンロードできます。メインクラスからメソッドを呼び出すと、別の画像がフラッシュされ、必要に応じて現在の画像に戻りますが、[再生] をクリックしてマウスを放すと、呼び出されないことに気付くでしょう。そうすべき。必要に応じてコードを試してみてください。
編集 2:ワークスペースをダウンロードしたくない人のためにコードを投稿することも要求されているので、ここにあります:
サイモン.java
package simon;
public class Simon {
public static void main(String[] args) {
// Load all of the other class files into this main class.
SimonGUI SimonGUI = new SimonGUI();
// For some reason, setting the background color doesn't work when we
// try doing it within the GUI development environment, but it works
// here, so that's what we are going to do.
SimonGUI.getContentPane().setBackground(new java.awt.Color(0, 0, 0));
// Make the form visible to the user. It is now ready for use.
SimonGUI.setVisible(true);
SimonGUI.playBackPattern();
}
}
SimonGUI.java*
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package simon;
import java.awt.Component;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Administrator
*/
public class SimonGUI extends javax.swing.JFrame {
// Declare class level variables.
boolean aboutTextVisible = false;
boolean mainMenuVisible = true;
boolean userResponseAllowed = false;
private Component frame;
/**
* Creates new form SimonGUI
*/
public SimonGUI() {
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() {
lblPlayButton1 = new javax.swing.JLabel();
lblPlayButton = new javax.swing.JLabel();
lblSimonBoard = new javax.swing.JLabel();
lblPlayButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/MenuPlay.png"))); // NOI18N
lblPlayButton1.setName("lblPlayButton"); // NOI18N
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Simon");
setBackground(new java.awt.Color(0, 0, 0));
setMaximumSize(new java.awt.Dimension(600, 600));
setMinimumSize(new java.awt.Dimension(600, 600));
setName("frmSimon"); // NOI18N
setPreferredSize(new java.awt.Dimension(600, 600));
setResizable(false);
getContentPane().setLayout(null);
lblPlayButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/MenuPlay.png"))); // NOI18N
lblPlayButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
lblPlayButton.setName("lblPlayButton"); // NOI18N
lblPlayButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
lblPlayButtonMouseReleased(evt);
}
});
getContentPane().add(lblPlayButton);
lblPlayButton.setBounds(150, 20, 317, 58);
lblPlayButton.getAccessibleContext().setAccessibleName("lblPlayerButton");
lblSimonBoard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/Original.PNG"))); // NOI18N
lblSimonBoard.setToolTipText("");
lblSimonBoard.setFocusable(false);
lblSimonBoard.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
lblSimonBoard.setName("lblSimon"); // NOI18N
getContentPane().add(lblSimonBoard);
lblSimonBoard.setBounds(-1, 93, 600, 497);
lblSimonBoard.getAccessibleContext().setAccessibleName("lblSimon");
getAccessibleContext().setAccessibleName("frmSimon");
getAccessibleContext().setAccessibleDescription("");
pack();
}// </editor-fold>
private void lblPlayButtonMouseReleased(java.awt.event.MouseEvent evt) {
// This handles the start of Simon gameplay.
toggleBoard();
playBackPattern();
}
public void toggleBoard() {
// Handles toggling between the main menu and the simon board.
if (mainMenuVisible == true)
{
// Board is visible, let's toggle it off.
lblPlayButton.setBounds(700, 700, 317, 58);
mainMenuVisible = false;
lblSimonBoard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/Original.PNG")));
}
else
{
// Board is not visible, let's toggle it on.
lblPlayButton.setBounds(120, 140, 317, 58);
mainMenuVisible = true;
lblSimonBoard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/SimonBackground.PNG")));
}
}
/**
* @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(SimonGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SimonGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SimonGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SimonGUI.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 SimonGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel lblPlayButton;
private javax.swing.JLabel lblPlayButton1;
public javax.swing.JLabel lblSimonBoard;
// End of variables declaration
public void flashColor(int colorID) {
// Flash one of the colors. The value of the color that we are going to
// flash is passed here, and the color is flashed.
// Pause for a fraction of a second before blinking the color. In case
// something goes wrong during the pause, we have an error which we hope
// to never use that will catch the program's weakness.
try {
Thread.sleep(250);
} catch (InterruptedException ex) {
JOptionPane.showMessageDialog(frame,"A fatal error has caused Simon to stop working.","Simon • Fatal Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
// Flash the respective color.
if(colorID == 1) {
// Flash Red
lblSimonBoard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/Red.PNG")));
}
else if(colorID == 2){
// Flash Green
lblSimonBoard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/Green.PNG")));
}
else if (colorID == 3) {
// Flash Yellow
lblSimonBoard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/Yellow.PNG")));
}
else {
// Flash Blue
lblSimonBoard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/Blue.PNG")));
}
// Wait for a fraction of a second before we return to the regular
// board. In case something bad happens here while we pause, we have an
// error message that we hope will never be used.
try {
Thread.sleep(250);
lblSimonBoard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simon/resources/Original.PNG")));
} catch (InterruptedException ex) {
JOptionPane.showMessageDialog(frame,"A fatal error has caused Simon to stop working.","Simon • Fatal Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
public void userResponseEnabled(boolean responsePermitted) {
// Toggles the class-level variable "userResponseAllowed", which
// controls if the user can click on the buttons on the Simon board and
// give a response.
// Pass the value to the class-level variable.
userResponseAllowed = responsePermitted;
}
// "Actual Game Code"
int score = 0;
ArrayList pattern = new ArrayList();
int playerColor = 0;
int y = 0;
boolean correct = true;
private SimonGUI SimonGUI;
int certainColor = 1;
int numberOfColors = 0;
public void playBackPattern() {
// Normally, the playBackPattern() method has more than just this line,
// but for demo purposes, this line is all that is needed.
flashColor(4);
}
}
*このコードの一部は、NetBeans 用の Swing GUI デザイナー アドオンを使用して自動的に生成されます。