Форум программистов, компьютерный форум, киберфорум
Java SE (J2SE)
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.88/8: Рейтинг темы: голосов - 8, средняя оценка - 4.88
0 / 0 / 0
Регистрация: 06.04.2017
Сообщений: 20
1

Вызвать метод из другого класса

06.04.2017, 20:29. Показов 1637. Ответов 4
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Всем привет. Подскажите что за магия у меня твориться. Есть программа, в которой есть JFrame с меню и JLabel-ами. Из меню можно открыть картинку и отобразить ее в JInternalFrame (который с 2-мя кнопками, а его код находиться в другом классе). Путь к картинке храниться в названии JInternalFram-а. Создал метод который по щелчку кнопки из JInternalFram-а рисует изображение в JFrame на одном из JLabel-ов.
Теперь проблема: если кнопку размещать в JFram-e то все работает шикарно, но по щелчку кнопки в JInternalFrame ничего не происходит. По коду вроде все кошерно - создал обьект класса и т.д. Не могу понять в чем дело. Может на мне порча)))
Вот SSCCE:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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) {
        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) {
        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(); 
    }
}
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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) {
        DesktopFrame obj = new DesktopFrame();
        if (arg0.getActionCommand().equals("A")) {
            obj.uploadFPImages(arg0.getActionCommand());  
        }
 
        if (arg0.getActionCommand().equals("B")) {
            obj.uploadFPImages(arg0.getActionCommand());
        }
    }      
 }
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
06.04.2017, 20:29
Ответы с готовыми решениями:

Как вызвать из одного класса (для метода типа void) метод типа boolean другого класса?
ребят, только учусь и конечно, вопросов возникает много. ситуация вот в чем. есть массив. я должна...

Как вызвать метод вложенного класса в методе родительского класса
Имеется родительский класс для прорисовки графики Jogj package objects; import...

Вызвать метод из другого приложения
1. Есть JavaFX приложение. 2. Есть JavaFX (или даже обычное) приложение. Мне нужно вызвать с...

Как вызвать метод класса в основном классе
Имеется класс Main и класс Towers public class Main{ public static void main (String args) {...

4
0 / 0 / 0
Регистрация: 06.04.2017
Сообщений: 20
06.04.2017, 20:30  [ТС] 2
И ещё вот этот класс чтобы все заработало.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package Mail;
 
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
 
public class MyImageIO {
 
    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;
    }
 
    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;
    }
}
0
0 / 0 / 0
Регистрация: 06.04.2017
Сообщений: 20
19.04.2017, 16:38  [ТС] 3
Неужели никто ничего не подскажет...
0
51 / 51 / 23
Регистрация: 05.04.2010
Сообщений: 127
19.04.2017, 19:05 4
Сложно было по описанию понять чего вы хотите=)
Вы пытались грузить картинку в новый DesktopFrame, а надо в тот-же
просто сделайте конструктор приватным, а сам класс синглтоном:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
static DesktopFrame instance;
 
 
public static DesktopFrame getInstance() {
    if (instance == null) {
        instance = new DesktopFrame();
    }
    return instance;
}
 
private DesktopFrame() {
 
...
Все вызовы его соответственно поменяйте на
Java
1
DesktopFame desktopFrame = DesktopFrame.getInstance();
1
0 / 0 / 0
Регистрация: 06.04.2017
Сообщений: 20
29.04.2017, 21:11  [ТС] 5
Спасибо!!!
0
29.04.2017, 21:11
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
29.04.2017, 21:11
Помогаю со студенческими работами здесь

Вызвать метод к уже существующему экземпляру класса
Здравствуйте, помогите пожалуйста вызвать метод закрытия, я понимаю что возможно это просто и для...

Метод из другого класса
допустим есть класс Editor и метод editor и есть класс Main с методом main как вызвать метод...

Вызвать метод класса, который находится в другом потоке
Hello, World! :) Зачастил я сегодня с вопросами... В общем у меня есть окно (класс,...

Вызвать метод из класса MyArray при помощи рефлексии
Помогите пожалуйста со следующим вопросом: есть метод в классе MyArray, который надо вызвать при...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru