java open a frame from another class - java

So I am trying to just make it so when I click a button it will open a frame from another class my filechooser frame just won't open.
This is the class called mainFrame:
package javatut;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class mainFrame {
private JFrame frmMainwindow;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFrame window = new mainFrame();
window.frmMainwindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainFrame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmMainwindow = new JFrame();
frmMainwindow.setTitle("Mainwindow");
frmMainwindow.setBounds(100, 100, 280, 150);
frmMainwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMainwindow.getContentPane().setLayout(null);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
myButtonAction();
}
});
btnBrowse.setBounds(155, 11, 100, 23);
frmMainwindow.getContentPane().add(btnBrowse);
textField = new JTextField();
textField.setBounds(10, 12, 135, 20);
frmMainwindow.getContentPane().add(textField);
textField.setColumns(10);
}
private void myButtonAction(){
Toolkit.getDefaultToolkit().beep();
}
}
And this is the FileChooser class called simply frame:
package javatut;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class frame {
private JFrame frmFilechooser;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame window = new frame();
window.frmFilechooser.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmFilechooser = new JFrame();
frmFilechooser.setTitle("FileChooser");
frmFilechooser.setBounds(100, 100, 470, 350);
frmFilechooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFilechooser.getContentPane().setLayout(new BorderLayout(0, 0));
JFileChooser fileChooser = new JFileChooser();
frmFilechooser.getContentPane().add(fileChooser);
}
}

The easiest and most logical solution is to change the myButtonAction() method to:
private void myButtonAction() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(frmMainwindow);
if (result==JFileChooser.APPROVE_OPTION) {
// do something with the chosen file ..
}
}

If I understand you correctly, you're just missing two lines. The first in mainFrame's myButtonAction:
private void myButtonAction(){
// Toolkit.getDefaultToolkit().beep();
new frame();
}
And the other in frame's initialize:
private void initialize() {
frmFilechooser = new JFrame();
frmFilechooser.setTitle("FileChooser");
frmFilechooser.setBounds(100, 100, 470, 350);
frmFilechooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFilechooser.getContentPane().setLayout(new BorderLayout(0, 0));
JFileChooser fileChooser = new JFileChooser();
frmFilechooser.getContentPane().add(fileChooser);
frmFilechooser.setVisible(true);
}
(I just added the setVisible line at the bottom)

Related

Importing button and text field from another class to main class

I have two different classes (mainClass) and (visual). In the visual class I have a method and inside the method I put the required code for a simple JButton. In the main class I create an object to call the method from visual class, to show the button in the main class . But it does not work. I would appreciate any advice.
package init;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
public class mainClass {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainClass window = new mainClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainClass() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
In the code below I made an object and called the method from the visual class
visual bt = new visual();
bt.btn();
}
}
////////////////VISUAL CLASS//////////////////////
package init;
import javax.swing.JButton;
import javax.swing.JFrame;
public class visual {
public JFrame frame;
public void btn() {
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(141, 155, 151, 45);
frame.getContentPane().add(btnNewButton);
}
}
For what you are trying to achieve here you don't need 2 classes. You can do it like this:
import javax.swing.*;
import java.awt.*;
public class MainClass {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrame frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnNewButton = new JButton("New button");
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(btnNewButton);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

Get(), set() methods make JButton and JTable can not be displayed on JFrame?

I organized my example Project to practice MVC pattern. Model package I stored class "Student", model view I stored a JFrame called "ExampleView", controller I stored a class "ExampleController".
In JFrame "ExampleView", I have a button(btnGetAllInfo) and a table(tblGetAll).
This is my source code for "ExampleView"
package View;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTable;
public class ExampleView extends JFrame {
private JPanel contentPane;
private JTable tblGetAllStudentInfo;
private JButton btnGetAllInformation;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleView frame = new ExampleView();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ExampleView() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
this.contentPane = new JPanel();
this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(this.contentPane);
this.contentPane.setLayout(null);
this.btnGetAllInformation = new JButton("Get all information");
this.btnGetAllInformation.setBounds(159, 11, 128, 23);
this.contentPane.add(btnGetAllInformation);
this.tblGetAllStudentInfo = new JTable();
this.tblGetAllStudentInfo.setBounds(24, 52, 384, 180);
this.contentPane.add(this.tblGetAllStudentInfo);
}
public JPanel getContentPane() {
return contentPane;
}
public void setContentPane(JPanel contentPane) {
this.contentPane = contentPane;
}
public JTable getTblGetAllStudentInfo() {
return tblGetAllStudentInfo;
}
public void setTblGetAllStudentInfo(JTable tblGetAllStudentInfo) {
this.tblGetAllStudentInfo = tblGetAllStudentInfo;
}
public JButton getBtnGetAllInformation() {
return btnGetAllInformation;
}
public void setBtnGetAllInformation(JButton btnGetAllInformation) {
this.btnGetAllInformation = btnGetAllInformation;
}
}
When I run JFrame "ExampleView" with no getBtnGetAllInfo() and getTblGetAllStudentInfo() methods, I got this below result
And corresponding result with getBtnGetAllInfo() and getTblGetAllStudentInfo() methods, I got this below result
Can anyone explain to me why when I have get(), set() methods for button and table like I do above, my button and table do not be shown?

