Relative path for browsing folder in java - java

I want to modify to browse the folder through the relative path.
The code only browse through the absolute path and check only the provided directory is empty or not...plz help....thanks in advance
package fyp;
import java.awt.Color;
public class Frame2 extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame2 frame = new Frame2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Frame2() {
textField = new JTextField();
textField.setBounds(92, 107, 272, 20);
setTitle("Plagiarm Detection System\r\n");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 300);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Browse the folder to process");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(true);
File file=new File("C:/Users/Shahzaib/Desktop/empty");
//File relative=new File("C:/Users/Shahzaib/Desktop/empty");
//System.out.println(relative.getName());
//System.out.println(relative.getPath());
//File file = new File("directory");
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
textField.setText(chooser.getSelectedFile().toString());
//System.out.println("getCurrentDirectory(): "+ chooser.getCurrentDirectory());
//System.out.println("getSelectedFile() : "+ chooser.getSelectedFile());
}
if(file.isDirectory()){
if(file.list().length>0){
Component frame = null;
JOptionPane.showMessageDialog(frame, "Directory is Not Empty.");
}else{
Component frame = null;
JOptionPane.showMessageDialog(frame, "Directory is Empty.");
}
//else
//{
// Component frame = null;
//JOptionPane.showMessageDialog(frame, "No Selection.");
}
}
});
getContentPane().add(btnBrowse);
btnBrowse.setBounds(374, 106, 89, 23);
contentPane.add(btnBrowse);
contentPane.add(textField);
textField.setColumns(10);
JButton btnProceed = new JButton("Next");
btnProceed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
new Frame2().setVisible(true);
}
});
btnProceed.setBounds(485, 227, 89, 23);
contentPane.add(btnProceed);
JButton btnBack = new JButton("Cancel");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
new Frame().setVisible(true);
}
});
btnBack.setBounds(374, 227, 89, 23);
contentPane.add(btnBack);
JLabel lblNewLabel = new JLabel("Choose Folder of Assignments");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel.setBounds(180, 11, 235, 50);
contentPane.add(lblNewLabel);
}
}

When it comes to files usually you at least want to have a try{} and catch{}.
Hints: if you want to find the directory of a file, try file.getParent() or file.getParentFile(). Additionally, you should check to see if the file exists .exists() or isDirectory().

Related

when I make a popup menu with JPopupMenu it quits my file explorer page that I made and goes back to the main page(desktop)

