repaint()方法在GUI類的開始和結束時都能正常工作,但是當我在另一個類的中間再次調用它時班級不起作用。我一直在尋找並嘗試將近一週。我問同樣的問題之前,但我想讓我在完成他所做的所有事情之後發佈整個程序my old post。所以這是我的整個計劃希望得到一些幫助。當我在另一個類中調用它時,我的repaint()不起作用
package TEST_DiningPhilosophersproblem;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DiningPhilosopherProblem {
// Makes the code more readable.
//===================================================================================================================
//================================================ChopStick class==================================================================
//===================================================================================================================
public static class ChopStick {
// Make sure only one philosopher can have me at any time.
Lock up = new ReentrantLock();
// Who I am.
private final int id;
public ChopStick(int id) {
this.id = id;
}
public boolean pickUp(Philosopher who, String where) throws InterruptedException {
if (up.tryLock(10, TimeUnit.MILLISECONDS)) {
System.out.println(who + " picked up " + where + " " + this);
return true;
}
return false;
}
public void putDown(Philosopher who, String name) {
up.unlock();
System.out.println(who + " put down " + name + " " + this);
}
@Override
public String toString() {
return "Chopstick-" + id;
}
}
public static Graphics g;
// One philosoper.
//===================================================================================================================
//================================================Philosopher class==================================================================
//===================================================================================================================
public static class Philosopher implements Runnable {
// Which one I am.
private final int id;
// The chopsticks on either side of me.
private final ChopStick leftChopStick;
private final ChopStick rightChopStick;
// Am I full?
volatile boolean isTummyFull = false;
// To randomize eat/Think time
private Random randomGenerator = new Random();
// Number of times I was able to eat.
private int noOfTurnsToEat = 0;
private GUI y=new GUI();
private int noOfTurnsToThink = 0;
private int noOfTurnsToHungry = 0;
/**
* **
*
* @param id Philosopher number
*
* @param leftChopStick
* @param rightChopStick
*/
public Philosopher(int id, ChopStick leftChopStick, ChopStick rightChopStick) {
this.id = id;
this.leftChopStick = leftChopStick;
this.rightChopStick = rightChopStick;
}
// GUI GU = new GUI();
@Override
public void run() {
try {
while (!isTummyFull) {
// Think for a bit.
// TDPP.start();
// table.start();
think();
// GU.Test_exit();
System.out.println("think() "+T);
// Make the mechanism obvious.
hungry();
System.out.println("hungry() "+T);
if (leftChopStick.pickUp(this, "left")) {
//asus++;
if (rightChopStick.pickUp(this, "right")) {
// Eat some.
eat();
// Finished.
rightChopStick.putDown(this, "right");
}
// Finished.
leftChopStick.putDown(this, "left");
}
}
// TDPP.exit();
} catch (Exception e) {
// Catch the exception outside the loop.
e.printStackTrace();
}
}
private void think() throws InterruptedException {
System.out.println(this + " is thinking");
// System.out.println(this);
Philosopher s= this;
String g= s.toString();
// Thread.sleep(randomGenerator.nextInt(1000));
//!!!!!
T=0;
//GU.repaint();
noOfTurnsToThink++;
if(g.equals("Philosopher-0")){
asus= asus + noOfTurnsToThink;
}
Thread.sleep(randomGenerator.nextInt(10));
y.rrepaint();
}
//hungry
private void hungry() throws InterruptedException {
T=1;
//GU.paintComponent(g);
//GU.Test_exit();
System.out.println(this + " is hungry");
// Thread.sleep(randomGenerator.nextInt(1000));
//!!!!!!
noOfTurnsToHungry++;
Thread.sleep(randomGenerator.nextInt(10));
y.rrepaint();
}
//end
private void eat() throws InterruptedException {
System.out.println(this + " is eating");
noOfTurnsToEat++;
Thread.sleep(randomGenerator.nextInt(10));
}
// Accessors at the end.
public int getNoOfTurnsToEat() {
return noOfTurnsToEat;
}
//!!!!!!!!
public int getNoOfTurnsToThink() {
return noOfTurnsToThink;
}
public int getNoOfTurnsToHungry() {
return noOfTurnsToHungry;
}
//!!!!!!!!
@Override
public String toString() {
return "Philosopher-" + id;
}
}
//===================================================================================================================
//================================================GUI class==================================================================
//===================================================================================================================
public static class GUI extends JPanel {
private final Dimension PANEL_SIZE = new Dimension(500,500);
private final Color BACKGROUND_COLOR = Color.white;
private JPanel colorPanel = new JPanel();
private JLabel label = new JLabel();
ImageIcon redDevil = new ImageIcon("C:\\Users\\LNU\\Documents\\Java_2013\\1DV012OperatingSystems\\src\\DiningPhilosophersproblem\\pic\\red_Devil.gif");
ImageIcon green_devil = new ImageIcon("C:\\Users\\LNU\\Documents\\Java_2013\\1DV012OperatingSystems\\src\\DiningPhilosophersproblem\\pic\\green_devil.gif");
public GUI() {
setPreferredSize(PANEL_SIZE);
setBackground(BACKGROUND_COLOR);
/* Color panel */
/* Create the button panel */
JPanel buttonSubPanel = createButtonPanel();
add(buttonSubPanel);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
// g=pp;
if(T == 0)
redDevil.paintIcon(this, g, 0, 0);
if(T== 1)
green_devil.paintIcon(this, g, 220, 220);
//System.out.println("!! "+T);
//repaint();
rrepaint();
}
private JPanel createButtonPanel() {
int panelWidth = PANEL_SIZE.width;
int panelHeight = PANEL_SIZE.height/10;
//Dimension panelSize = new Dimension(panelWidth,panelHeight);
JPanel buttonSubPanel = new JPanel();
//buttonSubPanel.setPreferredSize(panelSize);
//buttonSubPanel.setBackground(Color.blue);
/* Create and add the button */
JButton ButtonStart = new JButton("START");
buttonSubPanel.add(ButtonStart);
JButton ButtonExit = new JButton("EXIT");
buttonSubPanel.add(ButtonExit);
/* Add an event handler */
//ButtonStart.addActionListener(new ButtonListener());
ButtonListener listener = new ButtonListener(ButtonStart,ButtonExit);
ButtonStart.addActionListener(listener);
ButtonExit.addActionListener(listener);
return buttonSubPanel;
}
public void rrepaint(){
repaint();
}
/*
* Event handler for the button
*/
private class ButtonListener implements ActionListener {
//private final Random random = new Random();
private JButton Start, Exit;
public ButtonListener(JButton S, JButton E) {
Start = S;
Exit = E;
}
public void actionPerformed(ActionEvent event) {
//TheDiningPhilosophersProblem TDPP = new TheDiningPhilosophersProblem();
if (event.getSource() == Start) {
// public static void main(String args[]) {
ExecutorService executorService = null;
Philosopher[] philosophers = null;
int outnow = 0;
// public void start(){
try {
philosophers = new Philosopher[NO_OF_PHILOSOPHER];
//As many forks as Philosophers
ChopStick[] chopSticks = new ChopStick[NO_OF_PHILOSOPHER];
// Cannot do this as it will fill the whole array with the SAME chopstick.
//Arrays.fill(chopSticks, new ReentrantLock());
for (int i = 0; i < NO_OF_PHILOSOPHER; i++) {
chopSticks[i] = new ChopStick(i);
}
executorService = Executors.newFixedThreadPool(NO_OF_PHILOSOPHER);
for (int i = 0; i < NO_OF_PHILOSOPHER; i++) {
philosophers[i] = new Philosopher(i, chopSticks[i], chopSticks[(i + 1) % NO_OF_PHILOSOPHER]);
executorService.execute(philosophers[i]);
}
// Main thread sleeps till time of simulation
try {
System.out.println("====================================SIMULATION_MILLIS==========================================================");
Thread.sleep(SIMULATION_MILLIS);
// Thread.sleep((Long) null);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Stop all philosophers.
for (Philosopher philosopher : philosophers) {
philosopher.isTummyFull = true;
}
System.out.println("====================================Stop all philosophers==========================================================");
}//end try
finally {
// Close everything down.
executorService.shutdown();
// Wait for all thread to finish
while (!executorService.isTerminated()) {
//Thread.sleep(1000);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("asus = "+asus);
for (Philosopher philosopher : philosophers) {
System.out.println(philosopher);
String PH = philosopher.toString();
if(PH.equals("Philosopher-0"))
System.out.println(philosopher + " avreg "+(double) asus/philosopher.getNoOfTurnsToThink());
}
// Time for check
for (Philosopher philosopher : philosophers) {
System.out.println(philosopher + " => No of Turns to Eat =" + philosopher.getNoOfTurnsToEat());
}
//!!!!!!!!
for (Philosopher philosopher : philosophers) {
System.out.println(philosopher + " => No of Turns to think =" + philosopher.getNoOfTurnsToThink());
}
for (Philosopher philosopher : philosophers) {
System.out.println(philosopher + " => No of Turns to Hungry =" + philosopher.getNoOfTurnsToHungry());
}
//!!!!!!!!
}
}
//}
if (event.getSource() == Exit) { // Clear-button
System.exit(0);
//TDPP.exit();
}
}
}
}
//===================================================================================================================
//================================================Main class==================================================================
//===================================================================================================================
// How many to test with.
private static final int NO_OF_PHILOSOPHER = 5;
//private static final int SIMULATION_MILLIS = 1000 * 60 * 8;
// private static final int SIMULATION_MILLIS = 10 * 10;
private static int asus=0;
private static int T=0;
private static Random random = new Random();
private final static int SIMULATION_MILLIS = random.nextInt(100)*10;
public static void main(String args[]) throws InterruptedException {
JFrame frame = new JFrame("Random Colours");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100,100);
GUI panel= new GUI();
frame.getContentPane().add(panel);
//frame.getContentPane().validate();
//frame.getContentPane().repaint();
frame.pack();
frame.setVisible(true);
}
}
的[重繪複製()簡化版,工作時,我在另一個類中調用它](http://stackoverflow.com/questions/21276337/repaint-doest-work-when-i-call-it-in-another-class)。不要重新發布相同的問題,只需[編輯原創](http://stackoverflow.com/posts/21276337/edit)。 : -/ –
@AndrewThompson由於某些原因,我無法對其進行編輯!你不認爲我嘗試過:/ – user3222289
你無法編輯原始問題真的不是我的問題。 –