I am trying to get a scroll bar for a Panel that will get a big number of lines, however I am stuck whit this.
As you can see in my window (click here to open the picture), Scroll bars does not adjust to the panel's dimensions
Below you can see the code i am working with:
public class Config extends JFrame {
private static JPanel contentPane;
private static JScrollPane paneSiteScroll;
private static JPanel paneSite;
private JTextField txtURL;
private JButton btnAdd;
private JLabel lblName;
private JTextField txtName;
private JPanel paneBar;
/**
* Launch the application.
*/
public static void config() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Config frame = new Config();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Throwable
*/
public Config() throws Throwable {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 550);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Start top Add Bar
paneBar = new JPanel();
paneBar.setBounds(0, 0, 700, 35);
contentPane.add(paneBar);
paneBar.setLayout(null);
JButton btnBack = new JButton("Back");
btnBack.setBounds(1, 3, 65, 28);
paneBar.add(btnBack);
btnBack.setVerticalAlignment(SwingConstants.TOP);
JLabel lblUrl = new JLabel("URL:");
lblUrl.setBounds(80, 9, 35, 20);
paneBar.add(lblUrl);
txtURL = new JTextField();
txtURL.setBounds(115, 5, 310, 26);
paneBar.add(txtURL);
txtURL.setColumns(10);
lblName = new JLabel("Name:");
lblName.setBounds(435, 9, 47, 20);
paneBar.add(lblName);
txtName = new JTextField();
txtName.setBounds(480, 5, 155, 26);
paneBar.add(txtName);
txtName.setColumns(10);
btnAdd = new JButton("Add");
btnAdd.setBounds(635, 3, 61, 29);
paneBar.add(btnAdd);
//End top Add Bar
//Start Scroll and Panel configuration
paneSiteScroll = new JScrollPane();
paneSite = new JPanel();
paneSite.setLayout(null);
paneSite.setBounds(10, 40, 400, 600);
/*Testing different dimensions configuration*/
paneSiteScroll.setSize(new Dimension(300, 300));
paneSiteScroll.setBounds(10, 40, 300, 200);
paneSiteScroll.setPreferredSize(new Dimension(400, 300));
/*Testing different dimensions configuration*/
paneSiteScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
paneSiteScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
paneSiteScroll.getViewport().add(paneSite);
contentPane.add(paneSiteScroll);
paneSiteScroll.setVisible(true);
paneSite.setVisible(true);
//End Scroll and Panel configuration
try {
Categories.categories(paneSite); //GET CATEGORIES
} catch (Throwable e) {
e.printStackTrace();
}
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!txtURL.getText().isEmpty() || !txtName.getText().isEmpty()) {
InsertDB insert = new InsertDB();
try {
insert.insertDB("INSERT INTO sites (siUrl, siName) VALUES ('" + txtURL.getText() +"'"
+ ", '" + txtName.getText() + "')",
conn);
} catch (Exception e1) {
e1.printStackTrace();
}
}
else {
JOptionPane.showMessageDialog(null, "URL or Name cannot be empty!");
}
}
});
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Back action button
dispose();
}
});
}
}
This is my first question, I do not know what else to add, also i visited many question from stak overflow with similar problems but i couldn't figure it out.
Thanks in advance.
Finally fixed it, I restored the layout to null and added paneSite.setPreferredSize(new Dimension(600, 600)); after paneSite.setbounds. This make it work.
Related
I have this JFrame that has a JScrollPane and a JTextArea inside it, it works okay but the scroll button only appears at the bottom, I want it to show at the top as default. How can I change this?
public class frameMyPasswords extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frameMyPasswords frame = new frameMyPasswords();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public frameMyPasswords() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//scrollPane.getViewport().setViewPosition( new Point(0, 0) );
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.getVerticalScrollBar().setValue(0);
scrollPane.setBounds(10, 45, 414, 194);
contentPane.add(scrollPane);
JTextArea txtField = new JTextArea();
scrollPane.setViewportView(txtField);
txtField.setLineWrap(true);
txtField.setEditable(false);
txtField.setToolTipText("");
txtField.setText("LONG TEXT");
}
}
I have been working on some side project involving MySQL, with will use tree different screens: 'menu, ' add breed', 'browse breed'.
At this point section initialize is getting quite large and I would like to split it into 3 different classes.
Is it possible to initialize for example JPanel outside Window class?
public class Window {
public static void setBreed()
{
for(int i=0; i<16;i++) {
breedLabels[i].setText(breedInfo[i]);
breedLabels[i].setBounds(600,100+i*30,300, 100);
breedLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(breedLabels[i]);
}
}
public static void setText()
{
for(int i=0; i<16;i++) {
textLabels[i].setText(text[i]);
textLabels[i].setBounds(300,100+i*30,300, 100);
textLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(textLabels[i]);
}
}
public static String URL = "jdbc:mysql://localhost:3306/chooseyourpuppy";
public static String user = "root";
public static String password = "";
public static String query = "select * from breeds";
static String [] breedInfo = new String[16];
static String [] text = new String[16];
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
View.connect(URL, user, password, query);
}
public Window() {
initialize();
}
private JFrame frame;
public JPanel addBreed;
public static JPanel viewBreed;
public JPanel menu;
public static JLabel[] textLabels;
public static JLabel[] breedLabels;
private void initialize() {
final int WIDTH = 1280, HEIGHT = 720;
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("MyBREEDS Viewer");
frame.setResizable(false);
frame.setVisible(true);
//header
JPanel red = new JPanel();
red.setBounds(400, 0, 888, 80);
frame.getContentPane().add(red);
red.setBackground(new Color(204, 0, 0));
red.setLayout(null);
JPanel darkGrey = new JPanel();
darkGrey.setBounds(0, 0, 387, 80);
frame.getContentPane().add(darkGrey);
darkGrey.setBackground(new Color(51, 51, 51));
darkGrey.setLayout(null);
JLabel txtpnChoose = new JLabel();
txtpnChoose.setForeground(new Color(240, 240, 240));
txtpnChoose.setBounds(56, 11, 367, 63);
txtpnChoose.setFont(new Font("Verdana", Font.BOLD, 46));
txtpnChoose.setText("Choose your");
txtpnChoose.setBackground(null);
darkGrey.add(txtpnChoose);
JLabel txtpnPuppy = new JLabel();
txtpnPuppy.setBounds(5, 11, 166, 63);
txtpnPuppy.setForeground(new Color(240, 240, 240));
txtpnPuppy.setFont(new Font("Nunito-Bold", Font.BOLD, 46));
txtpnPuppy.setText("puppy");
txtpnPuppy.setBackground(null);
red.add(txtpnPuppy);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, WIDTH, HEIGHT);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
JButton btnMenu = new JButton("Back to menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(menu);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnMenu.setForeground(Color.WHITE);
btnMenu.setBackground(new Color(51, 51, 51));
btnMenu.setFont(new Font("Verdana", Font.BOLD, 18));
btnMenu.setBounds(660, 20, 180, 40);
btnMenu.setBorderPainted(false);
btnMenu.setFocusPainted(false);
red.add(btnMenu);
//menu
menu = new JPanel();
menu.setBackground(Color.WHITE);
layeredPane.add(menu, "name_410359960271086");
menu.setLayout(null);
JButton btnBrowse = new JButton("Browse breeds");
btnBrowse.setBounds(100, 300, 400, 200);
btnBrowse.setFont(new Font("Verdana", Font.PLAIN, 40));
btnBrowse.setBorder(new LineBorder(Color.DARK_GRAY));
btnBrowse.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnBrowse.setBackground(Color.WHITE);
btnBrowse.setRequestFocusEnabled(false);
btnBrowse.setVisible(true);
btnBrowse.setFocusPainted(false);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(viewBreed);
layeredPane.repaint();
layeredPane.revalidate();
setText();
setBreed();
}
});
btnBrowse.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnBrowse.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnBrowse.setBackground(Color.WHITE);
}
});
menu.add(btnBrowse);
addBreed = new JPanel();
layeredPane.add(addBreed, "name_410359942089403");
addBreed.setVisible(false);
addBreed.setBackground(Color.WHITE);
addBreed.setLayout(null);
//view breed window
viewBreed = new JPanel();
layeredPane.add(viewBreed, "name_410359924014670");
viewBreed.setLayout(null);
viewBreed.setVisible(false);
viewBreed.setBackground(Color.WHITE);
ImageIcon previous = new ImageIcon("src/images/previous.png");
ImageIcon previousHover = new ImageIcon("src/images/previousHover.png");
JButton prevBreed = new JButton(previous);
prevBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
prevBreed.setIcon(previousHover);
}
#Override
public void mouseExited(MouseEvent e) {
prevBreed.setIcon(previous);
}
});
prevBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(false);
}
});
prevBreed.setBounds(30, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(prevBreed);
prevBreed.setRequestFocusEnabled(false);
prevBreed.setOpaque(false);
prevBreed.setContentAreaFilled(false);
prevBreed.setBorderPainted(false);
prevBreed.setFocusPainted(false);
ImageIcon next = new ImageIcon("src/images/next.png");
ImageIcon nextHover = new ImageIcon("src/images/nextHover.png");
JButton nextBreed = new JButton(next);
nextBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
nextBreed.setIcon(nextHover);
}
#Override
public void mouseExited(MouseEvent e) {
nextBreed.setIcon(next);
}
});
nextBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(true);
}
});
nextBreed.setBounds(1140, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(nextBreed);
nextBreed.setRequestFocusEnabled(false);
nextBreed.setVisible(true);
nextBreed.setOpaque(false);
nextBreed.setContentAreaFilled(false);
nextBreed.setBorderPainted(false);
nextBreed.setFocusPainted(false);
//add breed window
JButton btnAdd = new JButton("Add new breed");
btnAdd.setBounds(780, 300, 400, 200);
btnAdd.setFont(new Font("Verdana", Font.PLAIN, 40));
btnAdd.setBorder(new LineBorder(Color.DARK_GRAY));
btnAdd.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnAdd.setBackground(Color.WHITE);
btnAdd.setRequestFocusEnabled(false);
btnAdd.setFocusPainted(false);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(addBreed);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnAdd.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnAdd.setBackground(Color.WHITE);
}
});
menu.add(btnAdd);
breedLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
breedLabels[i] = new JLabel(breedInfo[i]);
}
textLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
textLabels[i] = new JLabel(breedInfo[i]);
}
}
}
Is it possible to initialize for example JPanel outside Window class?"
Yes. A different class might contain a method that creates & returns a JPanel.
Other tips:
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.
new Font("Verdana", Font.PLAIN, 20) Use defaults or logical fonts (E.G. Font.SERIF) unless the font is supplied with your app. as an embedded resource.
The loop and array of labels that are added to viewBreed suggest it should be a JList rather than a JPanel
layeredPane.removeAll(); .. Ugh.. Use a CardLayout as shown in this answer.
What is the purpose of the JLayeredPane? I expect it's unnecessary purely on the basis that there is so little use for them.
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));
I'm trying to create a sort of log of all the keys hit, at the moment I just need to figure out how to either:
Link the position of the "text" to the scroll bar to the right
OR
Add a different component which is suited better to hold large amounts of multiple line text.
What am I doing wrong here? Thanks!
public class MacroMakerGui extends JFrame {
public static final long serialVersionUID = 1L;
public static JPanel contentPane;
public static JTextField textField = new JTextField();;
public static MacroKeyListener keylistener = new MacroKeyListener(textField);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MacroMakerGui frame = new MacroMakerGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MacroMakerGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 126, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnNewButton = new JButton("Record Macro");
btnNewButton.setBounds(10, 220, 99, 30);
contentPane.add(btnNewButton, null);
textField.setBounds(10, 189, 99, 20);
contentPane.add(textField);
textField.setColumns(10);
JEditorPane editorPane = new JEditorPane();
editorPane.setBounds(10, 11, 84, 153);
contentPane.add(editorPane);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(93, 11, 17, 153);
contentPane.add(scrollBar);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnNewButton.addKeyListener(keylistener);
}
});
}
}
Instead of JScrollBar, use JScrollPanel. Add that to the contentPane, and add your editorPane as a chiled of the JScrollPanel.
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