Форум программистов, компьютерный форум, киберфорум
Java: GUI, графика
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/4: Рейтинг темы: голосов - 4, средняя оценка - 4.50
]:->
 Аватар для dan41k
102 / 96 / 19
Регистрация: 12.11.2013
Сообщений: 398

Первая программа

18.11.2013, 19:55. Показов 701. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
В общем, начал учить Java недельку назад. Постепенно учусь.) Решил написать программу (типа простой базы), в которая представляет собой фрейм, состоящий из 2-х панелей (верхняя - таблица, нижняя - кнопки (добавить, сохранить в файл, открыть и выход). Пока начал оформлять фрейм (ну тут походу много ума не нужно). Уже появилась 1-я проблема. Вот собственно код:

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
package dan;
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
 
public class MainFrame {
    
    public static void main (String[] args) {
        
        //создаем главный фрейм
        
        CreateMainFrame frame=new CreateMainFrame();
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        
    }
    
}
 
 
class CreateMainFrame extends JFrame {
    
    public static final int DEFAULT_WIDTH=800;
    public static final int DEFAULT_HEIGHT=600;
    
    public CreateMainFrame() {
        
        setTitle ("Outlay");
        setSize (DEFAULT_WIDTH,DEFAULT_HEIGHT);
        
        /*Добавляем 2 панели:
         1 панель(нижняя часть) - кнопки;
         2 панель (центр) - таблица
        */
        
        MainFramePanel1 panel1=new MainFramePanel1();
        add(panel1, BorderLayout.SOUTH);
        
        MainFramePanel2 panel2=new MainFramePanel2();
        add(panel2, BorderLayout.CENTER);
        
    }
    
}
 
 
class MainFramePanel1 extends JPanel {
    
    public MainFramePanel1() {
        
        // Добавляем кнопки
        
        JButton adds = new JButton ("Добавить");
        add(adds);
        JButton open = new JButton ("Открыть");
        add(open);
        JButton save = new JButton ("Сохранить как");
        add(save);
        JButton exit = new JButton ("Выход");
        add(exit);
        
        //Action для adds - открывает новый фрейм в отд. окне
        
        adds.addActionListener(new ActionListener() {
            
            public void actionPerformed (ActionEvent e) {
                
                CreateAddFrame frame=new CreateAddFrame();
                frame.setVisible(true);
                
            }
            
        });
        
        //Action для exit - выход из приложения
        
        exit.addActionListener(new ActionListener() {
            
            public void actionPerformed (ActionEvent e) {
                
                System.exit(0);
                
            }
            
        });
        
    }
 
}
 
 
 
class MainFramePanel2 extends JPanel {
    
    public MainFramePanel2() {
        
// Здесь будет располагаться таблица
        
    }
    
}
 
 
//создание вспомогательного фрейма для кнопки "Добавить"
 
class CreateAddFrame extends JFrame {
    
    public static final int DEFAULT_WIDTH=400;
    public static final int DEFAULT_HEIGHT=400;
    
    public CreateAddFrame() {
        
        setTitle ("Добавление позиции:");
        setSize (DEFAULT_WIDTH, DEFAULT_HEIGHT);
        setLocation (250,100);
        
        // создание панелей для кнопок и тела фрейма
        
        AddFramePanel1 panel1=new AddFramePanel1();
        add(panel1, BorderLayout.SOUTH);
        AddFramePanel2 panel2=new AddFramePanel2();
        add(panel2, BorderLayout.CENTER);
    }
    
}
 
 
class AddFramePanel1 extends JPanel {
    
    public AddFramePanel1() {
        
        JButton save = new JButton("Сохранить");
        add(save);
        JButton cancel = new JButton ("Отменить");
        add(cancel);
        
        cancel.addActionListener (new ActionListener() {
            
            public void actionPerformed (ActionEvent e) {
                
                /* Вот здесь ошибка (логично ^_^)
                 * 
                 * Как вызвать метод setVisible у фрейма из
                 * класса CreateAddFrame?
                 * 
                 */
                
                frame.setVisible (false);
                
            }
            
        });
        
    }
    
}
 
class AddFramePanel2 extends JPanel {
    
    public AddFramePanel2() {
        
        //Здесь будет располагаться тело фрейма
        
    }
    
}
проблема в классе AddFramePanel1. Как соединить фрейм "frame", который создается в классе CreateAddFrame? Этот фрейм появляется при нажатии кнопки "Добавить"(я пытаюсь создать ActionListener на него, чтобы его закрыть.). Буду благодарен, если поможете решить проблему)

