МІНІСТЕРСТВО ОСВІТИ ТА НАУКИ УКРАЇНИ
НАЦІОНАЛЬНИЙ УНІВЕРСИТЕТ “ЛЬВІВСЬКА ПОЛІТЕХНІКА”
/
“Основні компоненти графічного інтерфейса”
Звіт
до лабораторної роботи №8
з курсу “Об’єктно-орієнтоване програмування”
ЛЬВІВ 2016
Мета
Одержати навики побудови алгоритмів лінійних обчислювальних процесів, навчитися складати алгоритми та програмувати процеси з розгалуженням, циклами, ітераційними циклами за допомогою мови Java. Одержати навички роботи із масивами.
Індивідуальне завдання
Варіант 6
Малювання прямокутників в графічному вікні. При натисненні кнопки миші фіксується лівий верхній кут прямокутника. При відпуску миші фіксується правий нижній кут прямокутника, і прямокутник промальовувався на екрані.
Текст програми
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.filechooser.FileFilter;
public class Main
{
// малювання
int rezhim=0;
int xPad;
int xf;
int yf;
int yPad;
int thickness;
boolean pressed=false;
// колір
Color maincolor;
MyFrame f;
MyPanel japan;
JButton colorbutton;
JColorChooser tcc;
BufferedImage imag;
boolean loading=false;
String fileName;
public Main()
{
f=new MyFrame("Малювання прямокутника");
f.setSize(350,350);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maincolor=Color.black;
JMenuBar menuBar = new JMenuBar();
f.setJMenuBar(menuBar);
menuBar.setBounds(0,0,350,30);
JMenu fileMenu = new JMenu("Файл");
menuBar.add(fileMenu);
Action loadAction = new AbstractAction("Open")
{
public void actionPerformed(ActionEvent event)
{
JFileChooser jf= new JFileChooser();
int result = jf.showOpenDialog(null);
if(result==JFileChooser.APPROVE_OPTION)
{
try
{
// підстроюємо розміри форми
// і панелі під завантажене зображення
fileName = jf.getSelectedFile().getAbsolutePath();
File iF= new File(fileName);
jf.addChoosableFileFilter(new TextFileFilter(".png"));
jf.addChoosableFileFilter(new TextFileFilter(".jpg"));
imag = ImageIO.read(iF);
loading=true;
f.setSize(imag.getWidth()+40, imag.getWidth()+80);
japan.setSize(imag.getWidth(), imag.getWidth());
japan.repaint();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(f, "Такого файлу не існує");
}
catch (IOException ex) {
JOptionPane.showMessageDialog(f, "java.io.Exception");
}
catch (Exception ex) {
}
}
}
};
JMenuItem loadMenu = new JMenuItem(loadAction);
fileMenu.add(loadMenu);
japan = new MyPanel();
japan.setBounds(30,30,260,260);
japan.setBackground(Color.white);
japan.setOpaque(true);
f.add(japan);
// Тулбар для кнопок
JToolBar colorbar = new JToolBar("Colorbar", JToolBar.VERTICAL);
colorbar.setBounds(30, 0, 260, 30);
colorbutton = new JButton();
colorbutton.setBackground(maincolor);
colorbutton.setBounds(15, 5, 20, 20);
colorbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
ColorDialog coldi = new ColorDialog(f,"Вибір кольору");
coldi.setVisible(true);
}
});
colorbar.add(colorbutton);
JButton redbutton = new JButton();
redbutton.setBackground(Color.red);
redbutton.setBounds(40, 5, 15, 15);
redbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
maincolor = Color.red;
colorbutton.setBackground(maincolor);
}
});
colorbar.add(redbutton);
JButton orangebutton = new JButton();
orangebutton.setBackground(Color.orange);
orangebutton.setBounds(60, 5, 15, 15);
orangebutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
maincolor = Color.orange;
colorbutton.setBackground(maincolor);
}
});
colorbar.add(orangebutton);
JButton yellowbutton = new JButton();
yellowbutton.setBackground(Color.yellow);
yellowbutton.setBounds(80, 5, 15, 15);
yellowbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
maincolor = Color.yellow;
colorbutton.setBackground(maincolor);
}
});
colorbar.add(yellowbutton);
JButton greenbutton = new JButton();
greenbutton.setBackground(Color.green);
greenbutton.setBounds(100, 5, 15, 15);
greenbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
maincolor = Color.green;
colorbutton.setBackground(maincolor);
}
});
colorbar.add(greenbutton);
JButton bluebutton = new JButton();
bluebutton.setBackground(Color.blue);
bluebutton.setBounds(120, 5, 15, 15);
bluebutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
maincolor = Color.blue;
colorbutton.setBackground(maincolor);
}
});
colorbar.add(bluebutton);
JButton cyanbutton = new JButton();
cyanbutton.setBackground(Color.cyan);
cyanbutton.setBounds(140, 5, 15, 15);
cyanbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
maincolor = Color.cyan; colorbutton.setBackground(maincolor);
}
});
colorbar.add(cyanbutton);
JButton magentabutton = newJButton(); magentabutton.setBackground(Color.magenta);
magentabutton.setBounds(160, 5, 15,15); magentabutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
maincolor = Color.magenta; colorbutton.setBackground(maincolor);
}
});
colorbar.add(magentabutton);
JButton whitebutton = new JButton();
whitebutton.setBackground(Color.white);
whitebutton.setBounds(180, 5, 15, 15);
whitebutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
maincolor = Color.white;
colorbutton.setBackground(maincolor);
}
});
colorbar.add(whitebutton);
JButton blackbutton = new JButton();
blackbutton.setBackground(Color.black);
blackbutton.setBounds(200, 5, 15, 15);
blackbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
maincolor = Color.black;
colorbutton.setBackground(maincolor);
}
});
colorbar.add(blackbutton);
colorbar.setLayout(null);
f.add(colorbar);
tcc = new JColorChooser(maincolor);
tcc.getSelectionModel().addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
maincolor = tcc.getColor();
colorbutton.setBackground(maincolor);
}
});
japan.addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
if (pressed==true)
{
Graphics g = imag.getGraphics();
Graphics2D g2 = (Graphics2D)g;
g2.setColor(maincolor);
xPad=e.getX();
yPad=e.getY();
}
japan.repaint();
}
});
japan.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
Graphics g = imag.getGraphics();
Graphics2D g2 = (Graphics2D)g;
g2.setColor(maincolor);
}
public void mousePressed(MouseEvent e) {
xPad=e.getX();
yPad=e.getY();
xf=e.getX();
yf=e.getY();
pressed=true;
}
public void mouseReleased(MouseEvent e) {
Graphics g = imag.getGraphics();
Graphics2D g2 = (Graphics2D)g;
g2.setColor(maincolor);
// Розрахунки для овал і прям
int x1=xf, x2=xPad, y1=yf, y2=yPad;
if(xf>xPad)
{
x2=xf; x1=xPad;
}
if(yf>yPad)
{
y2=yf; y1=yPad;
}
g.drawRect(x1, y1, (x2-x1), (y2-y1));
xf=0; yf=0;
pressed=false;
japan.repaint();
}
});
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}
class ColorDialog extends JDialog
{
public ColorDialog(JFrame owner, String title)
{
super(owner, title, true);
add(tcc);
setSize(200, 200);
}
}
class MyFrame extends JFrame
{
public void paint(Graphics g)
{
super.paint(g);
}
public MyFrame(String title)
{
super(title);
}
}
class MyPanel extends JPanel
{
public MyPanel()
{ }
public void paintComponent (Graphics g)
{
if(imag==null)
{
imag = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D d2 = (Graphics2D) imag.createGraphics();
d2.setColor(Color.white);
d2.fillRect(0, 0, this.getWidth(), this.getHeight());
}
super.paintComponent(g);
g.drawImage(imag, 0, 0,this);
}
}
// Фільтр картинок
class TextFileFilter extends FileFilter
{
private String ext;
public TextFileFilter(String ext)
{
this.ext=ext;
}
public boolean accept(java.io.File file)
{
if (file.isDirectory()) return true;
return (file.getName().endsWith(ext));
}
public String getDescription()
{
return "*"+ext;
}
}
Результат виконання програми
/
Висновок
Виконав[ім’я автора приховано]тераційними циклами за допомогою мови Java. Одержати навички роботи із масивами.