Новичок
Профиль
Группа: Участник
Сообщений: 6
Регистрация: 24.1.2017
Репутация: нет Всего: нет
|
Доброго времени суток. Я столкнулся с довольно интересным случаем. Думаю вы мне поможете разобраться. Пытаюсь вызвать метод из JInternalFram-а по нажатию кнопки (которая находиться в нем). Для этого создаю обьект класса и обращаюсь через него. Метод работает если обращаюсь к нему из "родного" класса, но отказывается работать когда вызываю его из класса, где находиться JInternalFrame. Подскажите в чем дело. Вот код (сократил насколько это возможно). Скомпилируйте и запустите. Метод работает если нажать Menu -> Open(выберите изображение), а затем в меню Click_me -> It_works_from_here), и не работает если нажать Menu -> Open(выберите изображение), а затем на вызванном JInternalFrame кнопку А или В. Не смотрите что кода много, там все просто. По сути есть метод к которому обращаются через меню и через кнопку во внутреннем окне. Код | package Mail;
import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.beans.*; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter;
public class MyMain {
public static void main(String[] args) {
if (args.length!=0) { System.out.println("java imageProgram"); System.exit(1); }
EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new DesktopFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
@SuppressWarnings("serial") class DesktopFrame extends JFrame {
JDesktopPane desktop; private JDesktopPane borderDesktop; private int nextFrameX; private int nextFrameY; private int frameDistance; private static final int DEFAULT_WIDTH = 600; private static final int DEFAULT_HEIGHT = 550; static int[][][] testImage={null}; static int Maxrows = 0; static int Maxcols = 0; static File file;
JScrollPane UpdateImageInFrame; final String path[] = {null}; JLabel ImageAlabel; JLabel ImageBlabel; Icon iconFPImage;
public DesktopFrame() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
desktop = new JDesktopPane(); add(desktop,BorderLayout.CENTER); borderDesktop=new JDesktopPane();
JLabel ImageAlabeltext = new JLabel("Preview A:"); JLabel ImageBlabeltext = new JLabel("Preview B:"); ImageAlabel = new JLabel(); ImageAlabel.setPreferredSize(new Dimension(200, 200)); ImageAlabel.setBorder(BorderFactory.createEtchedBorder()); ImageBlabel = new JLabel(); ImageBlabel.setPreferredSize(new Dimension(200, 200)); ImageBlabel.setBorder(BorderFactory.createEtchedBorder());
GroupLayout layout = new GroupLayout(borderDesktop); borderDesktop.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setHorizontalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(ImageAlabeltext) .addComponent(ImageAlabel,GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(ImageBlabeltext) .addComponent(ImageBlabel,GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ) ); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(ImageAlabeltext) .addComponent(ImageAlabel,GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(ImageBlabeltext) .addComponent(ImageBlabel,GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ); layout.linkSize(SwingConstants.HORIZONTAL, ImageAlabel, ImageBlabel);
desktop.setBackground(Color.WHITE); borderDesktop.setBackground(Color.LIGHT_GRAY); JSplitPane splitPaneHor = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPaneHor.setResizeWeight(1); splitPaneHor.setEnabled(false); splitPaneHor.setDividerSize(0); splitPaneHor.add(desktop); splitPaneHor.add(borderDesktop); add(splitPaneHor, BorderLayout.CENTER);
JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); JMenuItem openItem = new JMenuItem("Open"); fileMenu.add(openItem);
fileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem("Exit"); fileMenu.add(exitItem);
JMenu moreMenu = new JMenu("Click me"); menuBar.add(moreMenu); JMenuItem aboutItem = new JMenuItem("It works from here"); moreMenu.add(aboutItem);
path[0]="d:/"; openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileopen = new JFileChooser(); fileopen.setMultiSelectionEnabled(true); fileopen.setCurrentDirectory(new java.io.File(path[0])); fileopen.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "jpeg", "gif", "bmp"));
int result = fileopen.showDialog(desktop, null); if (result == JFileChooser.APPROVE_OPTION) { path[0] = fileopen.getSelectedFile().toString(); file = fileopen.getSelectedFile(); } else if (result == JFileChooser.CANCEL_OPTION) { return; }
try { testImage = MyImageIO.loadImage(path[0]); } catch (InterruptedException e1) { e1.printStackTrace(); }
if(testImage!=null) { UpdateImageInFrame = new JScrollPane(new MyInternalFrame(testImage)); createInternalFrame(UpdateImageInFrame,path[0]);
Maxrows = testImage.length; Maxcols = testImage[0].length; } } });
exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } });
aboutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { uploadFPImages("A"); } });
}
public void createInternalFrame(Component c, String t) { JInternalFrame iframe = new JInternalFrame(t, true, true, true, true); iframe.add(c, BorderLayout.CENTER); desktop.add(iframe);
iframe.addVetoableChangeListener(new VetoableChangeListener() { public void vetoableChange(PropertyChangeEvent event) throws PropertyVetoException { String name = event.getPropertyName(); Object value = event.getNewValue(); if(name.equals("closed") && value.equals(true)) {
Object[] options = {"Y", "N"}; int result = JOptionPane.showOptionDialog(desktop, " Confirm", "Close?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if(result != JOptionPane.YES_OPTION) { throw new PropertyVetoException("User canceled close", event); } } } });
int width = desktop.getWidth() / 2; int height = desktop.getHeight() / 2; iframe.reshape(nextFrameX, nextFrameY, width, height); iframe.show();
try { iframe.setSelected(true); } catch(PropertyVetoException e) {}
frameDistance = iframe.getHeight() - iframe.getContentPane().getHeight();
nextFrameX += frameDistance; nextFrameY += frameDistance; if(nextFrameX + width > desktop.getWidth()) nextFrameX = 0; if(nextFrameY + height > desktop.getHeight()) nextFrameY = 0; }
public void uploadFPImages(String valueCommand) { // TODO // Problem starts from here ))) String pathToImage = desktop.getSelectedFrame().getTitle();
if(pathToImage != null) { if(pathToImage != "Buffer data") { BufferedImage img; try { img = ImageIO.read(new File(pathToImage)); if (img==null) { System.err.println("Can not read the image: "+pathToImage); return; } float width = img.getWidth(); float height = img.getHeight(); float scale = height / width; width = 200;
height = (width * scale); iconFPImage = new ImageIcon(img.getScaledInstance(Math.max(1, (int)width), Math.max(1, (int)height), Image.SCALE_SMOOTH)); if (valueCommand=="A"){ ImageAlabel.setIcon(iconFPImage); } else if (valueCommand=="B") { ImageBlabel.setIcon(iconFPImage); } else { System.err.println("Unknown command. valueCommand ="+valueCommand); } } catch (IOException e) { e.printStackTrace(); } } else { return; } } else { System.err.println("Can not read the image. pathtoimage="+pathToImage); } this.repaint(); }
}
|
Код | package Mail;
import java.awt.image.*; import java.io.*; import javax.imageio.ImageIO;
public class MyImageIO {
// ****************************** loadImage ********************************** public static int[][][] loadImage(String path) throws InterruptedException {
BufferedImage originalImage; int width; int height; int[][][] imagePixels;
try { originalImage=ImageIO.read(new File(path));
width = originalImage.getWidth(); height = originalImage.getHeight();
imagePixels = new int [width][height][4]; int curColor;
for (int i = 0 ; i < width ; ++i) { for (int j = 0 ; j < height ; ++j) { curColor = originalImage.getRGB(i,j); int R = (curColor >>16 ) & 0xFF; int G = (curColor >> 8 ) & 0xFF; int B = (curColor ) & 0xFF; imagePixels[i][j][0]=R; imagePixels[i][j][1]=G; imagePixels[i][j][2]=B; } }
return imagePixels;
} catch (IOException e) { e.printStackTrace(); }
return null; }
// ******************************* OutputToScrn ************************************ public static BufferedImage outputToScrn(int[][][] imagePixels){
int height = imagePixels.length; int width = imagePixels[0].length; int[][] flat = new int[width*height][4];
int index=0; for(int row=0; row<height; row++) { for(int col=0; col<width; col++) { for(int rgbo=0; rgbo<4; rgbo++) { flat[index][rgbo]=imagePixels[row][col][rgbo]; } index++; } }
int[] outPixels = new int[flat.length]; for(int j=0; j<flat.length; j++) { outPixels[j] = ((flat[j][0]&0xff)<<16) | ((flat[j][1]&0xff)<<8) | (flat[j][2]&0xff) | ((flat[j][3]&0xff)<<24); }
BufferedImage buffimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); buffimg.setRGB(0, 0, width, height, outPixels, 0, width);
return buffimg;
} }
|
Код | package Mail;
import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JPanel; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
@SuppressWarnings("serial") public class MyInternalFrame extends JPanel implements ActionListener {
BufferedImage image; JButton IntF_ButtonA; JButton IntF_ButtonB; DesktopFrame callDesktopFrame = new DesktopFrame(); static String pathToImage = "";
public MyInternalFrame(int [][][] testImage) {
image = MyImageIO.outputToScrn(testImage);
GridBagConstraints GLayout = new GridBagConstraints(); setLayout(new GridBagLayout());
IntF_ButtonA = new JButton("A"); IntF_ButtonA.setActionCommand("A"); GLayout.fill = GridBagConstraints.HORIZONTAL; GLayout.ipady = 0; GLayout.ipadx = 0; GLayout.weighty = 1.0; GLayout.anchor = GridBagConstraints.PAGE_END; GLayout.insets = new Insets(10,0,0,0); GLayout.gridx = 0; GLayout.gridy = 1; GLayout.gridwidth = 1; add(IntF_ButtonA, GLayout); IntF_ButtonA.addActionListener(this);
IntF_ButtonB = new JButton("B"); IntF_ButtonB.setActionCommand("B"); GLayout.fill = GridBagConstraints.HORIZONTAL; GLayout.ipady = 0; GLayout.ipadx = 0; GLayout.weighty = 1.0; GLayout.anchor = GridBagConstraints.PAGE_END; GLayout.insets = new Insets(10,0,0,0); GLayout.gridx = 1; GLayout.gridy = 1; GLayout.gridwidth = 1; add(IntF_ButtonB, GLayout); IntF_ButtonB.addActionListener(this); }
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2= (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
int width = getWidth(); int height = getHeight(); int iwidth = image.getWidth(); int iheight = image.getHeight();
double xScale = (double)width/iwidth; double yScale = (double)height/iheight; double scale = Math.min(xScale, yScale);
int width2 = (int)(scale*iwidth); int height2 = (int)(scale*iheight);
int x = (width - width2)/2; int y = (height - height2)/2; g2.drawImage(image, x, y, width2, height2, this);
}
@Override public void actionPerformed(ActionEvent arg0) { // TODO // Bug is near (at least, i want to believe) DesktopFrame obj = new DesktopFrame();
if (arg0.getActionCommand().equals("A")) { obj.uploadFPImages(arg0.getActionCommand()); }
if (arg0.getActionCommand().equals("B")) { obj.uploadFPImages(arg0.getActionCommand()); } }
}
|
Добавлено через 3 минуты и 31 секундуСам метод называется uploadFPImages и находиться в листинге 1. Листинг 2 просто "до кучи" чтоб все работало. Там все ОК. В листинге 3 находиться злополучный JInternlFrame с кнопками.
|