Here's an example
My Jtextfields and Jbuttons are being duplicated in the same window, and appear to function exactly the same.
This is probably an easy fix, but as you can tell I'm pretty awful at coding.
(oh and some of the names for variables and such are placeholders :p)
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.GridLayout;
import java.awt.Font;
import java.awt.FlowLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
import javax.swing.JLabel;
public class Adding extends JFrame {
public Adding(Heavy_Lifting lifting) {
addUI(lifting);
}
public void addUI(final Heavy_Lifting lifting) {
setLayout(new FlowLayout());
JButton addButton = new JButton("Enter");
JButton backButton = new JButton("Quit");
final JTextField eInput = new JTextField("Enter english name");
final JTextField mInput = new JTextField("Enter maori name");
final JTextField dInput = new JTextField("Enter description");
//add(addButton);
//add(eInput);
//add(mInput);
//add(backButton);
//add(dInput);
Dimension x = new Dimension(500, 50);
//addButton.setText("Enter");
addButton.setPreferredSize(x);
//backButton.setText("Quit");
backButton.setPreferredSize(x);
//eInput.setText("Enter english name");
eInput.setPreferredSize(x);
//mInput.setText("Enter maori name");
mInput.setPreferredSize(x);
//dInput.setText("Enter description");
dInput.setPreferredSize(x);
add(addButton);
add(eInput);
add(mInput);
add(dInput);
add(backButton);
addButton.addActionListener(new ActionListener() {#
Override
public void actionPerformed(ActionEvent e) {
String mname = mInput.getText();
String ename = eInput.getText();
String desc = dInput.getText();
PeePee p = new PeePee(mname);
Description d = new Description(desc);
if (lifting.allChar(ename, p)) {
lifting.insert(ename, p);
lifting.insert(ename, d);
eInput.setText("1");
mInput.setText("2");
dInput.setText("3");
} else {
eInput.setText("4");
mInput.setText("5");
dInput.setText("6");
}
}
});
backButton.addActionListener(new ActionListener() {#
Override
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
setTitle("placeholder");
setSize(550, 300);
setMinimumSize(new Dimension(550, 300));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
}
This looks like your public method addUI is called twice, maybe by another class. Try switch it to private and see if it still runs and produces the same visual output.
Related
Hello I found a Projekt on yt where you can search for a keyword and it will show all the websites it found on google. And right now I am trying to revive the keyword the user put in the textfield but it isn't working. It does not find the textfield (tf1) I made, but I don't know what I did wrong. Thanks in advance!
here's my code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Main implements ActionListener {
public static void main(String[] args) {
int frameWidth = 600;
int frameHeight = 600;
JFrame f = new JFrame();
JLabel l1 = new JLabel();
JTextField tf1 = new JTextField();
JButton b1 = new JButton();
f.getContentPane().setBackground(Color.PINK);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setSize(frameWidth, frameHeight);
f.setTitle("Search");
f.setLocationRelativeTo(null);
f.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
f.add(l1);
f.add(tf1);
f.add(b1);
l1.setText("Enter Keywords");
tf1.setPreferredSize(new Dimension(200, 20));
tf1.revalidate();
b1.setText("Search");
b1.addActionListener(new Main());
f.setVisible(true);
// ArrayList<WebCrawler> bots = new ArrayList<>();
// bots.add(new WebCrawler("", 1));
// bots.add(new WebCrawler("", 2));
// bots.add(new WebCrawler("", 3));
// for(WebCrawler w : bots) {
// try {
// w.getThread().join();
//
// }catch(InterruptedException e) {
// e.printStackTrace();
// }
// }
}
#Override
public void actionPerformed(ActionEvent e) {
String keyword = tf1.getText(); //Here it does not find the tf I made
System.out.println(keyword); //just for confirmation
}
}
You have a reference issue.
tf1 is declared as a local variable within main, which makes it inaccessible to any other method/context. Add into the fact that main is static and you run into another problem area.
The simple solution would be to make tf1 a instance field. This would be further simplified if you grouped your UI logic into a class, for example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JTextField;
import javax.swing.border.EmptyBorder;
public 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 {
private JLabel label;
private JTextField textField;
private JButton searchButton;
public TestPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(Color.PINK);
setLayout(new GridBagLayout());
label = new JLabel("Enter Keywords: ");
textField = new JTextField(20);
searchButton = new JButton("Search");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(8, 8, 8, 8);
gbc.gridx = 0;
gbc.gridy = 0;
add(label, gbc);
gbc.gridx++;
add(textField, gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(searchButton, gbc);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
JOptionPane.showMessageDialog(TestPane.this, "You want to search for: " + text);
}
};
textField.addActionListener(listener);
searchButton.addActionListener(listener);
}
}
}
This is basic Java 101. You might find something like What is the difference between a local variable, an instance field, an input parameter, and a class field? of help
I have created a JFrame with 3 JTextFields, a button and a label in the centre of the page. I will create a key where if the user enters 'a' in all three textfields and hits the button, the color of the text in the label should change to a different colour for example red.
The main problem I have is linkning my textfields and the button so they work together.
import java.awt.BorderLayout;
import java.awt.Color;
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.JTextField;
public class CE203_2017_Ex1 extends JFrame
{
public static void window()
{
//Button
JButton but = new JButton("Submit");
//JNumberTextField
JTextField rgb1 = new JTextField("",3);
JTextField rgb2 = new JTextField("",3);
JTextField rgb3 = new JTextField("",3);
//JLabel
JLabel text1 = new JLabel("hello my name is adam ", JLabel.CENTER);
text1.setForeground(Color.BLUE);
text1.setAlignmentX(0);
text1.setAlignmentY(0);
//JFrame
JFrame window1 = new JFrame("Adam");
window1.setVisible(true);
window1.setSize(500,500);
window1.add(text1);
//JPanel
JPanel butPanel = new JPanel();
butPanel.add(rgb1);
butPanel.add(rgb2);
butPanel.add(rgb3);
butPanel.add(but);
window1.add(butPanel, BorderLayout.SOUTH);
window1.add(text1);
Here is my actionlistener for the button
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JTextField input = (JTextField) e.getSource();
String passy = input.getText();
String p = new String (passy);
if (rgb1.equals("a")&& rgb2.equals("a")&& rgb3.equals("a")){
text1.setForeground(Color.WHITE);
}
else{
JOptionPane.showMessageDialog(null, "nocorrect");}}});
}
public static void main( String[] args )
{
window();
}
}
You want to test the text value in the textFields not the objects.
if (rgb1.getText().equals("a")&& rgb2.getText().equals("a")&& rgb3.getText().equals("a")) {
text1.setForeground(Color.WHITE);
}
I'm trying to make a GUI window in Java with 4 tabs at the top Home, Booking, Guest, Room. However, the problem is that I'm not sure how to implement buttons in specific tab.
More specific, I made a class called GuestTab and I made 1 button and 1 textfield, but I don't know how can I convey those informations to a Guest tab.
So, if I wasn't so clear, when I click on Guest tab I want to have buttons and text fields that I made in GuestTab class.
I'll put the code of "SEP" class, where I have my GUI main design and "GuestTab" class where I'm adding stuff for Guest tab.
SEP.java:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SEP extends JFrame
{
private GuestTab GuestTab;
private JTabbedPane tPane;
private MyButtonListener buttonListener;
private MyTabListener tabListener;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem exitMenuItem;
public SEP()
{
super("Deer Alley Hotel");
buttonListener = new MyButtonListener();
tabListener = new MyTabListener();
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(buttonListener);
fileMenu = new JMenu("File");
setJMenuBar(menuBar);
tPane = new JTabbedPane();
tPane.addTab(" Home ", new JPanel(
new FlowLayout()));
tPane.addTab(" Booking ", new JPanel(
new FlowLayout()));
tPane.addTab(" Guest ", GuestTab);
tPane.addTab(" Room ", new JPanel(new FlowLayout()));
tPane.addChangeListener(tabListener);
add(tPane);
setSize(575, 452);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
private class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == exitMenuItem)
{
int choice = JOptionPane.showConfirmDialog(null,
"Do you really want to exit the program?", "Exit",
JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
}
}
public class MyTabListener implements ChangeListener
{
public void stateChanged(ChangeEvent e)
{
}
}
}
GuestTab.java:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GuestTab extends JPanel
{
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JPanel panel1;
private JPanel panel2;
private JTextField text;
public GuestTab()
{
panel1 = new JPanel();
button1 = new JButton("Edit Note");
button2 = new JButton("Check out");
button3 = new JButton("Edit Form");
button4 = new JButton("Search");
text = new JTextField(15);
add(panel1);
panel1.setPreferredSize(new Dimension(280, 300));
panel1.add(button4);
panel1.add(text);
setVisible(true);
}
}
You aren't defining your GuestTab properly.
In this line:
tPane.addTab("Guest", guestTab);
Change it to:
tPane.addTab("Guest", new GuestTab());
Or you can initialize the JPanel. You never actually do this you just say
there is a guest tab but you never do anything with it so you can also do:
private GuestTab guestTab;
and then later:
guestTab = new GuestTab();
Side note, never use the same case for the variable definition and class call. Make sure you are using proper camel case.
I have to create a Library for lending Media Items. So far I have the GUI to look how it should, but now I've hit a brick wall with what to do next. When the user clicks the 'Add' button, two prompts should open asking the user for the Title and then the Format, but I have no clue what to do to achieve it. Any help would be great!
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class FinalView extends JFrame{
private JButton add;
private JButton checkOut;
private JButton checkIn;
private JButton delete;
private JScrollPane display;
private JList jlist;
Scanner input = new Scanner(System.in);
public FinalView(){
setTitle("My Library");
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//change later for save feature per printout
setLocationRelativeTo(null);
setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.setLayout(new GridLayout(1, 4, 8, 8));
add = new JButton("Add");
checkOut = new JButton("Check Out");
checkIn = new JButton("Check In");
delete = new JButton("Delete");
buttonPanel.add(add);
buttonPanel.add(checkOut);
buttonPanel.add(checkIn);
buttonPanel.add(delete);
String[] movie = {"Star Wars", "StarTrek"};
Library call = new Library();
jlist = new JList(movie);
jlist.setVisibleRowCount(4);
jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(jlist));
setVisible(true);
ActionListener listener = null;
add.addActionListener(listener);
}
public void actionPerformed(ActionEvent e) {
JOptionPane.showInputDialog("Title:");
String title = input.nextLine();
JOptionPane.showInputDialog("Format:");
String format = input.nextLine();
addNewItem(title, format);
}
private void addNewItem(String title, String format) {
MediaItem lib = new MediaItem(title, format);
// TODO Auto-generated method stub
}
public static void main(String[] args) {
new FinalView();
}
}
package bt;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class login extends javax.swing.JFrame implements ActionListener, javax.swing.RootPaneContainer {
private static final long serialVersionUID = 1L;
private JTextField TUserID=new JTextField(20);
private JPasswordField TPassword=new JPasswordField(20);
protected int role;
public JButton bLogin = new JButton("continue");
private JButton bCancel = new JButton("cancel");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new login().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel();
JLabel l2 = new JLabel("(2011)");
l2.setFont(new Font("Courier New", Font.BOLD, 10));
l.setIcon(icon);
JLabel LUserID=new JLabel("Your User ID: ");
JLabel LPassword=new JLabel("Your Password: ");
TUserID.addActionListener(this);
TPassword.addActionListener(this);
TUserID.setText("correct");
TPassword.setEchoChar('*');
TPassword.setText("correct");
bLogin.setOpaque(true);
bLogin.addActionListener(this);
bCancel.setOpaque(true);
bCancel.addActionListener(this);
JFrame f = new JFrame("continue");
f.setUndecorated(true);
f.setSize(460,300);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 80) / 100.0f);
Container pane = f.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS) );
pane.setBackground(Color.BLACK);
Box box0 = Box.createHorizontalBox();
box0.add(Box.createHorizontalGlue());
box0.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
box0.add(l);
box0.add(Box.createRigidArea(new Dimension(100, 0)));
pane.add(box0);
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box.add(Box.createRigidArea(new Dimension(100, 0)));
box.add(LUserID);
box.add(Box.createRigidArea(new Dimension(32, 0)));
box.add(TUserID);
LUserID.setMaximumSize( LUserID.getPreferredSize() );
TUserID.setMaximumSize( TUserID.getPreferredSize() );
pane.add(box);
Box box2 = Box.createHorizontalBox();
box2.add(Box.createHorizontalGlue());
box2.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box2.add(Box.createRigidArea(new Dimension(100, 0)));
box2.add(LPassword,LEFT_ALIGNMENT);
box2.add(Box.createRigidArea(new Dimension(15, 0)));
box2.add(TPassword,LEFT_ALIGNMENT);
LPassword.setMaximumSize( LPassword.getPreferredSize() );
TPassword.setMaximumSize( TPassword.getPreferredSize() );
pane.add(box2);
Box box3 = Box.createHorizontalBox();
box3.add(Box.createHorizontalGlue());
box3.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 100));
box3.add(bLogin);
box3.add(Box.createRigidArea(new Dimension(10, 0)));
box3.add(bCancel);
pane.add(box3);
f.setLocation(450,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.BLACK);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
String TBUsername = TUserID.getText();
Object src = evt.getSource();
char[] CHPassword1 = TPassword.getPassword();
String TBPassword = String.valueOf(CHPassword1);
login mLogin = this;
if (src==bLogin) {
if (authenticate(TBUsername,TBPassword)) {
System.out.println(this);
exitApp(this);
} else {
exitApp(this);
}
} else if (src==bCancel) {
exitApp(mLogin);
}
}
public void exitApp(JFrame mlogin) {
mlogin.setVisible(false);
}
private boolean authenticate(String uname, String pword) {
if ((uname.matches("correct")) && (pword.matches("correct"))) {
new MyJFrame().createAndShowGUI();
return true;
}
return false;
}
}
and MyJFrame.java
package bt;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MyJFrame extends javax.swing.JFrame implements ActionListener {
private static final long serialVersionUID = 2871032446905829035L;
private JButton bExit = new JButton("Exit (For test purposes)");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyJFrame().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
JPanel p = new JPanel();
p.setBackground(Color.black);
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel("(2011)"); //up to here
l.setIcon(icon);
p.add(l);
p.add(bExit);
bExit.setOpaque(true);
bExit.addActionListener(this);
JFrame f = new JFrame("frame");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setUndecorated(true);
p.setOpaque(true);
f.getContentPane().add(p);
f.pack();
f.setSize(1000,600);
Container pane=f.getContentPane();
pane.setLayout(new GridLayout(0,1) );
//p.setPreferredSize(200,200);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 90) / 100.0f);
f.setLocation(300,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src==bExit) {
System.exit(0);
}
}
}
I cannot get the exitApp() method to work, although it worked before I expanded on my code, I've been trying for hours to get it to work but no avail! The login button suceeds in opening the new frame but will not close the preious(login) frame. It did earlier till I added the validation method etc ....
Create only one JFrame as parent and for another Top-level Containers create only once JDialog (put there JPanel as base), and re-use that for another Action, then you only to remove all JComponents from Base JPanel and add there another JPanel
don't forget for as last lines after switch betweens JPanels inside Base JPanel
revalidate();
repaint();
you can pretty to forgot about that by implements CardLayout