JList gets updated but just allow users to select items once

I have a JList that is located in a JScrollPane. The application has a button for users to browse fileSystem and select a category to show its files and folders.
First time user clicks on the button JList shows the list and enables user to select from the list but if user clicks on the browse button for the second time new items will be shown but
he wont be able to select any item from the list anymore.
public class Main {
private JFrame frame;
final JFileChooser fc = new JFileChooser();
private JScrollPane scrollPane;
File directory;
JList<File> list;
private final Action action_1 = new SwingAction_1();
private final Action action_2 = new SwingAction_2();
JTextArea message;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
list = new JList<File>();
JButton btnBut1 = new JButton("Convert1");
btnBut1.setBounds(401, 6, 114, 29);
btnBut1.setAction(action_1);
JButton btnBut2 = new JButton("Convert2");
btnBut2.setBounds(523, 6, 117, 29);
btnBut2.setAction(action_2);
JButton btnChooseDirectory = new JButton("Choose Directory");
btnChooseDirectory.setBounds(59, 6, 153, 29);
btnChooseDirectory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog(fc);
if (returnVal == JFileChooser.APPROVE_OPTION) {
directory = fc.getSelectedFile();
File[] filesInDir = directory.getAbsoluteFile().listFiles();
addFilesToList(filesInDir);
}
}
});
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnChooseDirectory);
JLabel lblFilesMsg = new JLabel("List of files in the directory:");
lblFilesMsg.setBounds(6, 64, 175, 16);
frame.getContentPane().add(lblFilesMsg);
frame.getContentPane().add(btnBut1);
frame.getContentPane().add(btnBut2);
message = new JTextArea();
message.setBounds(6, 426, 788, 146);
message.setEditable(false);
message.setLineWrap(true);
frame.getContentPane().add(message);
frame.setTitle(APP_NAME);
}
private void addFilesToList(File[] filesInDir) {
list.setListData(filesInDir);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
scrollPane = new JScrollPane(list);
scrollPane.setBounds(6, 81, 788, 330);
scrollPane.setBackground(Color.WHITE);
frame.getContentPane().add(scrollPane);
scrollPane.revalidate();
}
private class SwingAction_1 extends AbstractAction {
public SwingAction_1() {
putValue(NAME, "Converter1");
}
public void actionPerformed(ActionEvent e) {
MyAction1 act = new MyAction1();
act.method1(list.getSelectedValuesList());
}
}
private class SwingAction_2 extends AbstractAction {
public SwingAction_2() {
putValue(NAME, "Converter2");
}
public void actionPerformed(ActionEvent e) {
MyAction2 act = new MyAction2();
act.method2(list.getSelectedValuesList());
}
}
}
I would suggest your problem(s) start with:
Creating a JScrollPane within the addFilesToList method: scrollPane = new JScrollPane(list);. Create the JList AND JScrollPane ONCE, there should be no need to continuously recreate these
Use of null layouts. This has been suggested to you more times then I care to remember. Seriously, make the time to learn the layout managers, it will solve so many small and annoying problems
The problem here...
scrollPane.setBounds(6, 81, 788, 330);
scrollPane.setBackground(Color.WHITE);
frame.getContentPane().add(scrollPane);
Is, which JScrollPane is actually visible on the screen? Which one actually contains the JList? You have more than one now...
And yet, another, simple, runnable example, which works...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JFileChooser fc;
private JList<File> listOfFiles;
private JLabel selectedFile;
public TestPane() {
setLayout(new BorderLayout());
JButton browse = new JButton("Browse");
browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (fc == null) {
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
int returnVal = fc.showOpenDialog(fc);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File directory = fc.getSelectedFile();
File[] filesInDir = directory.getAbsoluteFile().listFiles();
addFilesToList(filesInDir);
}
}
protected void addFilesToList(File[] filesInDir) {
DefaultListModel<File> model = (DefaultListModel<File>) listOfFiles.getModel();
model.removeAllElements();
for (File file : filesInDir) {
model.addElement(file);
}
}
});
add(browse, BorderLayout.NORTH);
listOfFiles = new JList<>(new DefaultListModel<File>());
listOfFiles.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
File file = listOfFiles.getSelectedValue();
selectedFile.setText("You selected: " + (file == null ? "Nothing" : file.getPath()));
}
}
});
add(new JScrollPane(listOfFiles));
selectedFile = new JLabel("You selected: Nothing");
add(selectedFile, BorderLayout.SOUTH);
}
}
}