I have tried telling it to dispose the file explorer and recreate it works but I cannot seem to get my file image on it now any help in making it not quit in the first place?
here is the code(btw I am on IntelliJ IDEA CE):
package os_pack;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OS extends JFrame implements ActionListener {
String title = "waliOS";
String message = "please login";
int width = 600;
int height = 400;
JButton b;
JLabel label;
JTextField text;
JLabel c;
JPasswordField pass;
JFrame f;
JFrame f2;
JLabel username;
JLabel password;
JLabel welcomeMain;
JFrame folderFrame;
JFrame textFrame;
JLabel folderLabel;
OS() {
f = new JFrame(title);
f.setSize(width, height);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel(message);
label.setBounds(200, 100, 200, 50);
label.setForeground(Color.WHITE);
text = new JTextField();
text.setBounds(200, 150, 200, 30);
b = new JButton("login");
b.setBounds(200, 250, 200, 50);
b.addActionListener(this);
pass = new JPasswordField();
pass.setBounds(200, 200, 200, 30);
c = new JLabel();
c.setBounds(200, 300, 200, 50);
c.setForeground(Color.WHITE);
username = new JLabel("username");
username.setBounds(130, 140, 200, 50);
username.setForeground(Color.WHITE);
password = new JLabel("password");
password.setBounds(130, 190, 200, 50);
password.setForeground(Color.WHITE);
f.add(password);
f.add(username);
f.add(c);
f.add(pass);
f.add(b);
f.add(label);
f.add(text);
f.setLayout(null);
f.setVisible(true);
f.setResizable(false);
f.getContentPane().setBackground(Color.BLACK);
}
public void mainPage(){
f.dispose();
f2 = new JFrame();
f2.setTitle(title);
f2.setSize(width, height);
f2.setLocationRelativeTo(null);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setResizable(false);
f2.setLayout(null);
f2.setVisible(true);
f2.setResizable(false);
f2.getContentPane().setBackground(Color.BLACK);
welcomeMain = new JLabel("this is the home page");
welcomeMain.setForeground(Color.WHITE);
welcomeMain.setBounds(200, 100, 200, 50);
f2.add(welcomeMain);
ImageIcon folder = new ImageIcon(getClass().getResource("OS_file.png"));
JLabel folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
folderPage();
}
});
ImageIcon textEdit = new ImageIcon(getClass().getResource("text_edit.png"));
JLabel textImage = new JLabel(textEdit);
textImage.setBounds(200, 200, 80, 80);
textImage.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent em){
textEditPage();
}
});
f2.add(folderLabel);
f2.add(textImage);
}
public void folderPage() {
f2.dispose();
folderFrame = new JFrame(title + " folder");
folderFrame.setSize(width, height);
folderFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
folderFrame.setLocationRelativeTo(null);
folderFrame.setResizable(false);
folderFrame.setLayout(null);
folderFrame.setVisible(true);
folderFrame.getContentPane().setBackground(Color.BLACK);
JLabel test = new JLabel("this is the folder page");
test.setForeground(Color.WHITE);
test.setBounds(300, 200, 200, 50);
JButton back = new JButton("back");
back.setBounds(10, 10, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
folderFrame.dispose();
}
});
JPopupMenu menu = new JPopupMenu();
JMenuItem newFolder = new JMenuItem("new Folder");
newFolder.addActionListener(this);
newFolder.setActionCommand("NF");
menu.add(newFolder);
folderFrame.addMouseListener((new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)){
menu.show(folderFrame, e.getX(), e.getY());
}
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}));
ImageIcon folder = new ImageIcon("folder.png");
folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderFrame.add(test);
folderFrame.add(back);
}
public void textEditPage() {
f2.dispose();
textFrame = new JFrame(title + " text editor");
textFrame.setResizable(false);
textFrame.setLayout(null);
textFrame.setSize(width, height);
textFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textFrame.setVisible(true);
textFrame.setLocationRelativeTo(null);
textFrame.getContentPane().setBackground(Color.BLACK);
JTextArea textArea = new JTextArea();
Font font = new Font(
Font.MONOSPACED,
Font.PLAIN,
textArea.getFont().getSize());
textArea.setFont(font);
textArea.setBounds(1, 30, 599, 399);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JLabel title = new JLabel("Text Editor");
title.setBounds(250, 2, 100, 30);
title.setForeground(Color.WHITE);
JButton back = new JButton("back");
back.setBounds(10, 4, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
textFrame.dispose();
}
});
textFrame.add(back);
textFrame.add(title);
textFrame.add(textArea);
}
public static void main(String[] args){
new OS();
}
#Override
public void actionPerformed(ActionEvent e) {
String user = text.getText();
String pass1 = pass.getText();
if (user.trim().equals("wali") && pass1.trim().equals("haider")) {
c.setText("welcome wali");
mainPage();
} else if(user.trim().equals("admin") && pass1.trim().equals("admin")) {
c.setText("welcome admin");
mainPage();
} else {
c.setText("wrong user");
}
String command = e.getActionCommand();
switch (command) {
case "NF":
System.out.println("done");
folderPage();
folderFrame.dispose();
System.out.print("hello");
folderFrame.add(folderLabel);
}
}
}
can I please get some help on this because I am really stuck if you have questions tell me in the comments that will be very helpful

How to stop JDialog from closing when you hit the Enter key?

