Fórum Criando uma simples Janela Swing #565381
09/04/2009
0
import javax.swing.JFrame;
public class MeuNote extends JFrame{
. . .
}
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MeuNote extends JFrame{
/* Componentes devem estar no contexto da instância,
para que possam ser acessados em todos os métodos
não-estáticos da classe
*/
private JTextArea texto = new JTextArea();
public MeuNote(){
//Define o título da janela
super("Meu Notepad");
this.montaJanela();
}
private void montaJanela(){
this.getContentPane().add(texto);
}
. . .
}
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MeuNote extends JFrame{
/* Componentes devem estar no contexto da instância,
para que possam ser acessados em todos os métodos
não-estáticos da classe
*/
private JTextArea texto = new JTextArea();
public MeuNote(){
//Define o título da janela
super("Meu Notepad");
this.montaJanela();
}
private void montaJanela(){
this.getContentPane().add(texto);
}
public static void main(String[] args){
//Cria objeto:
MeuNote janela = new MeuNote();
}
}
janela.setVisible(true);
/* A medida de tamanho é em pixels por polegada, igual a da resolução da sua tela */
janela.setSize(640,480);
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MeuNote extends JFrame{
/* Componentes devem estar no contexto da instância,
para que possam ser acessados em todos os métodos
não-estáticos da classe
*/
private JTextArea texto = new JTextArea();
public MeuNote(){
//Define o título da janela
super("Meu Notepad");
this.montaJanela();
}
private void montaJanela(){
this.getContentPane().add(texto);
}
public static void main(String[] args){
//Cria objeto:
MeuNote janela = new MeuNote();
janela.setSize(640,480);
janela.setVisible(true);
}
}
Claudio Silva
Curtir tópico
+ 1Posts
09/04/2009
Ronaldo Luiz
Gostei + 0
09/04/2009
Claudio Silva
import java.wat.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
//Procure no javadoc cada umas das classes que vc. não conhece neste exemplo. Assim vc. saberá em que pacotes elas estão e as conhecerá melhor! ;-)
public class MeuNote extends JFrame{
//Componentes
private JToolBar toolbar = new JToolBar("Ferramentas");
private JMenuBar menubar = new JMenuBar();
private JMenu arquivo = new JMenu("Arquivo");
private JTextArea texto = new JTextArea();
//Ações:
private Action novo = new NovoAction(this.texto);
private Action salvar = new SalvarAction(this.texto);
private Action abrir = new AbrirAction();
public MeuNote(){
super("Meu Notepad");
//Desliga automaticamente a aplicação quando o usuário fecha a janela.
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container interno = this.getContentPane();
this.montaMenu();
this.montaToolBar();
this.montaGUI();
}
private void montaMenu(){
//JMenuItem pode ser construído a partir de um objeto que implementa a interface Action
JMenuItem itemNovo = new JMenuItem(this.novo);
JMenuItem itemSalvar = new JMenuItem(this.salvar);
JMenuItem itemAbrir = new JMenuItem(this.abrir);
this.arquivo.add(itemNovo);
this.arquivo.add(itemSalvar);
this.arquivo.add(itemAbrir);
this.menubar.add(this.arquivo);
this.setJMenuBar(this.menubar);
}
private void montaToolBar(){
//Barras de ferramenta swing também aceitam objetos que implementam Action como parâmetro de construtor
this.toolbar.add(this.novo);
this.toolbar.add(this.salvar);
this.toolbar.add(this.abrir);
}
private void montaGUI(Container interno){
interno.setLayout(new BorderLayout());
interno.add(this.toolbar, BorderLayout.NORTH);
interno.add(new JScrollPane(this.texto));
}
public static void main(String args[]){
//Vc. sabe o que fazer...
}
}
public class NovoAction extends AbstractAction{
private JTextArea texto;
public NovoAction(JTextArea texto){
//Define o nome da ação
super("Novo");
//Define mais algumas características
this.putValue(Action.SMALL_ICON, new ImageIcon("new.gif"));
this.putValue(Action.SHORT_DESCRIPTION, "Limpa a área de texto");
//Consultem a documentação de javax.swing.Action para outras propriedades
}
//Definimos aqui o procedimento que será executado quando NovoAction for acionado
public void actionPerformed(ActionEvent ev){
this.texto.setText("");
}
}public class SalvarAction extends AbstractAction{
private JTextArea texto;
public SalvarAction(JTextArea texto){
//Define o nome da ação
super("Salvar");
//Define mais algumas características
this.putValue(Action.SMALL_ICON, new ImageIcon("save.gif"));
this.putValue(Action.SHORT_DESCRIPTION, "Salva arquivo texto");
//Consultem a documentação de javax.swing.Action para outras propriedades
}
//Definimos aqui o procedimento que será executado quando NovoAction for acionado
public void actionPerformed(ActionEvent ev){
JFileChooser jfc = new JFileChooser();
int resp = jfc.showSaveDialog(this.texto);
if(resp != JFileChooser.APPROVE_OPTION) return;
File arquivo = jfc.getSelectedFile();
this.saveFile(arquivo);
}
//Aqui trabalhamos com classes do java.io
private void saveFile(File f){
try{
FileWriter out = new FileWriter(f);
out.write(this.texto.getText());
out.close();
}catch(IOException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}Gostei + 0
09/04/2009
Dalton
private void saveFile(File f) {
FileWriter out = new FileWriter(f);
out.write(this.texto.getText());
out.close();
} private void montaGUI(Container interno){
interno.setLayout(new BorderLayout());
interno.add(this.toolbar, BorderLayout.NORTH);
interno.add(new JScrollBar(this.texto));
} public MeuNote(){
super("Meu Notepad");
//Desliga automaticamente a aplicação quando o usuário fecha a janela.
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container interno = this.getContentPane();
this.montaMenu();
this.montaToolBar();
this.montaGUI();
} Gostei + 0
09/04/2009
Claudio Silva
Gostei + 0
09/04/2009
Junior.esnaola
Gostei + 0
09/04/2009
Claudio Silva
Gostei + 0
09/04/2009
Claudio Silva
Gostei + 0
09/04/2009
Lich King
Gostei + 0
09/04/2009
Claudio Silva
Gostei + 0
09/04/2009
Lich King
Gostei + 0
09/04/2009
Bugaavila
public class NovoAction extends AbstractAction{
private JTextArea texto;
public NovoAction(JTextArea txt){
super("Novo");
this.putValue(Action.SMALL_ICON, new ImageIcon("new.gif"));
this.putValue(Action.SHORT_DESCRIPTION, "Limpa a área de texto");
/*Aqui objeto de instancia texto recebe o objeto
* da superclasse texto.
*/
texto = txt;
}
...
...
...
package br.est.aca.df.projectSWING;
import java.awt.event.ActionEvent;
import java.io.*;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
public class AbrirAction extends AbstractAction{
private JTextArea texto;
private File file;
public AbrirAction(JTextArea txt){
//Define o nome da ação
super("Abrir");
//Define mais algumas características
this.getValue("Abrir");
this.putValue(Action.SMALL_ICON, new ImageIcon("new.gif"));
this.putValue(Action.SHORT_DESCRIPTION, "Abre arquivo para edição");
texto = txt;
}
public void actionPerformed(ActionEvent ev){
//private String err="";
try{
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(jfc.FILES_ONLY);
int resp = jfc.showOpenDialog(this.texto);
if(resp== jfc.CANCEL_OPTION){
return;
}else{
file = jfc.getSelectedFile();
openFile(file);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e.getMessage(),"Erro na abertura de aquivo",JOptionPane.ERROR_MESSAGE);
}
}
private void openFile(File f){
try{
FileReader rd = new FileReader(f);
int i = rd.read();
String ret="";
while(i!=-1){
ret = ret+(char)i;
i = rd.read();
}
this.texto.setText(ret);
}catch(IOException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
Gostei + 0
09/04/2009
Lich King
Gostei + 0
09/04/2009
Ronaldo Luiz
Gostei + 0
09/04/2009
Lich King
Gostei + 0
09/04/2009
Ronaldo Luiz
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)