I found on the Web code: http://java-sl.com/tip_autoreplace_smiles.html which I edited to my own needs, take a look:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Emotes extends JEditorPane {
public Emotes() {
super();
this.setEditorKit(new StyledEditorKit());
this.initListener();
}
private void replace (String text, StyledDocument doc, ImageIcon icon, int start, String what) throws BadLocationException
{
int i = text.indexOf(what);
while(i >= 0)
{
final SimpleAttributeSet attrs = new SimpleAttributeSet(doc.getCharacterElement(start+i).getAttributes());
if (StyleConstants.getIcon(attrs) == null)
{
StyleConstants.setIcon(attrs, icon);
doc.remove(start+i, what.length());
doc.insertString(start+i,what, attrs);
}
i = text.indexOf(what, i+what.length());
}
}
private void initListener() {
getDocument().addDocumentListener(new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent event) {
final DocumentEvent e=event;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
if (e.getDocument() instanceof StyledDocument) {
try {
StyledDocument doc=(StyledDocument)e.getDocument();
int start= Utilities.getRowStart(Emotes.this,Math.max(0,e.getOffset()-1));
int end=Utilities.getWordStart(Emotes.this,e.getOffset()+e.getLength());
String text=doc.getText(start, end-start);
replace(text, doc, createEmoticon("wink.png"), start, ";)");
replace(text, doc, createEmoticon("wink.png"), start, "<wink>");
replace(text, doc, createEmoticon("sad.png"), start, ":(");
replace(text, doc, createEmoticon("sad.png"), start, "<sad>");
replace(text, doc, createEmoticon("smile.png"), start, ":)");
replace(text, doc, createEmoticon("smile.png"), start, "<smile>");
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
});
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
}
static ImageIcon createEmoticon(String icon)
{
BufferedImage img = null;
try
{
img = ImageIO.read(new File(icon));
Graphics g = img.getGraphics();
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}catch (IOException ex)
{
}
return new ImageIcon(img);
}
}
which works great. But I created in Netbeans a new GUI (JDialog Window) with JEditorPane on it, where I want to use this feature on JDialog window:
but it doesnt want to work at all. When I type ":)" its not changing in an image.
Just try to run that code:
public class NewJDialog extends javax.swing.JDialog {
/** Creates new form NewJDialog */
public NewJDialog(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() {
jScrollPane1 = new javax.swing.JScrollPane();
jEditorPane1 = new Emotes();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jScrollPane1.setViewportView(jEditorPane1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
/**
* #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(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJDialog.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() {
NewJDialog dialog = new NewJDialog(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.JEditorPane jEditorPane1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
And the emotes I use are:
An application is compiled to a .jar file. Normal File I/O then does not take (the current directory varies depending on the call). Take the images out of the jar/class path as:
img = ImageIO.read(Emotes.class.getResourceAsStream(icon));
Related
i am making simple graphics editor, and on the beggining ive got a problem.
I am doing double windows program, i want to click button in one window, choose path of the image, and after that image appear on the second window. I ve done almost everything, but it looks like that: i start the program nothing appears in second window, i read image and it doesnt appear on the second window, it looks like i need something to refresh second window after i read image, but i dont know how to do that, please help.
I know that there is repaint() method, but i dont know how to use repaint in one window and force it to repaint the second one
First file:
package edytor;
import java.awt.*;
import javax.swing.*;
public class Edytor extends JFrame {
public static boolean pom, pom1;
public static Image obraz;
public static String sciezka;
public Edytor() {
super("Edytor 2D");
setBounds(420,50,800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
CObrazek obraz = new CObrazek();
con.add(obraz);
przybornik przyb = new przybornik();
pom = false;
pom1=false;
Edytor.obraz = new ImageIcon(Edytor.sciezka).getImage();
setVisible(true);
}
public static void main(String args[]) {
new Edytor();
}
}
class CObrazek extends Canvas {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(Edytor.obraz, 0,0,null);
g2d.drawString("Wsp x: " , 300, 400);
}
}
Second file:
package edytor;
import java.io.*;
import javax.swing.*;
public class przybornik extends javax.swing.JFrame {
public przybornik() {
initComponents();
setVisible(true);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
read_but = new javax.swing.JButton();
save_but = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
read_but.setText("Wczytaj");
read_but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
read_butActionPerformed(evt);
}
});
save_but.setText("Zapisz");
save_but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
save_butActionPerformed(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()
.addContainerGap()
.addComponent(read_but, javax.swing.GroupLayout.PREFERRED_SIZE,
184, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(save_but, javax.swing.GroupLayout.DEFAULT_SIZE,
178, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(read_but)
.addComponent(save_but))
.addContainerGap(266, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void read_butActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new
File(System.getProperty("user.home")));
int path = fileChooser.showOpenDialog(this);
if (path == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " +
selectedFile.getAbsolutePath());
Edytor.sciezka = selectedFile.getAbsolutePath();
}
System.out.print(Edytor.sciezka);
}
private void save_butActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #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(przybornik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(przybornik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(przybornik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(przybornik.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 przybornik().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton read_but;
private javax.swing.JButton save_but;
// End of variables declaration
}
I just show you the places I changed and added.
EDIT:
public class Edytor extends JFrame{
CObrazek obraz = new CObrazek();//here (new place)
public static boolean pom, pom1;
public static Image image;
public static String sciezka;
public void EdytorShow(String image_path) {//changed
setBounds(420,50,800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
//CObrazek obraz = new CObrazek();//disabled
przybornik przyb = new przybornik();//here (new place)
/**
* We do not want the window to appear without selecting an image.
* For this reason we will use "if"
*/
if(!image_path.equals("null")){
con.add(obraz);
// przybornik przyb = new przybornik();//Moved out of if ;)
pom = false;
image = new ImageIcon(image_path).getImage();
setVisible(true);
}//if
}
public static void main(String args[]) {
Edytor et = new Edytor();
et.EdytorShow("null");
}
}
And in the "przybornik.java" file:
private static boolean isWindowActive = false; //for window active.
public przybornik() {
initComponents();
if(isWindowActive == false){ //window active check here.
setVisible(true);
isWindowActive = true;
}
}
//-------- and:
Edytor edytor = new Edytor();//here (new place)
private void read_butActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new
File(System.getProperty("user.home")));
int path = fileChooser.showOpenDialog(this);
if (path == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " +
selectedFile.getAbsolutePath());
//Edytor.sciezka = selectedFile.getAbsolutePath();
//new Edytor().EdytorShow(selectedFile.getAbsolutePath());//disabled(Moved out of function ;)
edytor.EdytorShow(selectedFile.getAbsolutePath());//newly added
}
System.out.print(Edytor.sciezka);
}
I am trying to make a simple Java GUI that allows you to enter a time, and once the time runs out, it plays a sound. For some reason I find an error despite looking a many different sources that all tell me to use Timer or Handler. Here is my code:
/*
* 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.
*/
/**
*
* #author CIS
*/
import java.io.*;
import sun.audio.*;
import java.util.TimerTask;
public class Timer extends javax.swing.JFrame {
public Timer() {
initComponents();
initEditable();
}
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop1 = null;
AudioPlayer ABC = AudioPlayer.player;
AudioStream ABCD;
AudioData ABCDE;
ContinuousAudioDataStream loop2 = null;
public void initEditable(){
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
textFieldTimer = new javax.swing.JTextField();
buttonTest = new javax.swing.JButton();
buttonSet = new javax.swing.JButton();
labelTimeRemaining = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonTest.setText("Test Sound");
buttonTest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonTestActionPerformed(evt);
}
});
buttonSet.setText("Set");
buttonSet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSetActionPerformed(evt);
}
});
labelTimeRemaining.setText("time remaing");
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.TRAILING, false)
.addComponent(textFieldTimer)
.addComponent(buttonTest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(buttonSet)
.addComponent(labelTimeRemaining)))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonSet, buttonTest, labelTimeRemaining, textFieldTimer});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldTimer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelTimeRemaining))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonTest)
.addComponent(buttonSet)))
);
pack();
}// </editor-fold>
int hello = 1000;
public void music1(){
ContinuousAudioDataStream loop = null;
try
{
InputStream alert = new FileInputStream("alert.wav");
BGM = new AudioStream(alert);
AudioPlayer.player.start(BGM);
//MD = BGM.getData();
//loop = new ContinuousAudioDataStream(MD)
}
catch(FileNotFoundException e){
System.out.print(e.toString());
}
catch(IOException error)
{
System.out.print(error.toString());
}
MGP.start(loop1);
}
private void buttonSetActionPerformed(java.awt.event.ActionEvent evt) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
music1();
}
}, 2000);
}
private void buttonTestActionPerformed(java.awt.event.ActionEvent evt) {
music1();
}
/**
* #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(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Timer.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 Timer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonSet;
private javax.swing.JButton buttonTest;
private javax.swing.JLabel labelTimeRemaining;
private javax.swing.JTextField textFieldTimer;
// End of variables declaration
}
When I get to the line new Timer().schedule(new TimerTask() {
I get on error on the schedule.
I apologize if my method of presenting my problem is incorrect, I'm new here and new to Java programming as well.
Your class has the same name as the java.util.Timer class. You must disambiguate by fully qualifying that class name:
new java.util.Timer().schedule(new TimerTask() {
I'm making one jInternalFrame where I'am adding tabs dynamically.
now adding a new TAB I have coded,
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ui;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JTabbedPane;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.plaf.basic.BasicInternalFrameUI;
/**
*
* #author santoshg
*/
public class jTAB extends javax.swing.JFrame {
/**
* Creates new form jTAB
*/
JTabbedPane tabList = new JTabbedPane();
int nUserCount = 1;
boolean isDrag = true;
private static int pressedX = 0, pressedY = 0;
JDesktopPane sDesktoppane = new JDesktopPane();
JComponent northPane;
public jTAB() {
this.setUndecorated(true);
initComponents();
drag();
jInternalFrame1.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("maximum")) {
if (jInternalFrame1.isMaximum()) {
try { // Maximizing TAB window with the size of Screen.
jInternalFrame1.setMaximum(true);
Toolkit tk = getToolkit();
jInternalFrame1.setSize((int) getToolkit().getScreenSize().getWidth(), (int) getToolkit().getScreenSize().getHeight());
setLocation(0, 0);
isDrag = false;
} catch (Exception e) {
e.printStackTrace();
}
} else {
try { // Setting it to it's actual size.
jInternalFrame1.setMaximum(false);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
isDrag = true;
setLocation(pressedX, pressedY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
public final void drag() {
setContentPane(sDesktoppane);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
jInternalFrame1.addInternalFrameListener(new InternalFrameListener() {
#Override
public void internalFrameOpened(InternalFrameEvent e) {
}
#Override
public void internalFrameClosing(InternalFrameEvent e) {
}
#Override
public void internalFrameClosed(InternalFrameEvent e) {
}
#Override
public void internalFrameIconified(InternalFrameEvent e) {
jInternalFrame1.setIconifiable(true);
}
#Override
public void internalFrameDeiconified(InternalFrameEvent e) {
}
#Override
public void internalFrameActivated(InternalFrameEvent e) {
}
#Override
public void internalFrameDeactivated(InternalFrameEvent e) {
}
});
jInternalFrame1.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("maximum")) {
if (jInternalFrame1.isMaximum()) {
try { // Maximizing TAB window with the size of Screen.
jInternalFrame1.setMaximum(true);
Toolkit tk = getToolkit();
jInternalFrame1.setSize((int) getToolkit().getScreenSize().getWidth(), (int) getToolkit().getScreenSize().getHeight());
`enter code here` setLocation(0, 0);
isDrag = false;
} catch (Exception e) {
e.printStackTrace();
}
} else {
try { // Setting it to it's actual size.
jInternalFrame1.setMaximum(false);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
isDrag = true;
setLocation(pressedX, pressedY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
if (northPane == null) {
northPane = ((BasicInternalFrameUI) jInternalFrame1.getUI()).getNorthPane();
northPane.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
if (isDrag) {
System.out.println("pressedX and pressedY " + pressedX + " " + pressedY);
pressedX = e.getX();
pressedY = e.getY();
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
northPane.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if (isDrag) {
int draggedObjX = getLocation().x + e.getX() - pressedX;
int draggedObjY = getLocation().y + e.getY() - pressedY;
setLocation(draggedObjX, draggedObjY);
getjInternalFrame().setLocation(0, 0);
}
}
public void mouseMoved(MouseEvent e) {
}
});
}
sDesktoppane.add(jInternalFrame1);
jInternalFrame1.setVisible(true);
jInternalFrame1.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
setSize(jInternalFrame1.getSize().width, jInternalFrame1.getSize().height);
}
});
setSize(jInternalFrame1.getSize());
if (northPane == null) {
setLocation(new Point(pressedX, pressedY));
}
super.setVisible(true);
}
public JInternalFrame getjInternalFrame() {
return jInternalFrame1;
}
public JComponent getNorthPane() {
return northPane;
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jInternalFrame1 = new javax.swing.JInternalFrame();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame1.setMaximizable(true);
jInternalFrame1.setVisible(true);
jButton1.setText("Add TAB");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup()
.addGap(0, 512, Short.MAX_VALUE)
.addComponent(jButton1))
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 301, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1, javax.swing.GroupLayout.Alignment.TRAILING)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
tabList.addTab("User " + nUserCount, new ChatWindow("user " + nUserCount).getFrameComponent());
JComponent jif = (JComponent) jInternalFrame1.getContentPane();
jif.setLayout(new BorderLayout());
jif.add(tabList);
nUserCount++;
}//GEN-LAST:event_jButton1ActionPerformed
/**
* #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(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(jTAB.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 jTAB().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JInternalFrame jInternalFrame1;
// End of variables declaration//GEN-END:variables
}
Where ChatWindow,java is
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ui;
import javax.swing.JComponent;
/**
*
* #author santoshg
*/
public class ChatWindow extends javax.swing.JFrame {
/**
* Creates new form ChatWindow
*/
public ChatWindow() {
initComponents();
}
public ChatWindow(String userName) {
initComponents();
lblUserName.setText(userName);
}
public JComponent getFrameComponent(){
return jPanel1;
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblUserName = new javax.swing.JLabel();
lblAvatar = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
lblUserDept = new javax.swing.JLabel();
lblContactInfo = new javax.swing.JLabel();
lblSendFile = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblUserName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblUserName.setText("UserName");
lblUserName.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
lblAvatar.setText("Avatar");
lblAvatar.setAlignmentX(0.5F);
lblAvatar.setAlignmentY(0.2F);
lblAvatar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lblAvatar.setIconTextGap(2);
lblAvatar.setPreferredSize(new java.awt.Dimension(35, 15));
jTextArea1.setEditable(false);
jTextArea1.setBackground(new java.awt.Color(249, 251, 252));
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jTextArea2.setColumns(20);
jTextArea2.setRows(2);
jTextArea2.setMinimumSize(new java.awt.Dimension(3, 22));
jScrollPane2.setViewportView(jTextArea2);
lblUserDept.setText("Department");
lblContactInfo.setToolTipText("User Info");
lblSendFile.setToolTipText("Send File");
jLabel1.setToolTipText("View History");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE)
.addComponent(lblUserDept, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 355, Short.MAX_VALUE)
.addComponent(lblContactInfo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblSendFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblContactInfo)
.addComponent(lblSendFile))
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblUserDept))
.addComponent(lblAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* #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(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatWindow.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 ChatWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JLabel lblAvatar;
private javax.swing.JLabel lblContactInfo;
private javax.swing.JLabel lblSendFile;
private javax.swing.JLabel lblUserDept;
private javax.swing.JLabel lblUserName;
// End of variables declaration//GEN-END:variables
}
Hit the add button twice you'll get 2 TABS not when I maximize it "Add TAB" moved to Middle and Textareas are in top.
I want jTextAtrea1 to expand till the bottom of the page during maximize and restore to actual size during toggle.
I want jTextAtrea1 to expand till the bottom of the page during maximize
Sounds like you should be using a BorderLayout for the panel you add to the tab. Then you add the text area to the BorderLayout.CENTER and the other components to the BorderLayout.NORTH.
It looks like your layout code is generated by an IDE. Don't use the IDE to generate layout code. Do the layout yourself and you will be in full control.
I can't get this to work:
public void ru() throws InterruptedException {
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
setVisible(true);
}
private void BtnRoomsMouseEntered(java.awt.event.MouseEvent evt) {
try {
ru();
} catch (InterruptedException ex) {
}
}
Any solutions?
I want a jLabel to show a slide show when a mouse enters a certain button and stays like that as long as the mouse is still in a button. If the mouse happens to exit the button, the jlabel will return to a null state. (no more anything.) Is that possible? Please help. I also tried using for statement but no good. I'm using netbeans by the way.
First thing you need to implement a javax.swing.Timer. Trying to call Thread.sleep() will block the Event Dispatch Thread. See How to use Swing Timers. Here is the basic construct
Timer(int delay, ActionListener listener)
where delay is the time in milliseconds you want delayed and the listener will listen for the Timer ActionEvent fired every delay milliseconds.
So you want something like this
public class MyFrame extends javax.swing.JFrame {
private Timer timer = null;
ImageIcon[] icons = new ImageIcon[3];
int index = -1;
public MyFrame() {
initComponents();
icons[0] = new ImageIcon(...);
icons[1] = new ImageIcon(...);
icons[2] = new ImageIcon(...);
timer = new Timer(2000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (index + 1 > 2) {
index = 0;
jLabel3.setIcon(icons[index]);
} else {
index++;
jLabel3.setIcon(icons[index]);
}
}
});
}
}
For your button, you need to use mouseEntered and mouseExited, then you can just call timer.start() or timer.stop()
private void jButton1MouseExited(MouseEvent e) {
timer.stop();
}
private void jButton1MouseEntered(MouseEvent e) {
timer.start();
}
If you don't know how to add the MouseListener just right click on the button from the design view and select Event -> Mouse -> mouseEntered. Do the same for mouseExited. You should see the above methods auto-generated for you.
UPDATE
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class ImageViewer extends javax.swing.JFrame {
private Timer timer = null;
ImageIcon[] icons = new ImageIcon[5];
int index = -1;
public ImageViewer() {
initComponents();
try {
icons[0] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png"));
icons[1] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/caribbean-blue/stackoverflow-4-xxl.png"));
icons[2] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
icons[3] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/moth-green/stackoverflow-4-xxl.png"));
icons[4] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/soylent-red/stackoverflow-4-xxl.png"));
} catch (MalformedURLException ex) {
Logger.getLogger(ImageViewer.class.getName()).log(Level.SEVERE, null, ex);
}
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (index + 1 > 4) {
index = 0;
jLabel1.setIcon(icons[index]);
} else {
index++;
jLabel1.setIcon(icons[index]);
}
}
});
}
/**
* 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() {
jButton1 = new JButton();
jLabel1 = new JLabel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent evt) {
jButton1MouseEntered(evt);
}
public void mouseExited(MouseEvent evt) {
jButton1MouseExited(evt);
}
});
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(127, 127, 127))
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 285, GroupLayout.PREFERRED_SIZE)
.addContainerGap(29, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(16, 16, 16))
);
pack();
}// </editor-fold>
private void jButton1MouseEntered(MouseEvent evt) {
timer.start();
}
private void jButton1MouseExited(MouseEvent evt) {
timer.stop();
}
/**
* #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(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ImageViewer.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 ImageViewer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private JButton jButton1;
private JLabel jLabel1;
// End of variables declaration
}
You want to add a MouseAdapter to the JLabel and use its mouseEntered() and mouseExited() as follows:
jLabel3.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
setVisible(true);
} catch(InterruptedException e) {
}
#Override
public void mouseExited(java.awt.event.MouseEvent evt) {
//whatever you mean by "null state"
}
});
How to change the color of circle on click button in Java?
Here is the code
package circle;
import java.awt.Color;
import java.awt.Graphics;
/**
*
* #author Akmal
*/
public class NewJApplet extends javax.swing.JApplet {
/**
* Initializes the applet NewJApplet
*/
#Override
public void init() {
/* 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(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void paint(Graphics g)
{
super.paint( g );
setForeground(Color.yellow);
g.fillOval(100, 100, 100, 100);
}
/**
* This method is called from within the init() method 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() {
jButton2 = new javax.swing.JButton();
jButton2.setText("Blue");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(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()
.addContainerGap()
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
.addGap(277, 277, 277))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(137, 137, 137))
);
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
// Variables declaration - do not modify
private javax.swing.JButton jButton2;
// End of variables declaration
}
Please help
Declare a Color color = Color.YELLOW; as a class attribute.
Change setForeground(Color.yellow); to setForeground(color);
Change // TODO add your handling code here: to something like color = Color.BLACK; repaint();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NewJApplet extends JApplet {
private Color currentColor = Color.YELLOW;
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(currentColor);
g.fillOval(100, 100, 100, 100);
}
private void jButton2ActionPerformed(ActionEvent evt){
currentColor = Color.BLUE;
repaint();
}
}