I am trying to stop my JDialog from closing when the Enter key is pushed. I have already tried using getRootPane().setDefaultButton(null); but it is still not working. I am calling this constructor for my JDialog from the main JFrame. Here is my code:
public class CustomSaleDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField txtScanBarcode;
private JTextField txtNumSold;
private String barcode;
private int numTickets;
public void setNumTickets(int num) {
numTickets = num;
}
public void setBarCode(String code) {
barcode = code;
}
public int getNumTickets() {
return numTickets;
}
public String getBarCode() {
return barcode;
}
public CustomSaleDialog(JFrame f) {
getRootPane().setDefaultButton(null); //This is what I tried
setTitle("Custom Sale");
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
JLabel lblMakeACustom = new JLabel("Make a Custom Sale");
lblMakeACustom.setFont(new Font("Tahoma", Font.PLAIN, 25));
lblMakeACustom.setHorizontalAlignment(SwingConstants.CENTER);
lblMakeACustom.setBounds(10, 11, 414, 44);
contentPanel.add(lblMakeACustom);
}
{
JLabel lblScanTicket = new JLabel("Scan Ticket");
lblScanTicket.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblScanTicket.setBounds(20, 73, 102, 20);
contentPanel.add(lblScanTicket);
}
{
JLabel lblNumberOfTickets = new JLabel("Number of Tickets Being Sold");
lblNumberOfTickets.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblNumberOfTickets.setBounds(20, 136, 262, 25);
contentPanel.add(lblNumberOfTickets);
}
{
txtScanBarcode = new JTextField();
txtScanBarcode.setBounds(132, 73, 284, 20);
contentPanel.add(txtScanBarcode);
txtScanBarcode.setColumns(10);
}
{
txtNumSold = new JTextField();
txtNumSold.setBounds(292, 141, 124, 20);
contentPanel.add(txtNumSold);
txtNumSold.setColumns(10);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
barcode = txtScanBarcode.getText();
String numTickets = txtNumSold.getText();
int numTicketsInt = 0;
if (barcode.length() > 0
&& numTickets.matches("[0-9]+")
&& numTickets.length() >= 1) {
numTicketsInt = Integer.parseInt(numTickets);
setBarCode(barcode);
setNumTickets(numTicketsInt);
}
setVisible(false);
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setLocationRelativeTo(f);
setVisible(true);
}
}
And you forget to remove...
getRootPane().setDefaultButton(okButton);
This...
is why you don't use null layouts
Set focusable method or something like this that focuses to false.
remove this line getRootPane().setDefaultButton(okButton); it should work :)

this.dispose() is not working to close a JFrame

When I add:
this.dispose();
The window is not closing, what can I do?.
I use Eclipse with windowsBuilder.
I want to close the actual window to open another window.
My code:
public class Ventana_login extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7948060398287723741L;
private JPanel contentPane;
private JTextField txtUsuario;
private JPasswordField txtContrasena;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ventana_login frame = new Ventana_login();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Ventana_login() {
setTitle("Sistema Gestor de Eventos v1.0");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblBienvenidoAlSistema = new JLabel("Bienvenido");
lblBienvenidoAlSistema.setHorizontalAlignment(SwingConstants.CENTER);
lblBienvenidoAlSistema.setFont(new Font("Tahoma", Font.BOLD, 16));
lblBienvenidoAlSistema.setBounds(10, 11, 424, 14);
contentPane.add(lblBienvenidoAlSistema);
JLabel lblUsuario = new JLabel("Usuario");
lblUsuario.setHorizontalAlignment(SwingConstants.RIGHT);
lblUsuario.setBounds(96, 79, 70, 14);
contentPane.add(lblUsuario);
JLabel lblContrasena = new JLabel("Contrase\u00F1a");
lblContrasena.setHorizontalAlignment(SwingConstants.RIGHT);
lblContrasena.setBounds(96, 109, 70, 14);
contentPane.add(lblContrasena);
txtUsuario = new JTextField();
txtUsuario.setBounds(176, 76, 150, 20);
contentPane.add(txtUsuario);
txtUsuario.setColumns(10);
JButton btnIniciarSesion = new JButton("Iniciar Sesi\u00F3n");
btnIniciarSesion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Dato_login d_lgn = new Dato_login();
Logica_login l_lgn = new Logica_login();
d_lgn.setUsuario(txtUsuario.getText());
char[] contrasenaChar = txtContrasena.getPassword();
String contrasenaClean = new String(contrasenaChar);
d_lgn.setContrasena(contrasenaClean);
Dato_login d_lgn2 = l_lgn.login(d_lgn.getUsuario(), d_lgn.getContrasena());
if (Logica_login.resultado) {
Ventana_menu v_menu = new Ventana_menu();
v_menu.setVisible(true);
v_menu.setLocationRelativeTo(null);
Ventana_menu.lblPerfilActual.setText(d_lgn2.getPerfil());
Ventana_menu.lblApellidoActual.setText(d_lgn2.getApellido());
Ventana_menu.lblNombreActual.setText(d_lgn2.getNombre());
Ventana_menu.lblUsuarioActual.setText(d_lgn2.getUsuario());
if (Ventana_menu.lblPerfilActual.getText().equals("Portero")) {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(false);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(false);
Ventana_menu.btnReportes.setEnabled(true);
} else {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(true);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(true);
Ventana_menu.btnReportes.setEnabled(true);
}
this.dispose();
} else {
JOptionPane.showMessageDialog(contentPane, "Acceso Denegado", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Exception:\n" + e, "Error: Ventana_login", JOptionPane.ERROR_MESSAGE);
}
}
});
btnIniciarSesion.setBounds(176, 163, 150, 30);
contentPane.add(btnIniciarSesion);
I will assume by window you mean JFrame:
then do:
myJframe.dispatchEvent(new WindowEvent(myJframe, WindowEvent.WINDOW_CLOSING));