Добавлено через 2 часа 38 минут
и ещё вопрос: Нужно ли вообще столько классов? отдельно для панелей и т.д.? а то я теперь совсем запутался с вводом данных...полный провал...(((
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
18.11.2013, 19:55
Ответы с готовыми решениями:

Не запускается первая программа
Здравствуйте, создал программу, назвал ее 'Example.java' и поместил ее в Мои документы. Установил JDK 8.25, в командной строке пишу...

первая программа на java не работает
import java util.*; public class HelloDate { public static void main(String args) { System.out.println("HELLO"); ...

Первая программа. Код не компилируется и не запускается программа.
Первая программа, первая ошибка Здравствуйте! Решил учить С++. Скачал книгу Programming: Principles and Practice Using C++, Бьерн...

2
0 / 0 / 1
Регистрация: 23.07.2013
Сообщений: 36
18.11.2013, 20:26
Посмотри тут

http://download.java.net/media... Frame.html

Добавлено через 1 минуту
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// MainFrame - run an Applet as an application
//
// Copyright (C) 1996 by Jef Poskanzer <jef@acme.com>.  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
// Visit the ACME Labs Java page for up-to-date versions of this and other
// fine Java utilities: [url]http://www.acme.com/java/[/url]
 
package Acme;
 
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import java.io.*;
import java.util.*;
 
/// Run an Applet as an application.
// <P>
// Using this class you can add a trivial main program to any Applet
// and run it directly, as well as from a browser or the appletviewer.
// And unlike some versions of this concept, MainFrame implements both
// images and sound.
// <P>
// Sample main program:
// <BLOCKQUOTE><PRE>
// public static void main( String[] args )
//     {
//     new Acme.MainFrame( new ThisApplet(), args, 400, 400 );
//     }
// </PRE></BLOCKQUOTE>
// The only methods you need to know about are the constructors.
// <P>
// You can specify Applet parameters on the command line, as name=value.
// For instance, the equivalent of:
// <BLOCKQUOTE><PRE>
// &lt;PARAM NAME="pause" VALUE="200"&gt;
// </PRE></BLOCKQUOTE>
// would just be:
// <BLOCKQUOTE><PRE>
// pause=200
// </PRE></BLOCKQUOTE>
// You can also specify three special parameters:
// <BLOCKQUOTE><PRE>
// width=N          Width of the Applet.
// height=N         Height of the Applet.
// barebones=true   Leave off the menu bar and status area.
// </PRE></BLOCKQUOTE>
// <P>
// <A HREF="/resources/classes/Acme/MainFrame.java">Fetch the software.</A><BR>
// <A HREF="/resources/classes/Acme.tar.Z">Fetch the entire Acme package.</A>
 
public class MainFrame extends Frame
    implements Runnable, AppletStub, AppletContext
    {
 
    private String[] args = null;
    private static int instances = 0;
    private String name;
    private boolean barebones = false;
    private Applet applet;
    private Label label = null;
    private Dimension appletSize;
 
    private static final String PARAM_PROP_PREFIX = "parameter.";
 
    /// Constructor with everything specified.
    public MainFrame(
    Applet applet, String[] args, int width, int height )
    {
    build( applet, args, width, height );
    }
 
    /// Constructor with no default width/height.
    public MainFrame( Applet applet, String[] args )
    {
    build( applet, args, -1, -1 );
    }
 
    /// Constructor with no arg parsing.
    public MainFrame( Applet applet, int width, int height )
    {
    build( applet, null, width, height );
    }
 
    // Internal constructor routine.
    private void build(
    Applet applet, String[] args, int width, int height )
    {
    ++instances;
    this.applet = applet;
    this.args = args;
    applet.setStub( this );
    name = applet.getClass().getName();
    setTitle( name );
 
    // Set up properties.
    Properties props = System.getProperties();
    props.put( "browser", "Acme.MainFrame" );
    props.put( "browser.version", "11jul96" );
    props.put( "browser.vendor", "Acme Laboratories" );
    props.put( "browser.vendor.url", "http://www.acme.com/" );
 
    // Turn args into parameters by way of the properties list.
    if ( args != null )
        parseArgs( args, props );
 
    // If width and height are specified in the parameters, override
    // the compiled-in values.
    String widthStr = getParameter( "width" );
    if ( widthStr != null )
        width = Integer.parseInt( widthStr );
    String heightStr = getParameter( "height" );
    if ( heightStr != null )
        height = Integer.parseInt( heightStr );
 
    // Were width and height specified somewhere?
    if ( width == -1 || height == -1 )
        {
        System.err.println( "Width and height must be specified." );
        return;
        }
 
    // Do we want to run bare-bones?
    String bonesStr = getParameter( "barebones" );
    if ( bonesStr != null && bonesStr.equals( "true" ) )
        barebones = true;
 
    if ( ! barebones )
        {
        // Make menu bar.
        MenuBar mb = new MenuBar();
        Menu m = new Menu( "Applet" );
        m.add( new MenuItem( "Restart" ) );
        m.add( new MenuItem( "Clone" ) );
        m.add( new MenuItem( "Close" ) );
        m.add( new MenuItem( "Quit" ) );
        mb.add( m );
        setMenuBar( mb );
        }
 
    // Lay out components.
    setLayout( new BorderLayout() );
    add( "Center", applet );
    if ( ! barebones )
        {
        Panel borderPanel =
        new Acme.Widgets.BorderPanel( Acme.Widgets.BorderPanel.RAISED );
        borderPanel.setLayout( new BorderLayout() );
        label = new Label( "" );
        borderPanel.add( "Center", label );
        add( "South", borderPanel );
        }
 
    // Set up size.
    pack();
    validate();
    appletSize = applet.size();
    applet.resize( width, height );
    show();
 
    // Start a separate thread to call the applet's init() and start()
    // methods, in case they take a long time.
    (new Thread( this )).start();
    }
    
    // Turn command-line arguments into Applet parameters, by way of the
    // properties list.
    private static void parseArgs( String[] args, Properties props )
    {
    for ( int i = 0; i < args.length; ++i )
        {
        String arg = args[i];
        int ind = arg.indexOf( '=' );
        if ( ind == -1 )
        props.put( PARAM_PROP_PREFIX + arg.toLowerCase(), "" );
        else
        props.put(
            PARAM_PROP_PREFIX + arg.substring( 0, ind ).toLowerCase(),
            arg.substring( ind + 1 ) );
        }
    }
 
    /// Event handler for the menu bar.
    public boolean handleEvent( Event evt )
    {
    switch ( evt.id )
        {
        case Event.ACTION_EVENT:
        if ( evt.arg.equals( "Restart" ) )
        {
        applet.stop();
        applet.destroy();
        Thread thread = new Thread( this );
        thread.start();
        }
        else if ( evt.arg.equals( "Clone" ) )
        {
        try
            {
            new MainFrame(
            (Applet) applet.getClass().newInstance(), args,
            appletSize.width, appletSize.height );
            }
        catch ( IllegalAccessException e )
            {
            showStatus( e.getMessage() );
            }
        catch ( InstantiationException e )
            {
            showStatus( e.getMessage() );
            }
        }
        else if ( evt.arg.equals( "Close" ) )
        {
        hide();
        remove( applet );
        applet.stop();
        applet.destroy();
        if ( label != null )
            remove( label );
        dispose();
        --instances;
        if ( instances == 0 )
            System.exit( 0 );
        }
        else if ( evt.arg.equals( "Quit" ) )
        System.exit( 0 );
        break;
 
        case Event.WINDOW_DESTROY:
        System.exit( 0 );
        break;
        }
    return super.handleEvent( evt );
    }
    
 
    // Methods from Runnable.
 
    /// Separate thread to call the applet's init() and start() methods.
    public void run()
    {
    showStatus( name + " initializing..." );
    applet.init();
    validate();
    showStatus( name + " starting..." );
    applet.start();
    validate();
    showStatus( name + " running..." );
    }
 
 
    // Methods from AppletStub.
 
    public boolean isActive()
    {
    return true;
    }
    
    public URL getDocumentBase()
    {
    // Returns the current directory.
    String dir = System.getProperty( "user.dir" );
    String urlDir = dir.replace( File.separatorChar, '/' );
    try
        {
        return new URL( "file:" + urlDir + "/");
        }
    catch ( MalformedURLException e )
        {
        return null;
        }
    }
    
    public URL getCodeBase()
    {
    // Hack: loop through each item in CLASSPATH, checking if
    // the appropriately named .class file exists there.  But
    // this doesn't account for .zip files.
    String path = System.getProperty( "java.class.path" );
    Enumeration st = new StringTokenizer( path, ":" );
    while ( st.hasMoreElements() )
        {
        String dir = (String) st.nextElement();
        String filename = dir + File.separatorChar + name + ".class";
        File file = new File( filename );
        if ( file.exists() )
        {
        String urlDir = dir.replace( File.separatorChar, '/' );
        try
            {
            return new URL( "file:" + urlDir + "/" );
            }
        catch ( MalformedURLException e )
            {
            return null;
            }
        }
        }
    return null;
    }
    
    public String getParameter( String name )
    {
    // Return a parameter via the munged names in the properties list.
    return System.getProperty( PARAM_PROP_PREFIX + name.toLowerCase() );
    }
    
    public void appletResize( int width, int height )
    {
    // Change the frame's size by the same amount that the applet's
    // size is changing.
    Dimension frameSize = size();
    frameSize.width += width - appletSize.width;
    frameSize.height += height - appletSize.height;
    resize( frameSize );
    appletSize = applet.size();
    }
 
    public AppletContext getAppletContext()
    {
    return this;
    }
    
 
    // Methods from AppletContext.
 
    public AudioClip getAudioClip( URL url )
    {
    // This is an internal undocumented routine.  However, it
    // also provides needed functionality not otherwise available.
    // I suspect that in a future release, JavaSoft will add an
    // audio content handler which encapsulates this, and then
    // we can just do a getContent just like for images.
    return new sun.applet.AppletAudioClip( url );
    }
 
    public Image getImage( URL url )
    {
    Toolkit tk = Toolkit.getDefaultToolkit();
    try
        {
        ImageProducer prod = (ImageProducer) url.getContent();
        return tk.createImage( prod );
        }
    catch ( IOException e )
        {
        return null;
        }
    }
    
    public Applet getApplet( String name )
    {
    // Returns this Applet or nothing.
    if ( name.equals( this.name ) )
        return applet;
    return null;
    }
    
    public Enumeration getApplets()
    {
    // Just yields this applet.
    Vector v = new Vector();
    v.addElement( applet );
    return v.elements();
    }
    
    public void showDocument( URL url )
    {
    // Ignore.
    }
    
    public void showDocument( URL url, String target )
    {
    // Ignore.
    }
    
    public void showStatus( String status )
    {
    if ( label != null )
        label.setText( status );
    }
 
    }
0
]:->
 Аватар для dan41k
102 / 96 / 19
Регистрация: 12.11.2013
Сообщений: 398
19.11.2013, 11:01  [ТС]
Аплеты - это чуть не то, что я хотел...я их не использую...

Добавлено через 4 минуты
короче, я изначально начал делать не с той стороны...сначала думаю нужно создать класс с общими переменными, далее как-то соединить их в таблицу, а уж потом на основе их делать ввод...
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
19.11.2013, 11:01
Помогаю со студенческими работами здесь

Первая программа
Здравствуйте форумчане. Только не давно начал изучать delphi(а верней три дня назад D:). Начал составлять первую программку, но возникли...

Первая программа
Ток начал работать в RadASM и компилятор у меня masm32. Вот первая прога как в книге Калашникова которая не запустилась(( CSEG...

Первая программа
Всем привет! Вопрос: почему программа не выводит сообщение? Ведь когда открываю езешник открывается командная строка и сразу тухнет :(. Как...

Первая программа
Здравствуйте. Начал учить Assembler, написал первую программу: mov ax, 8 mov cx, 6 mov dx, cx add dx, ax При компиляции в...

Первая программа
Только начала изучать javascript, первая простенькая программка по учебнику, и она не работает. Что не так? Найти сумму 5 четных чисел,...


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

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru