このページのコンテンツ一覧(5個位までにしてください。上が最新で下が最古です)
JDK6.0で作成。
// FigureCanvasDemo.java import java.awt.Dimension; import javax.swing.JFrame; public class FigureCanvasDemo { public static void main(String[] args) { JFrame frame = new JFrame("FigureCanvas"); FigureCanvas canvas = new FigureCanvas(); canvas.setPreferredSize( new Dimension(300, 300) ); frame.getContentPane().add(canvas); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); JFrame frame2 = new JFrame("FigureCanvas2"); FigureCanvas2 canvas2 = new FigureCanvas2(); canvas2.setPreferredSize( new Dimension(300, 300) ); frame2.getContentPane().add(canvas2); frame2.pack(); frame2.setLocationByPlatform(true); frame2.setVisible(true); } }
// FigureCanvas.java import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JComponent; public class FigureCanvas extends JComponent implements MouseListener, MouseMotionListener { protected int shapeLeftUpX, shapeLeftUpY; protected int mouseDownX, mouseDownY; protected int shapeWidth, shapeHeight; public static int STATE_MOUSE_RELEASED= 0; public static int STATE_MOUSE_PRESSED = 1; public static int STATE_MOUSE_DRAGGED = 2; protected int state = STATE_MOUSE_RELEASED; public FigureCanvas() { addMouseListener(this); addMouseMotionListener(this); } public void paintComponent(Graphics g) { g.drawRect(shapeLeftUpX, shapeLeftUpY, shapeWidth, shapeHeight); if( state == STATE_MOUSE_DRAGGED ) { g.drawOval(shapeLeftUpX, shapeLeftUpY, shapeWidth, shapeHeight); } else if( state == STATE_MOUSE_RELEASED ) { g.fillOval(shapeLeftUpX, shapeLeftUpY, shapeWidth, shapeHeight); } } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { shapeLeftUpX = e.getX(); shapeLeftUpY = e.getY(); mouseDownX = e.getX(); mouseDownY = e.getY(); state = STATE_MOUSE_PRESSED; } public void mouseReleased(MouseEvent e) { if( state == STATE_MOUSE_DRAGGED ) { state = STATE_MOUSE_RELEASED; repaint(); } } public void mouseDragged(MouseEvent e) { shapeWidth = e.getX() - shapeLeftUpX; shapeHeight = e.getY() - shapeLeftUpY; state = STATE_MOUSE_DRAGGED; repaint(); } public void mouseMoved(MouseEvent e) {} }
// FigureCanvas2.java import java.awt.event.MouseEvent; public class FigureCanvas2 extends FigureCanvas { public void mouseDragged(MouseEvent e) { shapeWidth = Math.abs(e.getX() - mouseDownX); shapeHeight = Math.abs(e.getY() - mouseDownY); shapeLeftUpX = (e.getX() < mouseDownX) ? e.getX() : mouseDownX; shapeLeftUpY = (e.getY() < mouseDownY) ? e.getY() : mouseDownY; state = STATE_MOUSE_DRAGGED; repaint(); } }
Stateパターンを適用してみた.
// FigureCanvasDemo.java import java.awt.Dimension; import javax.swing.JFrame; public class FigureCanvasDemo { public static void main(String[] args) { JFrame frame = new JFrame("FigureCanvas"); FigureCanvas canvas = new FigureCanvas(); canvas.setPreferredSize( new Dimension(300, 300) ); frame.getContentPane().add(canvas); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); JFrame frame2 = new JFrame("FigureCanvas2"); FigureCanvas2 canvas2 = new FigureCanvas2(); canvas2.setPreferredSize( new Dimension(300, 300) ); frame2.getContentPane().add(canvas2); frame2.pack(); frame2.setLocationByPlatform(true); frame2.setVisible(true); } }
// FigureCanvas.java import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JComponent; public class FigureCanvas extends JComponent implements MouseListener, MouseMotionListener { protected int shapeLeftUpX, shapeLeftUpY; protected int mouseDownX, mouseDownY; protected int shapeWidth, shapeHeight; protected MouseState currentState; public static final MouseState RELEASED = new MouseReleased(); public static final MouseState PRESSED = new MousePressed(); public static final MouseState DRAGGED = new MouseDragged(); public FigureCanvas() { addMouseListener(this); addMouseMotionListener(this); currentState = FigureCanvas.RELEASED; } public void paintComponent(Graphics g) { // draw a rectangle g.drawRect(shapeLeftUpX, shapeLeftUpY, shapeWidth, shapeHeight); // draw an oval currentState.drawOval(g, this); } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { shapeLeftUpX = e.getX(); shapeLeftUpY = e.getY(); mouseDownX = e.getX(); mouseDownY = e.getY(); currentState = PRESSED; } public void mouseReleased(MouseEvent e) { if( currentState == DRAGGED ) { currentState = RELEASED; repaint(); } } public void mouseDragged(MouseEvent e) { shapeWidth = e.getX() - shapeLeftUpX; shapeHeight = e.getY() - shapeLeftUpY; currentState = DRAGGED; repaint(); } public void mouseMoved(MouseEvent e) {} }
// FigureCanvas2.java import java.awt.event.MouseEvent; public class FigureCanvas2 extends FigureCanvas { public void mouseDragged(MouseEvent e) { shapeWidth = Math.abs(e.getX() - mouseDownX); shapeHeight = Math.abs(e.getY() - mouseDownY); shapeLeftUpX = (e.getX() < mouseDownX) ? e.getX() : mouseDownX; shapeLeftUpY = (e.getY() < mouseDownY) ? e.getY() : mouseDownY; currentState = DRAGGED; repaint(); } }
// MouseState.java import java.awt.Graphics; public interface MouseState { void drawOval(Graphics g, FigureCanvas canvas); }
// MouseReleased.java import java.awt.Graphics; public class MouseReleased implements MouseState { public void drawOval(Graphics g, FigureCanvas c) { g.fillOval(c.shapeLeftUpX, c.shapeLeftUpY, c.shapeWidth, c.shapeHeight); } }
// MousePressed.java import java.awt.Graphics; public class MousePressed implements MouseState { public void drawOval(Graphics g, FigureCanvas c) { // do nothing. } }
// MouseDragged.java import java.awt.Graphics; public class MouseDragged implements MouseState { public void drawOval(Graphics g, FigureCanvas c) { g.drawOval(c.shapeLeftUpX, c.shapeLeftUpY, c.shapeWidth, c.shapeHeight); } }
JDK6.0で作成。
// PrimeDemo.java public class PrimeDemo { public static void main(String[] args) { PrimeFrame frame = new PrimeFrame("Primes"); frame.setSize(300, 200); frame.setDefaultCloseOperation(PrimeFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
// PrimeFrame.java import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class PrimeFrame extends JFrame implements ActionListener { JTextField inputField; JButton executeButton, clearButton; JLabel resultLabel1, resultLabel2; public PrimeFrame(String s) { super(s); inputField = new JTextField("input an integer"); inputField.selectAll(); executeButton = new JButton("execute"); executeButton.addActionListener(this); clearButton = new JButton("clear"); clearButton.addActionListener(this); resultLabel1 = new JLabel(); resultLabel2 = new JLabel(); JPanel p1 = new JPanel( new BorderLayout() ); JPanel p2 = new JPanel( new FlowLayout() ); JPanel p3 = new JPanel( new GridLayout(3, 1) ); p1.add( inputField, BorderLayout.CENTER ); p2.add( executeButton ); p2.add( clearButton ); p1.add( p2, BorderLayout.EAST ); p3.add( p1 ); p3.add( resultLabel1 ); p3.add( resultLabel2 ); getContentPane().add(p3); } public void actionPerformed(ActionEvent e) { if( e.getSource() == executeButton ) { String errorMessage = null; int number = 0; try { number = Integer.parseInt(inputField.getText()); if( number < 2 || number > 1000 ) errorMessage = "You must input an integer from 2 to 1000."; } catch( NumberFormatException nfe ) { errorMessage = "You must input an integer from 2 to 1000."; } if( errorMessage != null ) { JOptionPane.showMessageDialog(this, errorMessage, null, JOptionPane.ERROR_MESSAGE); } else { int count = 0, sum = 0; for( int i=2; i<=number; i++ ) { // judge whether the number i is prime boolean isPrime = true; for( int j=2; j<(Math.sqrt(i)+1); j++ ) { if( i == 2 ) { isPrime = true; break; } if( i%j == 0 ) { isPrime = false; break; } } if( isPrime ) { count++; sum += i; } } resultLabel1.setText("the numbers of primes from 1 to " + number + " is: " + count); resultLabel2.setText("the sum is: " + sum ); } } else if( e.getSource() == clearButton ) { inputField.setText(""); resultLabel1.setText(""); resultLabel2.setText(""); } } }
JDK6.0で作成。
// QuizDemo.java public class QuizDemo { public static void main(String[] args) { QuizFrame frame = new QuizFrame("三択クイズ"); frame.setSize(500, 300); frame.setVisible(true); frame.startQuestion(); } }
// QuizFrame.java import java.awt.BorderLayout; import java.awt.Button; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; public class QuizFrame extends Frame implements ActionListener, Runnable { ArrayList<Question> questions; Question nowQuestion; Label countLabel, timeLabel, questionLabel, statusLabel; Button[] buttons; Button result; Thread currentThread; int count, correct; long erapsed; String message = ""; public QuizFrame(String s) { super(s); createQuestions(); createComponents(); } private void createQuestions() { questions = new ArrayList<Question>(); questions.add( new Question( "日本の首都は?", "東京", new String[]{ "東京", "大阪", "名古屋", } ) ); questions.add( new Question( "インドの首都は?", "ニューデリー", new String[]{ "ニューデリー", "カルカッタ", "ムンバイ", } ) ); questions.add( new Question( "英雄ポロネーズの作者は?", "ショパン", new String[]{ "ショパン", "リスト", "ベートーベン", } ) ); questions.add( new Question( "2007年箱根駅伝の総合優勝大学は?", "順大", new String[]{ "順大", "日大", "山学", } ) ); questions.add( new Question( "2006年オールザッツ漫才優勝コンビは?", "とろサーモン", new String[]{ "とろサーモン", "ジャルジャル", "ギャロップ", } ) ); Collections.shuffle(questions); } private void createComponents() { Panel p1 = new Panel(new GridLayout(1, 2)); Panel p2 = new Panel(new GridLayout(3, 1)); Panel p3 = new Panel(new GridLayout(1, 3)); countLabel = new Label(); timeLabel = new Label(); p1.add( countLabel ); p1.add( timeLabel ); questionLabel = new Label(); buttons = new Button[3]; for( int i=0; i<buttons.length; i++ ) { buttons[i] = new Button(); buttons[i].addActionListener(this); p3.add( buttons[i] ); } statusLabel = new Label(); result = new Button("結果"); result.setEnabled(false); p2.add( p3 ); p2.add( statusLabel ); p2.add( result ); this.setLayout( new BorderLayout() ); add( p1, BorderLayout.NORTH ); add( questionLabel, BorderLayout.CENTER ); add( p2, BorderLayout.SOUTH ); } long start; public void startQuestion() { for( count=0; count<questions.size(); count++ ) { currentThread = new Thread(this); currentThread.start(); start = System.currentTimeMillis(); synchronized (this) { try { wait(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } for( int i=0; i<buttons.length; i++ ) { buttons[i].removeActionListener(this); } result.setEnabled(true); result.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { statusLabel.setText( correct + "問正解 正答率" + (correct*100)/questions.size() + "% 正解した問題の平均所要時間: " + (erapsed*1.0/correct) + "msecs." ); } } ); } public void run() { if(message == null)statusLabel.setText("時間切れ"); message = null; nowQuestion = questions.get(count); countLabel.setText("第" + (count+1) + "問"); questionLabel.setText( nowQuestion.getQuestionBody() ); for( int j=0; j<nowQuestion.getChoices().length; j++ ) { buttons[j].setLabel(nowQuestion.getChoices()[j]); } } public void actionPerformed(ActionEvent e) { long end = System.currentTimeMillis(); synchronized(this) { notify(); } // correct if( ((Button)e.getSource()).getLabel().equals(nowQuestion.getAnswer()) ) { message = "正解! 所要時間 " + (end-start) + "msecs."; correct++; erapsed += (end-start); // wrong } else { message = "残念..."; } statusLabel.setText(message); } }
// Question.java public class Question { private String questionBody; private String answer; private String[] choices; public Question(String questionBody, String answer, String[] choices) { this.questionBody = questionBody; this.answer = answer; this.choices = choices; } public String getAnswer() { return answer; } public String[] getChoices() { return choices; } public String getQuestionBody() { return questionBody; } }
JDK5.0で作成。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; interface iTelephone { void call(String num); void talk(String s); String listen(); void hang_up(); } class PCMogiTel implements iTelephone { /** この電話が使用中か否か */ private boolean using = false; public void call(String num) { if( using ) { System.out.println( "この電話は使用中です..." ); } else { using = true; System.out.println( num + "に電話をかけています..." ); } } public void hang_up() { if( using ) { System.out.println( "電話を切ります。" ); using = false; } } public String listen() { System.out.print( "> " ); BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); String message = null; try { message = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return message; } public void talk(String s) { System.out.println( s ); } } class TelTest { public static void main(String args[]) { iTelephone tel = new PCMogiTel(); tel.call("090-1234-5678"); tel.call("090-8765-4321"); tel.talk("もしもし"); System.out.println(tel.listen()); tel.talk("お元気ですか?"); System.out.println(tel.listen()); tel.talk("そうですか。それではまた。"); tel.hang_up(); } }
JDK5.0で作成。
// HexagonDrawer.java public class HexagonDrawer { public static void main(String[] args) { HexagonDrawerFrame frame = new HexagonDrawerFrame(); frame.setTitle("Hexagon Drawer"); frame.setSize(400, 400); frame.setVisible( true ); frame.setDefaultCloseOperation( HexagonDrawerFrame.EXIT_ON_CLOSE ); } }
// HexagonDrawerFrame.java import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.swing.JFrame; public class HexagonDrawerFrame extends JFrame implements MouseListener { private int[] xPoints = new int[6]; private int[] yPoints = new int[6]; private int nPoints; private File file; public HexagonDrawerFrame() { addMouseListener(this); } public void mouseClicked(MouseEvent e) { System.out.println( e.getX() + ":" + e.getY() ); Graphics g = this.getGraphics(); g.drawString(e.getX() + ":" + e.getY(), e.getX(), e.getY()); xPoints[nPoints] = e.getX(); yPoints[nPoints] = e.getY(); nPoints++; if( nPoints == 6 ) { g.setColor(Color.BLUE); g.fillPolygon(xPoints, yPoints, nPoints); file = new File("coordinate.txt"); BufferedWriter bw = null; try { bw = new BufferedWriter( new FileWriter(file) ); StringBuffer buf = new StringBuffer(); for( int i=0; i<nPoints; i++ ) { buf.append( xPoints[i] + " " + yPoints[i] + " " ); } bw.write(buf.toString()); bw.flush(); } catch (IOException e1) { e1.printStackTrace(); } finally { if( bw != null ) { try { bw.close(); } catch (IOException e1) { } } } } } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} }