How to restart the screen with action listener?

I was looking in to my Java project when I realized I have yet to make my title screen. But one problem came to mind: How do I make it in where when they press on the new file button it will clear everything on the screen and put the new stuff in?
In simpler words, how to make a action listener so when they click the button the screen will clear and put a new screen on?
package Main_Config;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class SET_UP extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JLabel consol;
public static Dimension size = new Dimension(800, 700);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SET_UP frame = new SET_UP();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SET_UP() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(370, 70, 0, 0);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setSize(size);
setLocationRelativeTo(null);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
consol.setText(input);
}
});
textField.setBounds(10, 452, 243, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton enter = new JButton("Enter");
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
enter.setBounds(253, 452, 89, 20);
contentPane.add(enter);
JLabel consol = new JLabel("");
consol.setBounds(0, 483, 335, 189);
contentPane.add(consol);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(352, 451, 200, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(584, 451, 200, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.setBounds(0, 0, 89, 23);
contentPane.add(btnNewButton_2);
}
}
To clear the screen, I do this:
Button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
frame.remove(panelTwo);
frame.remove(panelThree);
frame.add(panelFour);
frame.setVisible(true);
}
});

not showing message diologe with JOptione pane

i have written a code to create a sms form and i want to add the ability to show error message when the text area is empty. i put JOptionpane in my code but diologe dose not appear when i run the program! here is my code
private void initialize() {
frame = new JFrame("?????? ? ????? ?????");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JOptionPane optionPane = new JOptionPane();
JPanel middlePanel = new JPanel();
txtPath = new JTextField();
txtPath.setBounds(150, 10, 200, 21);
frame.getContentPane().add(txtPath);
txtPath.setColumns(10);
txtPath2 = new JTextField();
txtPath2.setBounds(150, 65, 200, 21);
frame.getContentPane().add(txtPath2);
txtPath2.setColumns(20);
JButton btnBrowse = new JButton("?????");
btnBrowse.setBounds(5, 10, 87, 23);
frame.getContentPane().add(btnBrowse);
final JButton ok = new JButton("?????");
ok.setBounds(250, 230, 87, 23);
frame.getContentPane().add(ok);
JButton cancel = new JButton("???");
cancel.setBounds(110, 230, 87, 23);
frame.getContentPane().add(cancel);
final JTextArea textarea = new JTextArea();
textarea.setBounds(50, 100, 300, 100);
frame.getContentPane().add(textarea);
textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setSize(10, 1);
progressBar.setForeground(Color.blue);
frame.getContentPane().add(progressBar);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
// For Directory
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
// For File
//fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
txtPath.setText(fileChooser.getSelectedFile().toString());
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt", "rtf"));
}
}
});
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textarea.getLineCount()>=1)
{
test t=new test();
ReadTextFile readTextFile=new ReadTextFile();
t.testMethode(txtPath2.getText(), textarea.getText(),readTextFile.readFile(txtPath.getText()) );
}
else
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
}
GUI's are event driven environments. Something happens, you respond to it.
You if-else statement will never be false because the time it is executed, the textarea will be blank (have no text).
You need to respond to some event (ie send for example) at which time you would make your check to valid the form.
Take a look at Creating a GUI with Swing for more details
Updated with example
public class Example {
public static void main(String[] args) {
new Example();
}
public Example() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private final JTextArea msg;
public TestPane() {
msg = new JTextArea(10, 20);
JButton send = new JButton("Send");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JScrollPane(msg), gbc);
add(send, gbc);
send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (msg.getText().trim().length() > 0) {
// Send msg
} else {
JOptionPane.showMessageDialog(TestPane.this, "Please write something (nice)", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
}
Updated based on changes to the answer by the OP
if(textarea.getLineCount()>=1) will always return true. Try using msg.getText().trim().length() > 0 instead to determine the JTextArea contains text or not...
Updated
mKobel has made an excellent point. You really should avoid using null layouts. You don't control what font size or screen DPI/resolution your application might need to work on. Layout managers take out the guess work.
You should try checking out A visual guide to layout managers and Using layout managers for more details

Categories