i want to add a image at 615,50 in my applet . image name is logo1.jpg . but the following code only prints d image.. when i compile and then run using applet viewer. only the image logo1 shows at d spot. the rest code doesnt work. however if i remove the image . then the code works fine. i think theres some problem with the paint() function . if i use ImageIcon and then add it into a label and set that label to the location,then it works fine in the appletviewer but as soon as i open it in a webbrowser, an IO Error appears
"access denied("java.io.FilePermission" "logo1.jpg" "read" ). pls help. image size is 126,126.
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
public class site extends Applet implements MouseListener, Runnable
{
JLabel l1;
JLabel l2;
JLabel l3;
JLabel l4;
JLabel l5;
JLabel l6;
JLabel l21;
String str;
String s1;
String s2;
String s3;
Thread th;
int x;
int vt;
int hr;
int yx=75;
ImageIcon I;
Image image;
public void init()
{
setLayout(null);
addMouseListener(this);
loadImage();
//I=new ImageIcon("logo1.jpg");
l1 = new JLabel("2");
l1.setBounds(433, yx, 50, 50);
l1.setFont(new Font("Sketch Block", Font.PLAIN, 50));
l1.setForeground(Color.red);
add(l1);
l21=new JLabel(I);
l21.setBounds(630,50,126,126);;
add(l21);
l2 = new JLabel("0");
l2.setBounds(483, yx, 50, 50);
l2.setFont(new Font("Sketch Block", 0, 50));
l2.setForeground(Color.blue);
add(l2);
l3 = new JLabel("1");
l3.setBounds(543, yx, 50, 50);
l3.setFont(new Font("Sketch Block", 0, 50));
l3.setForeground(Color.magenta);
add(l3);
l4 = new JLabel("3");
l4.setBounds(583, yx, 50, 50);
l4.setFont(new Font("Sketch Block", 0, 50));
l4.setForeground(Color.cyan);
add(l4);
l5 = new JLabel("Impressions");
l5.setBounds(770, yx, 400, 50);
l5.setFont(new Font("Sketch Block", 0, 50));
l5.setForeground(Color.black);
add(l5);
l6 = new JLabel("March");
l6.setBounds(683, yx, 200, 50);
l6.setFont(new Font("Sketch Block", 0, 50));
l6.setForeground(Color.black);
th = new Thread(this);
}
public void loadImage()
{
URL url = getClass().getResource("logo1.jpg");
image = getToolkit().getImage(url);
}
public void paint(Graphics g)
{
g.drawImage(image, 615,50, this);
}
public void mouseClicked(MouseEvent me)
{
vt=me.getY();
hr=me.getX();
try
{
final URI uri = new URI("file:///E:/site/1.html");
final URI uri1 = new URI("file:///E:/site/2.html");
final URI uri2 = new URI("file:///E:/site/3.html");
if(hr<=468 && hr>=427)
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(uri);
}
catch (Exception ex)
{
}
}
}
if(hr>=468 && hr<=527)
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(uri1);
}
catch (Exception ex)
{
}
}
}
if(hr<=577 && hr>=527)
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(uri2);
}
catch (Exception ex)
{
}
}
}
}
catch(Exception e)
{
}
}
public void mouseEntered(MouseEvent me)
{
th = new Thread(this);
th.start();
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void mouseExited(MouseEvent me) {
th.stop();
l1.setText(" ");
l2.setText(" ");
l3.setText(" ");
l4.setText(" ");
l5.setText(" ");
l6.setText(" ");
l1.setText("2");
l1.setBounds(433, yx, 40, 50);
l2.setText("0");
l2.setBounds(483, yx, 40, 50);
l3.setText("1");
l3.setBounds(533, yx, 40, 50);
l4.setText("3");
l4.setBounds(583, yx, 40, 50);
l5.setText("Impressions");
l5.setBounds(770, yx, 400, 50);
l21.setBounds(630,50,126,126);
}
public void run()
{
try
{
l2.setText(" ");
for (x = 0; x < 200; x += 1)
{
Thread.sleep(1L);
l3.setText("1");
l3.setBounds(533 - x / 2, yx, 40, 50);
l1.setText("2");
l1.setBounds(433 + x / 4, yx, 40, 50);
l4.setText("3");
l4.setBounds(583 - x / 4, yx, 40, 50);
l5.setBounds(770, yx-(6*x)/8, 400, 50);
l21.setBounds(630,50-x,126,126);
l6.setText("March");
l6.setBounds(650, 200 - (5 * x)/8, 200, 50);
add(l6);
}
l3.setText("<html>1<sup><font size=3>st</font></sup></html>");
l1.setText("<html>2<sup><font size=3>st</font></sup></html>");
l4.setText("<html>3<sup><font size=3>rd</font></sup></html>");
}
catch (Exception e)
{
}
}
}
everytime i use paint method, only the paint method works and the rest of the code doesnt work properly. even if i draw a line using the paint() method. then also the same happens.
Toolkit's image loading is sometimes not working. I don't know why but it is what I experienced. Use the ImageIcon class instead.
img = new ImageIcon(getClass().getResource("logo.png")).getImage();
Related
I have a print preview made by JPanel, JDialog that run error free but doesn't show up after pack();.
I know it's a bit long, but you can just skip to PrintPreview method, others are just there to know more detail of how I control.
Pls help, I don't know why it doesn't show up on the screen. Anyone please help thanks so much. ^_^
private PageFormat pf;
private Book pg;
private int pageIndex;
private int totalPages;
private double scaler;
private String title;
private JTextField pageInput;
private JTextField zoomInput;
private PreviewPanel pp;
private JLabel statusBar;
Start Here
public void PrintPreview(String title, Book pg, int pageIndex) {
this.title = title;
setTitle(title + " - Print Preview");
scaler = .5;
this.pg = pg;
this.pageIndex = pageIndex;
this.totalPages = pg.getNumberOfPages();
pf = pg.getPageFormat(pageIndex);
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
setLayout(new BorderLayout());
pp = new PreviewPanel();
add(new JScrollPane(pp), BorderLayout.CENTER);
JPanel topBar = new JPanel();
topBar.setLayout(new BorderLayout());
add(topBar, BorderLayout.NORTH);
JPanel leftTop = new JPanel();
JPanel rightTop = new JPanel();
topBar.add(leftTop, BorderLayout.WEST);
topBar.add(rightTop, BorderLayout.EAST);
leftTop.add(new JLabel("Page:"));
Insets pageButtonInsets = new Insets(0, 2, 0, 2);
JButton pageBack = new JButton("<");
pageBack.setMargin(pageButtonInsets);
pageBack.setActionCommand("back");
pageBack.addActionListener(this);
JButton pageForward = new JButton(">");
pageForward.setMargin(pageButtonInsets);
pageForward.setActionCommand("forward");
pageForward.addActionListener(this);
pageInput = new JTextField(Integer.toString(pageIndex+1));
pageInput.setPreferredSize(new Dimension(30, 20));
pageInput.setActionCommand("page");
pageInput.addActionListener(this);
leftTop.add(pageBack);
leftTop.add(pageInput);
leftTop.add(pageForward);
rightTop.add(new JLabel("Zoom:"));
zoomInput = new JTextField((int)(scaler*100)+"%");
zoomInput.setPreferredSize(new Dimension(30, 20));
rightTop.add(zoomInput);
JButton zoomSet = new JButton("Set");
zoomSet.setMargin(new Insets(0, 0, 0, 0));
zoomSet.setPreferredSize(new Dimension(30, 20));
rightTop.add(zoomSet);
zoomSet.setActionCommand("zoom");
zoomSet.addActionListener(this);
JPanel lowerBar = new JPanel();
lowerBar.setLayout(new BorderLayout());
lowerBar.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
statusBar = new JLabel("Ag"); // temporary label for setting size of status bar
lowerBar.add(statusBar, BorderLayout.CENTER);
add(lowerBar, BorderLayout.SOUTH);
JButton license = new JButton("<html>©</html>");
license.setActionCommand("license");
license.setMargin(new Insets(0, 0, 0, 0));
license.addActionListener(this);
lowerBar.add(license, BorderLayout.WEST);
JButton print = new JButton("Print...");
print.setActionCommand("print");
print.setMargin(new Insets(4, 0, 4, 0));
print.addActionListener(this);
lowerBar.add(print, BorderLayout.EAST);
pack();
//setVisible(true);
}
End here
private void updateStatusBar() {
updateStatusBar("Page " + (pageIndex+1) + " of " + totalPages);
}
private void updateStatusBar(String s) {
updateStatusBar(s, Color.black);
}
private void updateStatusBar(String s, Color c) {
statusBar.setText(s);
statusBar.setForeground(c);
}
private void print() {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPageable(pg);
pj.setJobName(title);
if (pj.printDialog()) {
try {
pj.print();
} catch (PrinterException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Could not print.\nSee the Java error console for details.", "error", JOptionPane.ERROR_MESSAGE);
}
}
}
private class PreviewPanel extends JPanel {
private static final long serialVersionUID = 1L;
public PreviewPanel() {
resetPreferredSize();
}
public void resetPreferredSize() {
setPreferredSize(new Dimension((int)(pf.getWidth()*scaler), (int)(pf.getHeight()*scaler)));
}
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D)g1;
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.white);
g.fillRect(0, 0, (int)(pf.getWidth()*scaler), (int)(pf.getHeight()*scaler));
g.setColor(Color.black);
try {
g.scale(scaler, scaler);
pg.getPrintable(pageIndex).print(g, pf, pageIndex);
updateStatusBar();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
g.setFont(new Font("Helvetica", Font.ITALIC, 30));
g.drawString("Page index out of range", 10, 30);
updateStatusBar("Page index out of range", Color.red);
} catch (PrinterException e) {
e.printStackTrace();
g.setFont(new Font("Helvetica", Font.ITALIC, 30));
g.drawString("Printer error", 10, 30);
updateStatusBar("Printer error", Color.red);
}
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getActionCommand().equals("page")) {
// change page
try {
pageIndex = Integer.parseInt(pageInput.getText())-1;
pp.repaint();
} catch (NumberFormatException e) {
// do nothing if the entry is not a number
}
} else if (arg0.getActionCommand().equals("back")) {
if (pageIndex > 0) {
pageIndex--;
pageInput.setText(Integer.toString(pageIndex+1));
pp.repaint();
}
} else if (arg0.getActionCommand().equals("forward")) {
if (pageIndex < totalPages - 1) {
pageIndex++;
pageInput.setText(Integer.toString(pageIndex+1));
pp.repaint();
}
} else if (arg0.getActionCommand().equals("zoom")) {
// change zoom setting
try {
scaler = Double.parseDouble(zoomInput.getText().replaceAll("%", ""))// 100.0;
pp.resetPreferredSize();
pp.revalidate();
pp.repaint();
} catch (NumberFormatException e) {
// do nothing if the entry is not a number
}
} else if (arg0.getActionCommand().equals("license")) {
JOptionPane.showMessageDialog(this, LICENSE);
} else if (arg0.getActionCommand().equals("print")) {
print();
}
}
Yeah, I figured it out. Hahahaha Actually it does pop out but behind other foreround application....hahahaa finally its done.
In my code i generate randoms integer between 0 and 60 and i draw lines based on these.
I just want my lines fit the ordinate vertical line without touching my randoms integer... I guess it's kind of a mathematics problem but i'm really stuck here!
Here's my code first:
Windows.java:
public class Window extends JFrame{
Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time=0;
double temperature=0.0;
Timer chrono;
public static void main(String[] args) {
new Window();
}
public Window()
{
System.out.println("je suis là");
this.setSize(1000,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
north.add(ip, BorderLayout.WEST);
print = new JButton ("Print");
north.add(print,BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("0.1",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
ListenForButton lForButton = new ListenForButton();
start.addActionListener(lForButton);
ip.addActionListener(lForButton);
print.addActionListener(lForButton);
centerPanel.add(start);
north.add(centerPanel, BorderLayout.CENTER);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
this.setContentPane(container);
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==start)
{
time=Double.parseDouble(timeStep.getText());
System.out.println(time);
chrono = new Timer((int)(1000*time),pan);
chrono.start();
}
if(e.getSource()==ip)
{
JPanel options = new JPanel();
JLabel address = new JLabel("IP Address:");
JTextField address_t = new JTextField(15);
JLabel port = new JLabel("Port:");
JTextField port_t = new JTextField(5);
options.add(address);
options.add(address_t);
options.add(port);
options.add(port_t);
int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION)
{
System.out.println(address_t.getText());
System.out.println(port_t.getText());
}
}
if(e.getSource()==print)
{
chrono.stop();
}
}
}
}
Panel.java:
public class Panel extends JPanel implements ActionListener {
int rand;
int lastrand=0;
ArrayList<Integer> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255,0,0);
Color green = new Color(0,200,0);
Color blue = new Color (0,0,200);
Color yellow = new Color (200,200,0);
int max=0;
int min=0;
int i,k,inc = 0,j;
int total,degr,moyenne;
public Panel()
{
super();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.8f));
g2.drawLine(20, 20, 20, this.getHeight()-50);
g2.drawLine(20, this.getHeight()-50, this.getWidth()-50, this.getHeight()-50);
g2.drawLine(20, 20, 15, 35);
g2.drawLine(20, 20, 25, 35);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-45);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-55);
g.drawString("10", 0, this.getHeight()-85);
g.drawString("20", 0, this.getHeight()-125);
g.drawString("30", 0, this.getHeight()-165);
g.drawString("40", 0, this.getHeight()-205);
g.drawString("50", 0, this.getHeight()-245);
g2.drawString("Maximum: ", 20, this.getHeight()-20);
g2.drawString(Integer.toString(max), 80, this.getHeight()-20);
g2.drawString("Minimum: ", 140, this.getHeight()-20);
g2.drawString(Integer.toString(min), 200, this.getHeight()-20);
g2.drawString("Average: ", 260, this.getHeight()-20);
g2.drawString(Integer.toString(moyenne), 320, this.getHeight()-20);
g2.setColor(red);
g2.drawLine(500, this.getHeight()-25, 540, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Maximum", 560, this.getHeight()-20);
g2.setColor(blue);
g2.drawLine(640, this.getHeight()-25, 680, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Minimum", 700, this.getHeight()-20);
g2.setColor(green);
g2.drawLine(780, this.getHeight()-25, 820, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Average", 840, this.getHeight()-20);
if(!randL.isEmpty()){
g2.setColor(red);
g2.drawLine(15, this.getHeight()-50-max, this.getWidth()-50,this.getHeight()-50-max);
g2.setColor(blue);
g2.drawLine(15, this.getHeight()-50-min, this.getWidth()-50,this.getHeight()-50-min);
g2.setColor(green);
g2.drawLine(15, this.getHeight()-50-moyenne, this.getWidth()-50,this.getHeight()-50-moyenne);
}
for(i = 0; i<tL.size(); i++){
int temp = randL.get(i);
int t = tL.get(i);
g2.setColor(new Color(0,0,0));
g2.drawLine(20+t, this.getHeight()-50-temp, 20+t, this.getHeight()-50);
// Ellipse2D circle = new Ellipse2D.Double();
//circle.setFrameFromCenter(20+t, this.getHeight()-50, 20+t+2, this.getHeight()-52);
}
for(j=0;j<5;j++)
{
inc=inc+40;
g2.setColor(new Color(0,0,0));
g2.drawLine(18, this.getHeight()-50-inc, 22, this.getHeight()-50-inc);
}
inc=0;
}
#Override
public void actionPerformed(ActionEvent e) {
rand = (int)(Math.random() * (60));
lastT += 80;
randL.add(rand);
tL.add(lastT);
Object obj = Collections.max(randL);
max = (int) obj;
Object obj2 = Collections.min(randL);
min = (int) obj2;
if(!randL.isEmpty()) {
degr = randL.get(k);
total += degr;
moyenne=total/randL.size();
}
k++;
if(randL.size()>=12)
{
randL.removeAll(randL);
tL.removeAll(tL);
lastT = 0;
k=0;
degr=0;
total=0;
moyenne=0;
}
repaint();
}
}
And here it what i gives me :
Sorry it's a real mess!
Any thoughts ?
Thanks.
You need to stop working with absolute/magical values, and start using the actual values of the component (width/height).
The basic problem is a simple calculation which takes the current value divides it by the maximum value and multiples it by the available width of the allowable area
int length = (value / max) * width;
value / max generates a percentage value of 0-1, which you then use to calculate the percentage of the available width of the area it will want to use.
The following example places a constraint (or margin) on the available viewable area, meaning all the lines need to be painted within that area and not use the entire viewable area of the component
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawLine {
public static void main(String[] args) {
new DrawLine();
}
public DrawLine() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int margin = 20;
int width = getWidth() - (margin * 2);
int height = getHeight() - (margin * 2);
int x = margin;
for (int index = 0; index < 4; index++) {
int y = margin + (int)(((index / 3d) * height));
int length = (int)(((index + 1) / 4d) * width);
g2d.drawLine(x, y, x + length, y);
}
g2d.dispose();
}
}
}
I have a JPanel where I have array of buttons. It's a kind of memory game, and I wont to show some few frames of animation, for example Double Point.
Here is a part of code:
This animation is that some text is slowly showing and disappearing (I used also Alpha channel in those images) , but I don't know why when id should slowly disapearing it didn't like if of this image stay there.
public void paintComponent(Graphics g)
{
//Image img = new ImageIcon("res\\double.png").getImage();
//g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
t.start();
Image img2 = new ImageIcon("res\\double\\double_0000"+i+".png").getImage();
g.drawImage(img2, 0, 0, this.getWidth(), this.getHeight(), null);
}
#Override
public void actionPerformed(ActionEvent e) {
i++;
if(i>30)
t.restart();
repaint();
}
}
public class ScoreWindow extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
final public JButton btnScoreReturnButton;
final public JLabel ScoreLabel;
//final public JScrollBar scrollScoreBar;
private String[] data;
Timer t;
String sth="";
int i=0;
int datapower=0;
public ScoreWindow() {
btnScoreReturnButton = new JButton("Powrót");
SpringLayout sl_ScoreWindow = new SpringLayout();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, btnScoreReturnButton, 27, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, btnScoreReturnButton, 11, SpringLayout.WEST, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, btnScoreReturnButton, 100, SpringLayout.WEST, this);
this.setLayout(sl_ScoreWindow);
this.add(btnScoreReturnButton);
ScoreLabel = new JLabel();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, ScoreLabel, 64, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, ScoreLabel, 111, SpringLayout.WEST, this);
sl_ScoreWindow.putConstraint(SpringLayout.SOUTH, ScoreLabel, -15, SpringLayout.SOUTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, ScoreLabel, -76, SpringLayout.EAST, this);
this.add(ScoreLabel);
JLabel SubtitleLabel = new JLabel();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, SubtitleLabel, 20, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, SubtitleLabel, 80, SpringLayout.WEST,ScoreLabel);
sl_ScoreWindow.putConstraint(SpringLayout.SOUTH, SubtitleLabel, 60, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, SubtitleLabel, -150, SpringLayout.EAST, this);
SubtitleLabel.setForeground(Color.BLACK);
SubtitleLabel.setHorizontalAlignment(JLabel.CENTER);
SubtitleLabel.setVerticalAlignment(JLabel.CENTER);
SubtitleLabel.setFont(ScoreLabel.getFont().deriveFont(32.0f));
SubtitleLabel.setText("Najlepsze Wyniki");
this.add(SubtitleLabel);
t=new Timer(100,this);
}
public void ReadData()
{
data = new String[20];
FileReader readFile=null;
BufferedReader reader =null;
String temp;
try
{
readFile=new FileReader("highscore.dat");
reader=new BufferedReader(readFile);
int i=0;
while((temp=reader.readLine())!=null)
{
data[i]=temp;
i++;
}
}
catch(Exception e)
{
data[0] ="Nobody:0";
}
finally
{
try {
if(reader!=null)
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void LoadData() {
String stream="<html>";
//System.out.print(data[0]+"\n");
for(int i=0;i<data.length;i++)
{
if(data[i]!=null)
{
if(i==0)
stream=stream+data[i];
//tream=stream+data[i];
else if(i>0)
stream=stream+"<br>"+data[i];
}
}
stream+="</html>";
System.out.print(stream+"\n");
ScoreLabel.setHorizontalAlignment(JLabel.CENTER);
ScoreLabel.setVerticalAlignment(JLabel.CENTER);
ScoreLabel.setForeground(Color.WHITE);
ScoreLabel.setFont(ScoreLabel.getFont().deriveFont(16.0f));
ScoreLabel.setText(stream);
ScoreLabel.setOpaque(false);
}
public int AmoutofData()
{
String amount[] = ScoreLabel.getText().split("<br>");
return amount.length;
}
public void paintComponent(Graphics g)
{
t.start();
if(i<10)
sth="0"+i;
else
sth=i+"";
Image img2 = new ImageIcon("res\\double\\double_000"+sth+".png").getImage();
g.drawImage(img2, i, i, 100, 100, null);
}
#Override
public void actionPerformed(ActionEvent e) {
i++;
if(i>30)
i=0;
repaint();
}
}
public class BelishaBeacon {
public class Design extends JPanel {
private boolean alternateColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(163, 180, 16, 45);
Rectangle box2 = new Rectangle(163, 225, 16, 45);
Rectangle box3 = new Rectangle(163, 270, 16, 45);
Rectangle box4 = new Rectangle(163, 315, 16, 45);
Rectangle box5 = new Rectangle(163, 360, 16, 45);
Rectangle box6 = new Rectangle(163, 405, 16, 45);
//drawing the shapes
Ellipse2D.Double ball = new Ellipse2D.Double(a, b, 100, 100);
g2.draw(ball);
g2.draw(box1);
g2.draw(box2);
g2.draw(box3);
g2.draw(box4);
g2.draw(box5);
g2.draw(box6);
//coloring the shapes
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.YELLOW);
g2.fill(ball);
if (alternateColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
alternateColors = false;
}
public void alternateColors() {
alternateColors = true;
repaint();
}
}
public BelishaBeacon() {
//frame
JFrame frame = new JFrame();
frame.setSize(330, 550);
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Design shapes = new Design();
JButton jbtFlash = new JButton("Flash");
jbtFlash.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runnable r = new Runnable(){
#Override
public void run(){
while(/* user stops / toggleButton state*/ true)
{
swapColors(); // some method using static boolean
try{
Thread.sleep(500);
}catch(Exception e){}
}
}
private void swapColors() {
boolean swapColors;
Graphics g2;
if (swapColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
} else {
g2.setColor(Color.YELLOW);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
}
};
Thread t = new Thread(r);
t.start();
}});
JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.alternateColors();
}
});
I have created an action listener for my jbutton steady and flash, I am just trying to created a method for swapColors for it to be initialised in the jbutton flash. The swapcolos method initially should alternate between the colours orange and grey
You wrote that you want it to flash every 0.5 seconds.
To do so you need to start new thread for example
jbtFlash.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runnable r = new Runnable(){
#Override
public void run(){
while(/* user stops / toggleButton state*/ true)
{
swapColors(); // some method using static boolean
try{
Thread.sleep(500);
}catch(Exception e){}
}
}
};
Thread t = new Thread(r);
t.start();
}});
if (alternateColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
alternateColors = false;
Should be:
if (alternateColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
} else {
g2.setColor(Color.YELLOW);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
AND
public void alternateColors() {
alternateColors = true;
repaint();
}
Should be:
public void alternateColors() {
//Flip boolean alternateColors
alternateColors = !alternateColors;
repaint();
}
I have created a basic Roulette wheel in Java, and I have a JButton with an ActionListener that spins the wheel. Once I have pressed the button once, it works as intended.
The problem is: Once I press the JButton a second time, it no longer works. I will post my entire code, for anyone who wants to see exactly what I mean.
Bonus Points: Bonus points to whoever can help me with the following things:
Buttons don't appear until after you have either clicked them, or put the window in the background and brought it back up.
For some reason, the spin ALWAYS lands on red. I have a method called randomSpin() which produces an int that is either 21 or 22, and that method DOES work, but for some reason when it's used in the spin method , it always spins 21 times.
WheelBuilder
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.lang.*;
public class WheelBuilder extends JApplet{
public int total = 1000, score, Tbet = 100, last;
public JLabel winning;
public JButton spin, Abet, Sbet;
RouletteWheel wheel = new RouletteWheel();
Graphics page;
public Color color;
public void init()
{
resize(540,600);
spin = new JButton("SPIN!");
spin.addActionListener(new spinListener());
Container cp = getContentPane();
cp.setVisible(true);
cp.setBackground((Color.GREEN).darker().darker());
Abet = new JButton("+BET+");
Abet.addActionListener(new aListener());
Sbet = new JButton("-BET-");
Sbet.addActionListener(new sListener());
cp.add(Sbet);
cp.add(spin);
cp.add(Abet);
cp.setLayout(new FlowLayout(270, 5, 525));
}
public void paint(Graphics page)
{
page.setColor((Color.GREEN).darker().darker());
page.fillRect(0, 0, 1000, 1000);
setBackground((Color.GREEN).darker().darker());
wheel.paintWheel(page, wheel.getStatus());
page.setColor(Color.BLACK);
page.drawString("TOTAL: "+total, 400, 50);
page.drawString("Current Bet: "+Tbet, 400, 25);
page.drawString("Last Spin:", 50, 25);
page.setColor(Color.WHITE);
page.fillOval(260, 75, 20, 20);
page.fillRect(50, 35, 60, 25);
page.setColor(color);
page.drawString(""+last, 70, 52);
}
public class spinListener implements ActionListener
{
Timer tm = new Timer(100, this);
int count = 0;
int countEnd = randomSpin();
public void actionPerformed(ActionEvent e)
{
tm.start();
changeWheel();
if (wheel.getStatus())
{
color = Color.RED;
last = (int)(Math.random()*7)*2+1;
}
else
{
color = Color.BLACK;
last = (int)(Math.random()*7)*2+2;
}
}
public void changeWheel()
{
int countEnd = randomSpin();
if (count <= countEnd)
{
wheel.setStatus(!(wheel.getStatus()));
repaint();
count++;
}
}
public int randomSpin()
{
return ((int)(Math.random()*2)+21);
}
}
public class aListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet <= total-50)
{
Tbet+=50;
}
last = 0;
repaint();
}
}
public class sListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet > 50)
{
Tbet-=50;
}
last = 0;
repaint();
}
}
}
RouletteWheel
import javax.swing.JApplet;
import java.awt.*;
public class RouletteWheel extends JApplet {
public boolean status;
public void paintWheel(Graphics page, boolean status)
{
if (status){
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.BLACK);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.setColor(Color.RED);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
if (!status)
{
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.RED);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
}
public boolean getStatus()
{
return status;
}
public void setStatus(boolean s)
{
status = s;
}
}