Opening a different frame with a button in Java

I am trying to open the menu frame using a button on the main frame. I added an event to the button and I tried calling the other class but it keeps giving me an error of ":: expected after this token"
This is my main frame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
public static JPanel mainPane;
public final JButton menuButton = new JButton("New button");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
mainPane = new JPanel();
mainPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(mainPane);
mainPane.setLayout(null);
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(String[] args);
}
});
menuButton.setBounds(76, 89, 104, 32);
mainPane.add(menuButton);
}
}
And this is my menu frame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
public class Menu extends JFrame {
public static JPanel menuPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu frame = new Menu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Menu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
menuPane = new JPanel();
menuPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(menuPane);
menuPane.setLayout(null);
JLabel menuTitle = new JLabel("Menu");
menuTitle.setBounds(194, 11, 46, 14);
menuPane.add(menuTitle);
}
}
change your action event to this.no need to call main method .create a new instance of Menu class instead.
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu menu = new Menu();
menu.setVisible(true);
}
});
if you relly want to call main method then use
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(new String[0]);
}
});
the error is here
Menu.main(String[] args);//error
this is not a correct way of passing arguments to a methods.this is declaration of parameter list.
you can correct error by changing it to ,
String args[] = null;
Menu.main(args); //correct

Java Swing processing status

I am trying to implement a swing frame. In this, I want to display a processing status in a textPanel using a different thread while performing the needed task. I tried the following code. Of course there is something wrong with the logic. Please provide me with the proper approach
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing=false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SampleSwing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(0, 31, 434, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
processing=true;
Processingstatus ps=new Processingstatus();
ps.start();
/*perform the actual task*/
processing=false;
}
});
btnNewButton.setBounds(174, 74, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
class Processingstatus extends Thread{
public void run() {
try {
while(SampleSwing.processing) {
SampleSwing.textField.setText("Processing");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing..");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing...");
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
First I thought, "you should be using a SwingWorker, as it has methods to handle progress and EDT updates..."
But when I looked closer, you don't actually really care about the process itself, you just want some where to show that a process is running...They are two separate entities, that are only related because one (the UI updates) will run so long as the other is running.
So, instead, I used a javax.swing.Timer. This allows me to schedule an event to occur every n milliseconds and have that triggered in the EDT, nice and clean...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.Timer;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing = false;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SampleSwing() {
initialize();
}
private Timer processTimer;
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
textField = new JTextField(25);
frame.add(textField, gbc);
processTimer = new Timer(500, new ActionListener() {
private StringBuilder dots = new StringBuilder(3);
#Override
public void actionPerformed(ActionEvent e) {
dots.append(".");
if (dots.length() > 3) {
dots.delete(0, dots.length());
}
textField.setText("Processing" + dots.toString());
}
});
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!processing) {
processing = true;
processTimer.start();
} else {
processTimer.stop();
processing = false;
textField.setText(null);
}
}
});
frame.add(btnNewButton, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
}
}
ps For the reason why your original code didn't work, see my comment in the above comments section ;)

Categories

Resources