I have been trying to left align buttons contained in a Box to the left, with no success.
They align left alright, but for some reason dont shift all the way left as one would imagine.
I attach the code below. Please try compiling it and see for yourself. Seems bizarre to me.
Thanks, Eric
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class MainGUI extends Box implements ActionListener{
//Create GUI Components
Box centerGUI=new Box(BoxLayout.X_AXIS);
Box bottomGUI=new Box(BoxLayout.X_AXIS);
//centerGUI subcomponents
JTextArea left=new JTextArea(), right=new JTextArea();
JScrollPane leftScrollPane = new JScrollPane(left), rightScrollPane = new JScrollPane(right);
//bottomGUI subcomponents
JButton encrypt=new JButton("Encrypt"), decrypt=new JButton("Decrypt"), close=new JButton("Close"), info=new JButton("Info");
//Create Menubar components
JMenuBar menubar=new JMenuBar();
JMenu fileMenu=new JMenu("File");
JMenuItem open=new JMenuItem("Open"), save=new JMenuItem("Save"), exit=new JMenuItem("Exit");
int returnVal =0;
public MainGUI(){
super(BoxLayout.Y_AXIS);
initCenterGUI();
initBottomGUI();
initFileMenu();
add(centerGUI);
add(bottomGUI);
addActionListeners();
}
private void addActionListeners() {
open.addActionListener(this);
save.addActionListener(this);
exit.addActionListener(this);
encrypt.addActionListener(this);
decrypt.addActionListener(this);
close.addActionListener(this);
info.addActionListener(this);
}
private void initFileMenu() {
fileMenu.add(open);
fileMenu.add(save);
fileMenu.add(exit);
menubar.add(fileMenu);
}
public void initCenterGUI(){
centerGUI.add(leftScrollPane);
centerGUI.add(rightScrollPane);
}
public void initBottomGUI(){
bottomGUI.setAlignmentX(LEFT_ALIGNMENT);
//setBorder(BorderFactory.createLineBorder(Color.BLACK));
bottomGUI.add(encrypt);
bottomGUI.add(decrypt);
bottomGUI.add(close);
bottomGUI.add(info);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// find source of the action
Object source=arg0.getSource();
//if action is of such a type do the corresponding action
if(source==close){
kill();
}
else if(source==open){
//CHOOSE FILE
File file1 =chooseFile();
String input1=readToString(file1);
System.out.println(input1);
left.setText(input1);
}
else if(source==decrypt){
//decrypt everything in Right Panel and output in left panel
decrypt();
}
else if(source==encrypt){
//encrypt everything in left panel and output in right panel
encrypt();
}
else if(source==info){
//show contents of info file in right panel
doInfo();
}
else {
System.out.println("Error");
//throw new UnimplementedActionException();
}
}
private void doInfo() {
// TODO Auto-generated method stub
}
private void encrypt() {
// TODO Auto-generated method stub
}
private void decrypt() {
// TODO Auto-generated method stub
}
private String readToString(File file) {
FileReader fr = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BufferedReader br=new BufferedReader(fr);
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String input="";
while(line!=null){
input=input+"\n"+line;
try {
line=br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
return input;
}
private File chooseFile() {
//Create a file chooser
final JFileChooser fc = new JFileChooser();
returnVal = fc.showOpenDialog(fc);
return fc.getSelectedFile();
}
private void kill() {
System.exit(0);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MainGUI test=new MainGUI();
JFrame f=new JFrame("Tester");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(test.menubar);
f.setPreferredSize(new Dimension(600,400));
//f.setUndecorated(true);
f.add(test);
f.pack();
f.setVisible(true);
}
}
Read the section from the Swing tutorial on How to Use Box Layout. It explains (and has an example) of how BoxLayout works when components have different alignments.
The simple solution is to add:
centerGUI.setAlignmentX(LEFT_ALIGNMENT);
Not sure why the buttons are aligned the way they are, but it's probably because they are trying to align with the box above it (I'm sure someone better versed in Swing can give you a better answer to that one). A handy way to debug layout issues is to highlight the components with coloured borders, e.g. in your current code:
centerGUI.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(centerGUI);
bottomGUI.setBorder(BorderFactory.createLineBorder(Color.RED));
add(bottomGUI);
However, if I had those requirements, I'd use a BorderLayout, e.g. this code is loosely based on yours, I removed the unnecessary bits, to concentrate on the layout portion (you should do this when asking questions, it allows others to answer questions more easily)
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Tester {
private JPanel contentPanel;
private JTextArea leftTextArea = new JTextArea();
private JTextArea rightTextArea = new JTextArea();
private JMenuBar menuBar = new JMenuBar();
public Tester() {
initialisePanel();
initFileMenu();
}
public JPanel getContent() {
return contentPanel;
}
public JMenuBar getMenuBar() {
return menuBar;
}
private final void initialisePanel() {
contentPanel = new JPanel(new BorderLayout());
Box centreBox = new Box(BoxLayout.X_AXIS);
JScrollPane leftScrollPane = new JScrollPane(leftTextArea);
JScrollPane rightScrollPane = new JScrollPane(rightTextArea);
centreBox.add(leftScrollPane);
centreBox.add(rightScrollPane);
Box bottomBox = new Box(BoxLayout.X_AXIS);
bottomBox.add(new JButton(new SaveAction()));
bottomBox.add(new JButton(new ExitAction()));
contentPanel.add(centreBox, BorderLayout.CENTER);
contentPanel.add(bottomBox, BorderLayout.SOUTH);
}
private void initFileMenu() {
JMenu fileMenu = new JMenu("File");
fileMenu.add(new SaveAction());
fileMenu.add(new ExitAction());
menuBar.add(fileMenu);
}
class SaveAction extends AbstractAction {
public SaveAction() {
super("Save");
}
#Override
public void actionPerformed(ActionEvent e) {
handleSave();
}
}
void handleSave() {
System.out.println("Handle save");
}
class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
}
#Override
public void actionPerformed(ActionEvent e) {
handleExit();
}
}
void handleExit() {
System.out.println("Exit selected");
System.exit(0);
}
public static void main(String[] args) {
Tester test = new Tester();
JFrame frame = new JFrame("Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(test.getContent());
frame.setJMenuBar(test.getMenuBar());
frame.setPreferredSize(new Dimension(600, 400));
frame.pack();
frame.setVisible(true);
}
}
Why not try using MiGLayout?
They have a lot of great online demos with source code, including lots of different alignment examples.
Related
I have a small text editor that I made in Java Swing with JTextArea.
I want to implement the following:
When the user presses Command+Backspace I want to remove all the text from the beginning of the line up to the cursor. How to implement this? I tried using KeyListeners but it doesn't work.
For example (before user presses Command+Backspace) ...
Result (after user presses Command+Backspace) ...
My code (Not 100% exact compared to the image):
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main{
static JFrame frame = new JFrame();
static JTextArea textArea = new JTextArea();
static JScrollPane scrollPane = new JScrollPane(textArea);
public static void main(String[] args) throws BadLocationException {
frame.setTitle("Untitled");
addComponentsToFrame();
textArea.addKeyListener(new KeyListener(){
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == (Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | KeyEvent.VK_BACK_SPACE)){
System.out.println("Delete"); //Placeholder
}
}
#Override
public void keyPressed(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
});
}
public static void addComponentsToFrame(){
scrollPane.setAutoscrolls(true);
frame.add(scrollPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
For now when I have placed a print Statement as a place holder, since I don't know how to delete all the words from the beginning of the line up to the cursor (i.e. the logic).
Credits: #Abra
Solution:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import java.awt.Toolkit;
public class TestSamplePrograms {
private JTextArea textarea;
private void buildAndShowGui() {
JFrame frame = new JFrame("Untitled");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTextArea(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JScrollPane createTextArea() {
textarea = new JTextArea(20, 60);
InputMap im = textarea.getInputMap();
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
im.put(ks, "del2EoL");
ActionMap am = textarea.getActionMap();
am.put("del2EoL", new Delete2EOL());
JScrollPane pane = new JScrollPane(textarea);
return pane;
}
#SuppressWarnings("serial")
private class Delete2EOL extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
int caretOffset = textarea.getCaretPosition();
int lineNumber = 0;
try {
lineNumber = textarea.getLineOfOffset(caretOffset);
int startOffset = textarea.getLineStartOffset(lineNumber);
int endOffset = textarea.getLineEndOffset(lineNumber);
textarea.replaceRange("", startOffset, endOffset);
} catch (BadLocationException ex) {
throw new RuntimeException(ex);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new TestSamplePrograms().buildAndShowGui());
}
}
I have a small text editor that I made in Java Swing with JTextArea.
I want to implement the following:
When the user presses Command+Backspace I want to remove all the text from the beginning of the line up to the cursor. How to implement this? I tried using KeyListeners but it doesn't work.
For example (before user presses Command+Backspace) ...
Result (after user presses Command+Backspace) ...
My code (Not 100% exact compared to the image):
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main{
static JFrame frame = new JFrame();
static JTextArea textArea = new JTextArea();
static JScrollPane scrollPane = new JScrollPane(textArea);
public static void main(String[] args) throws BadLocationException {
frame.setTitle("Untitled");
addComponentsToFrame();
textArea.addKeyListener(new KeyListener(){
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == (Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | KeyEvent.VK_BACK_SPACE)){
System.out.println("Delete"); //Placeholder
}
}
#Override
public void keyPressed(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
});
}
public static void addComponentsToFrame(){
scrollPane.setAutoscrolls(true);
frame.add(scrollPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
For now when I have placed a print Statement as a place holder, since I don't know how to delete all the words from the beginning of the line up to the cursor (i.e. the logic).
Credits: #Abra
Solution:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import java.awt.Toolkit;
public class TestSamplePrograms {
private JTextArea textarea;
private void buildAndShowGui() {
JFrame frame = new JFrame("Untitled");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTextArea(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JScrollPane createTextArea() {
textarea = new JTextArea(20, 60);
InputMap im = textarea.getInputMap();
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
im.put(ks, "del2EoL");
ActionMap am = textarea.getActionMap();
am.put("del2EoL", new Delete2EOL());
JScrollPane pane = new JScrollPane(textarea);
return pane;
}
#SuppressWarnings("serial")
private class Delete2EOL extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
int caretOffset = textarea.getCaretPosition();
int lineNumber = 0;
try {
lineNumber = textarea.getLineOfOffset(caretOffset);
int startOffset = textarea.getLineStartOffset(lineNumber);
int endOffset = textarea.getLineEndOffset(lineNumber);
textarea.replaceRange("", startOffset, endOffset);
} catch (BadLocationException ex) {
throw new RuntimeException(ex);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new TestSamplePrograms().buildAndShowGui());
}
}
I am creating a NotePad app in Java Swing but when I am trying to open a popup to set a title, it is not showing up.
The class that calls the popup:
import java.io.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class NewFile implements ActionListener{
public static String title;
public void actionPerformed(ActionEvent e){
PopupFileName popup = new PopupFileName();
/*try{
Thread.sleep(30000);
}catch (InterruptedException o){
o.printStackTrace();
}*/
JTextArea titl = popup.title;
title = titl.getText();
try{
File writer = new File(title+".txt");
if(writer.createNewFile()){
System.out.println("file created");
}else{
System.out.println("file exists");
}
}catch (IOException i) {
System.out.println("An error occurred.");
i.printStackTrace();
}
}
}
The popup class that is supposed to open:
import javax.swing.*;
public class PopupFileName{
static JFrame popup = new JFrame("File Title");
static JLabel titlel = new JLabel("Title:");
static public JTextArea title = new JTextArea();
public static void main(String[] args){
popup.setSize(200,300);
popup.setVisible(true);
popup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
popup.add(titlel);
popup.add(title);
}
}
Is there any way I can make it visible and make it able to get the text before it is created?
Start by taking a look at:
Creating a GUI With Swing
How to Write an Action Listener
How to Use Scroll Panes
How to Use Buttons, Check Boxes, and Radio Buttons
How to Make Dialogs
You're running in an event driven environment, this means, something happens and then you respond to it.
The problem with your ActionListener is, it's trying to present a window and then, immediately, trying to get some result from it. The problem is, the window probably isn't even present on the screen yet.
What you need is some way to "stop" the code execution until after the user responds. This is where a modal dialog comes in.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Test");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String title = PopupFileName.getTitle(TestPane.this);
System.out.println(title);
}
});
add(btn);
}
}
public static class PopupFileName extends JPanel {
private JLabel titlel = new JLabel("Title:");
private JTextArea title = new JTextArea(20, 40);
public PopupFileName() {
setLayout(new BorderLayout());
add(titlel, BorderLayout.NORTH);
add(new JScrollPane(title));
}
public String getTitle() {
return title.getText();
}
public static String getTitle(Component parent) {
PopupFileName popupFileName = new PopupFileName();
int response = JOptionPane.showConfirmDialog(parent, popupFileName, "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
switch (response) {
case JOptionPane.OK_OPTION:
return popupFileName.getTitle();
default: return null;
}
}
}
}
I'm using JTextPane and StyledDocument for styling message and I want to clear the messages or clear only the oldest message.
I can easily clear all by using:
textPane.setText("");
But if I want to clear all, except some lines, then not sure if/how it can be done.
I tried
textPane.setText(textPane.getText().substring(0, Math.min(200, textPane.getText().length())));
but the issue is that it remove the content styling.
Here is simple demo that shows the issue.
Is there an easy way to do it?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class TestJTextPane {
private JTextPane infoTextPane = new JTextPane();
private StyledDocument styledDocument;
private SimpleAttributeSet attributeSet = new SimpleAttributeSet();
private JButton addText;
private JButton clearText;
public static void main(String[] argv) {
new TestJTextPane();
}
public TestJTextPane(){
addText = new JButton("add");
addText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
StyleConstants.setForeground(attributeSet, Color.GREEN);
StyleConstants.setBackground(attributeSet, Color.BLACK);
StyleConstants.setBold(attributeSet, true);
StyleConstants.setFontSize(attributeSet, 20);
styledDocument.insertString(styledDocument.getLength(), "sample text message to add\n", attributeSet);
infoTextPane.setCaretPosition(infoTextPane.getDocument().getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
clearText = new JButton("clear");
clearText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//infoTextPane.setText("");
infoTextPane.setText(infoTextPane.getText().substring(0, Math.min(200, infoTextPane.getText().length())));
}
});
styledDocument = infoTextPane.getStyledDocument();
JPanel p = new JPanel();
p.add(addText);
p.add(clearText);
p.add(infoTextPane);
JFrame f = new JFrame("HyperlinkListener");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(p);
f.setPreferredSize(new Dimension(400, 400));
f.pack();
f.setVisible(true);
}
}
Figure how to do it with Element. For example, the below code will keep only the latest 2 messages.
Element root = infoTextPane.getDocument().getDefaultRootElement();
try {
while(root.getElementCount() > 3){
Element first = root.getElement(0);
infoTextPane.getStyledDocument().remove(root.getStartOffset(), first.getEndOffset());
}
} catch (BadLocationException e1) {
// FIXME Auto-generated catch block
e1.printStackTrace();
}
This code enables an employee to log in to the coffee shop system. I admit I have a lot of unneeded code. My problem is that when I run the program just the image is displayed above and no JButtons, JLabels or JTextFields.
Thanks in advance.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class login extends JFrame {
public void CreateFrame() {
JFrame frame = new JFrame("Welcome");
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout(1000,1000));
panel.setLayout(new FlowLayout());
getContentPane().add(panel);
ImagePanel imagePanel = new ImagePanel();
imagePanel.show();
panel.add(imagePanel, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new login().CreateFrame();
}
});
}
}
class GUI extends JFrame{
private JButton buttonLogin;
private JButton buttonNewUser;
private JLabel iUsername;
private JLabel iPassword;
private JTextField userField;
private JPasswordField passField;
public void createGUI(){
setLayout(new GridBagLayout());
JPanel loginPanel = new JPanel();
loginPanel.setOpaque(false);
loginPanel.setLayout(new GridLayout(3,3,3,3));
iUsername = new JLabel("Username ");
iUsername.setForeground(Color.BLACK);
userField = new JTextField(10);
iPassword = new JLabel("Password ");
iPassword.setForeground(Color.BLACK);
passField = new JPasswordField(10);
buttonLogin = new JButton("Login");
buttonNewUser = new JButton("New User");
loginPanel.add(iUsername);
loginPanel.add(iPassword);
loginPanel.add(userField);
loginPanel.add(passField);
loginPanel.add(buttonLogin);
loginPanel.add(buttonNewUser);
add(loginPanel);
pack();
Writer writer = null;
File check = new File("userPass.txt");
if(check.exists()){
//Checks if the file exists. will not add anything if the file does exist.
}else{
try{
File texting = new File("userPass.txt");
writer = new BufferedWriter(new FileWriter(texting));
writer.write("message");
}catch(IOException e){
e.printStackTrace();
}
}
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File("userPass.txt");
Scanner scan = new Scanner(file);;
String line = null;
FileWriter filewrite = new FileWriter(file, true);
String usertxt = " ";
String passtxt = " ";
String puname = userField.getText();
String ppaswd = passField.getText();
while (scan.hasNext()) {
usertxt = scan.nextLine();
passtxt = scan.nextLine();
}
if(puname.equals(usertxt) && ppaswd.equals(passtxt)) {
MainMenu menu = new MainMenu();
dispose();
}
else if(puname.equals("") && ppaswd.equals("")){
JOptionPane.showMessageDialog(null,"Please insert Username and Password");
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username / Password");
userField.setText("");
passField.setText("");
userField.requestFocus();
}
} catch (IOException d) {
d.printStackTrace();
}
}
});
buttonNewUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewUser user = new NewUser();
dispose();
}
});
}
}
class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK,5));
try
{
image = ImageIO.read(new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ8F5S_KK7uelpM5qdQXuaL1r09SS484R3-gLYArOp7Bom-LTYTT8Kjaiw"));
}
catch(Exception e)
{
e.printStackTrace();
}
GUI show = new GUI();
show.createGUI();
}
#Override
public Dimension getPreferredSize(){
return (new Dimension(430, 300));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}
Seems to me like you have a class login (which is a JFrame, but never used as one). This login class creates a new generic "Welcome" JFrame with the ImagePanel in it. The ImagePanel calls GUI.createGUI() (which creates another JFrame, but doesn't show it) and then does absolutely nothing with it, thus it is immediately lost.
There are way to many JFrames in your code. One should be enough, perhaps two. But you got three: login, gui, and a simple new JFrame().