Putting JLabel on JScrollPane from another class in Java - java

I am making family tree and this is my problem. I have screens NewFamilyTree.java and NewPerson.java.
NewFamilyTree.java:
public class NewFamilyTree {
...
private void initialize() {
frame = new JFrame();
frame.setTitle("New family tree");
frame.setBounds(100, 100, 906, 569);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane();
tabbedPane.addTab("Tree", null, scrollPane, null);
panel_1 = new JPanel();
scrollPane.setViewportView(panel_1);
panel_1.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));
NewPerson.java:
public class NewPerson{
...
buttonAdd = new JButton("Add");
buttonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String names = textFieldNames.getText();
String dateBirth = textFieldDateOfBirth.getText();
String bio = textAreaBio.getText();
Data newData = new Data(names, dateBirth, bio, fileID);
//code that puts new label on scrollpane from NewFamilyTree.java
}
});
buttonAdd.setBackground(new Color(30, 144, 255));
frame.getContentPane().add(buttonAdd, "cell 2 6,grow");
}
I need to put new JLabel from class NewPerson, by pressing on button Add, on the JScrollPane of NewFamilytree.java. Hope someone can help, I searched a lot and couldn't help myself.
EDIT: After the answer from #mjr.
I added public JPanel panel_1; in NewFamilyTree. In Add action performed I added:
JLabel lblHomer = new JLabel("Homer");
lblHomer.setIcon(new ImageIcon("C:\\Users\\Tinmar\\Desktop\\HomerSimpson3.gif"));
panel_1.add(lblHomer, "cell 7 5");
No errors, but - nothing happens after I press the add button. I also added NewPerson EXTENDS NewFamilyTree, ofc.

NewPerson doesn't need extend from NewFamilyTree, it's not adding any functionality to the class
Instead of using a JFrame in NewPerson, consider using a modal JDialog instead. See How to Make Dialogs for more details
Limit the exposure of components between classes. There is no reason why NewFamilyTree should be able to access the "window" been used by NewPerson. There's no reason why NewPerson should be adding anything to NewFamilyTree
Don't mix heavy weight components (like java.awt.Button) with light weight components, this can cause no end of issues...
You need to change the way you think of things. Instead of trying to make the NewPerson update the UI of the NewFamilyTree, have NewPerson gather the details from the user and pass this information back to NewFamilyTree so it can use it...
For example...
JButton newPersonButton = new JButton("New Person");
newPersonButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Data data = NewPerson.createPerson(frame);
if (data != null) {
JLabel lblHomer = new JLabel(data.names);
panel_1.add(lblHomer, "cell 7 5");
panel_1.revalidate();
}
}
});
This basically uses a static method createPerson which passes back a instance of Data (or null if the user cancelled the operation), which NewFamilyTree can then use. It decouples the code, as NewPerson is not relient on anything from NewFamilyTree and NewFamilyTree maintains control. This clearly defines the areas of responsibility between the two classes, it also means that NewPerson could be called from anywhere...
The createPerson method looks, something like, this...
public static Data createPerson(Component comp) {
NewPerson newPerson = new NewPerson();
Window win = SwingUtilities.getWindowAncestor(comp);
JDialog dialog = null;
if (win instanceof Frame) {
dialog = new JDialog((Frame) win, "New person", true);
} else if (win instanceof Dialog) {
dialog = new JDialog((Dialog) win, "New person", true);
} else {
dialog = new JDialog((Frame) null, "New person", true);
}
newPerson.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Component) {
Window win = SwingUtilities.getWindowAncestor((Component) source);
win.dispose();
}
}
});
dialog.add(newPerson);
dialog.setVisible(true);
return newPerson.getData();
}
It basically creates and instance of JDialog, shows it to the user and waits until the NewPerson class triggers an ActionEvent, which it uses to dispose of the dialog. It then asks the instance of NewPerson for the data...
And because there's a whole bunch of functionality I've not talked about, here's a fully runnable example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
public class NewFamilyTree {
private JFrame frame;
private JPanel panel_1;
private JScrollPane scrollPane;
private JTabbedPane tabbedPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NewFamilyTree window = new NewFamilyTree();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public NewFamilyTree() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("New family tree");
frame.getContentPane().setBackground(new Color(135, 206, 250));
frame.setBounds(100, 100, 906, 569);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(new Color(30, 144, 255));
frame.getContentPane().add(panel, BorderLayout.EAST);
panel.setLayout(new MigLayout("", "[]", "[][][][][][][][]"));
JButton newPersonButton = new JButton("New Person");
newPersonButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Data data = NewPerson.createPerson(frame);
if (data != null) {
JLabel lblHomer = new JLabel(data.names);
// lblHomer.setIcon(new ImageIcon("C:\\Users\\Tinmar\\Desktop\\HomerSimpson3.gif"));
panel_1.add(lblHomer, "cell 7 5");
panel_1.revalidate();
}
}
});
panel.add(newPersonButton, "cell 0 5");
JButton btnNewButton_1 = new JButton("New button");
panel.add(btnNewButton_1, "cell 0 6");
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
scrollPane = new JScrollPane();
tabbedPane.addTab("Tree", null, scrollPane, null);
panel_1 = new JPanel();
scrollPane.setViewportView(panel_1);
panel_1.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));
// JLabel lblHomer = new JLabel("Homer");
// lblHomer.setIcon(new ImageIcon("C:\\Users\\Tinmar\\Desktop\\HomerSimpson3.gif"));
// panel_1.add(lblHomer, "cell 7 5");
JScrollPane scrollPane_1 = new JScrollPane();
tabbedPane.addTab("Info", null, scrollPane_1, null);
frame.repaint();
}
//
// /**
// * Launch the application.
// */
// public static void main(String[] args) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// try {
// NewPerson window = new NewPerson();
// window.frame.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
public static class NewPerson extends JPanel {
private JTextField textFieldNames;
private JButton selectPictureButton;
private JLabel labelDateOfBirth;
private JTextField textFieldDateOfBirth;
private JLabel labelShortBio;
private JTextArea textAreaBio;
private JLabel labelSelectPicture;
private JButton buttonAdd;
private String fileID;
private Data data;
/**
* Create the application.
*/
private NewPerson() {
initialize();
}
public static Data createPerson(Component comp) {
NewPerson newPerson = new NewPerson();
Window win = SwingUtilities.getWindowAncestor(comp);
JDialog dialog = null;
if (win instanceof Frame) {
dialog = new JDialog((Frame) win, "New person", true);
} else if (win instanceof Dialog) {
dialog = new JDialog((Dialog) win, "New person", true);
} else {
dialog = new JDialog((Frame) null, "New person", true);
}
newPerson.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Component) {
Window win = SwingUtilities.getWindowAncestor((Component) source);
win.dispose();
}
}
});
dialog.add(newPerson);
dialog.pack();
dialog.setLocationRelativeTo(comp);
dialog.setVisible(true);
return newPerson.getData();
}
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
protected void fireActionPerformed() {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners != null && listeners.length > 0) {
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "created");
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
public Data getData() {
return data;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setBackground(new Color(135, 206, 250));
setLayout(new MigLayout("", "[][][grow]", "[][][][grow][][][]"));
JLabel labelNames = new JLabel("Name and Surname:");
add(labelNames, "cell 1 1,alignx trailing");
textFieldNames = new JTextField();
add(textFieldNames, "cell 2 1,growx");
textFieldNames.setColumns(10);
labelDateOfBirth = new JLabel("Date of birth:");
add(labelDateOfBirth, "cell 1 2,alignx center,aligny center");
textFieldDateOfBirth = new JTextField();
add(textFieldDateOfBirth, "cell 2 2,growx");
textFieldDateOfBirth.setColumns(10);
labelShortBio = new JLabel("Bio:");
add(labelShortBio, "cell 1 3,alignx center,aligny center");
textAreaBio = new JTextArea();
add(textAreaBio, "cell 2 3,grow");
labelSelectPicture = new JLabel("Select picture:");
add(labelSelectPicture, "cell 1 4,alignx center,aligny center");
selectPictureButton = new JButton("...");
selectPictureButton.setBackground(new Color(30, 144, 255));
selectPictureButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser chooser = new JFileChooser(new File(System.getProperty("user.home") + "\\Desktop"));
chooser.setDialogTitle("Select Location");
chooser.setFileSelectionMode(JFileChooser.APPROVE_OPTION);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
fileID = chooser.getSelectedFile().getPath();
// txtField.setText(fileID);
}
}
});
add(selectPictureButton, "cell 2 4");
buttonAdd = new JButton("Add");
buttonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String names = textFieldNames.getText();
String dateBirth = textFieldDateOfBirth.getText();
String bio = textAreaBio.getText();
data = new Data(names, dateBirth, bio, fileID);
fireActionPerformed();
}
});
buttonAdd.setBackground(new Color(30, 144, 255));
add(buttonAdd, "cell 2 6,grow");
}
}
public static class Data {
private final String names;
private final String dateBirth;
private final String bio;
private final String fileID;
private Data(String names, String dateBirth, String bio, String fileID) {
this.names = names;
this.dateBirth = dateBirth;
this.bio = bio;
this.fileID = fileID;
}
}
}
Don't rely on static to provide functionality across classes. If you HAVE to have something from another class, pass it as a reference. static is not your friend and you should be careful and wary of it's use
Don't expose the fields of your class without very good reason, rely on interfaces to allow classes to provide or get information. This limits what other classes can do.
Separate and isolate responsibility
Take a look at How to Use Trees

The same way that NewFamilyTree's frame is accessible in NewPerson when you add the button to it, the scrollPane must also be accessible in NewPerson, if you want to add a label from that class. So just do the same thing with scrollPane as what you did with frame to be able to use it in NewPerson.

I assumed that the JScrollPane and addButton are in different frames... although it will work for sure if they are in the same frame.
Basically you need to provide getters for the JScrollPane and the JPanel, so that they can be accessed from the NewPerson class.
In the action listener of the buttonAdd, you need to increase the preferred size of the panel,, if the labels don't feet in the current size of the panel. The scrollbars will appear automatically when the preferred size of the panel are bigger that the view size of the JScrollPane.
Please see the code below:
NewFamilyTree.jva:
package dva.test001;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class NewFamilyTree {
private JFrame frame;
private JScrollPane scrollPane;
private JPanel panel;
public NewFamilyTree() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setTitle("New family tree");
frame.setBounds(100, 100, 906, 569);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
panel = new JPanel();
panel.setPreferredSize(new Dimension(700, 300));
panel.setLayout(null);
scrollPane = new JScrollPane(panel);
tabbedPane.addTab("Tree", null, scrollPane, null);
frame.setVisible(true);
}
public static void main(String[] args) {
NewFamilyTree ft = new NewFamilyTree();
NewPerson np = new NewPerson(ft);
}
public JFrame getFrame() {
return frame;
}
public JScrollPane getScrollPane() {
return scrollPane;
}
public JPanel getPanel() {
return panel;
}
}
NewPerson.java:
package dva.test001;
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.JLabel;
public class NewPerson {
private NewFamilyTree familyTree;
private static final int labelHeight = 30;
public NewPerson(NewFamilyTree familyTree) {
this.familyTree = familyTree;
init();
}
public void init() {
JFrame frame = new JFrame();
frame.setTitle("New Person");
frame.setBounds(100, 500, 906, 100);
JButton buttonAdd = new JButton("Add");
buttonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String names = "names"; //textFieldNames.getText();
String dateBirth = "date"; //textFieldDateOfBirth.getText();
String bio = "bio"; //textAreaBio.getText();
//Data newData = new Data(names, dateBirth, bio, fileID);
//code that puts new label on scrollpane from NewFamilyTree.java
JLabel lbl = new JLabel(names);
int top = familyTree.getPanel().getComponentCount() * labelHeight;
if(top + labelHeight > familyTree.getPanel().getHeight()) {
familyTree.getPanel().setPreferredSize(new Dimension(familyTree.getPanel().getWidth(), top + labelHeight));
familyTree.getScrollPane().revalidate();
}
familyTree.getPanel().add(lbl);
lbl.setBounds(10, top, 100, labelHeight);
}
});
buttonAdd.setBackground(new Color(30, 144, 255));
frame.getContentPane().add(buttonAdd);
frame.setVisible(true);
}
}

Related

how to use a template dialog panel for multiple buttons?

I'm writing a GUI in java. I have a JXTable in which I currently only have static data, but I want allow the user to input data by using a template panel that I have created.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
public class Template_StackOverflowExample extends JPanel{
private JPanel diagPanel = new dialogTemplate();
Object[] columnIdentifiers = {
"id",
"imei",
};
Object[][] data = {
{"1", "123"},
{"2", "123"},
{"3", "123"}
};
private JDialog dialog;
private static DefaultTableModel model;
public Template_StackOverflowExample(){
setLayout(new BorderLayout());
JPanel pane = new JPanel(new BorderLayout());
JButton addRow = new JButton("Add Row");
addRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
openRowPane("Add Row");
}
});
JButton editRow = new JButton("Edit Row");
editRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
openRowPane("Edit Row");
}
});
JPanel buttonPane = new JPanel(new GridLayout(0, 1));
TitledBorder buttonBorder = new TitledBorder("Buttons");
buttonPane.setBorder(buttonBorder);
buttonPane.add(addRow);
buttonPane.add(editRow);
model = new DefaultTableModel();
model.setColumnIdentifiers(columnIdentifiers);
JTable table = new JTable(model);
for(int i = 0; i < data.length; i++){
model.insertRow(i, data[i]);
}
JScrollPane scrollPane = new JScrollPane(table);
pane.add(buttonPane, BorderLayout.LINE_END);
pane.add(scrollPane, BorderLayout.CENTER);
add(pane, BorderLayout.CENTER);
}
public void openRowPane(String name){
if(dialog == null){
Window win = SwingUtilities.getWindowAncestor(this);
if(win != null){
dialog = new JDialog(win, name, ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(diagPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true);
}
public static void createAndShowGUI(){
JFrame frame = new JFrame("MCVE");
Template_StackOverflowExample mainPanel = new Template_StackOverflowExample();
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
class dialogTemplate extends JPanel{
private JComponent[] content;
private String[] labelHeaders = {
"ID:",
"IMEI:",
};
public dialogTemplate(){
JPanel diagTemplate = new JPanel();
diagTemplate.setLayout(new BorderLayout());
JPanel rowContent = new JPanel(new GridLayout(0, 2));
JLabel idLabel = null;
JLabel imeiLabel = null;
JLabel[] labels = {
idLabel,
imeiLabel,
};
JTextField idTextField = new JTextField(20);
JTextField imeiTextField = new JTextField(20);
content = new JComponent[] {
idTextField,
imeiTextField,
};
for(int i = 0; i < labels.length; i++){
labels[i] = new JLabel(labelHeaders[i]);
rowContent.add(labels[i]);
rowContent.add(content[i]);
labels[i].setLabelFor(content[i]);
}
JButton save = new JButton("Save");
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
JPanel buttonPane = new JPanel(new GridLayout(0, 1, 5, 5));
buttonPane.add(save);
buttonPane.add(cancel);
buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
diagTemplate.add(buttonPane, BorderLayout.PAGE_END);
diagTemplate.add(rowContent, BorderLayout.CENTER);
add(diagTemplate);
}
public void closeWindow(){
Window win = SwingUtilities.getWindowAncestor(this);
if(win != null) {
win.dispose();
}
}
}
As you might see both of the buttons in the pane creates the dialog that is created first ("Add Row" or "Edit Row"). I want them to create different dialogs so that the editing of data doesn't conflict with the addition of data.
Thanks in advance.
Assign a different dialog-creating method to each button so you can open two dialogs:
public void openRowPane(String name){
if(dialog == null){
Window win = SwingUtilities.getWindowAncestor(this);
//change modality
dialog = new JDialog(win, name, ModalityType.MODELESS);
dialog.getContentPane().add(diagPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
dialog.setVisible(true);
}
public void openRowPane2(String name){
if(dialog2 == null){
Window win = SwingUtilities.getWindowAncestor(this);
//change modality
dialog2 = new JDialog(win, name, ModalityType.MODELESS);
dialog2.getContentPane().add(diagPanel2);
dialog2.pack();
dialog2.setLocationRelativeTo(null);
}
dialog2.setVisible(true);
}

is it possible to close JOptionPane.showMessageDialog(buttonPanel," ") with timer?if it's possible pls tell me how(the program code is down)

import javax.swing.*; // Graphics import java.awt.Color; // Graphics Colors
import java.awt.event.ActionListener; // Events
import java.awt.event.ActionEvent; // Events
public class ButtonDemo_Extended implements ActionListener {
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel, redScore, blueScore;
JButton redButton, blueButton, resetButton;
public JPanel createContentPane() {
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(10, 10);
titlePanel.setSize(250, 30);
totalGUI.add(titlePanel);
redLabel = new JLabel("Red Team");
redLabel.setLocation(0, 0);
redLabel.setSize(120, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel);
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(130, 0);
blueLabel.setSize(120, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(260, 30);
totalGUI.add(scorePanel);
redScore = new JLabel("" + redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(120, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
blueScore = new JLabel("" + blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(120, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(260, 70);
totalGUI.add(buttonPanel);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(120, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(130, 0);
blueButton.setSize(120, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 40);
resetButton.setSize(250, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == redButton) {
redScoreAmount = redScoreAmount + 1;
redScore.setText("" + redScoreAmount);
JOptionPane.showMessageDialog(buttonPanel, "GOOOOOOOOOOOL");
} else if (e.getSource() == blueButton) {
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText("" + blueScoreAmount);
JOptionPane.showMessageDialog(buttonPanel, "GOOOOOOOOOOOL");
} else if (e.getSource() == resetButton) {
redScoreAmount = 0;
blueScoreAmount = 0;
redScore.setText("" + redScoreAmount);
blueScore.setText("" + blueScoreAmount);
}
}
private static void createAndShowGUI() { // For this Class Onlyyyyyyyyyyyy .
JFrame.setDefaultLookAndFeelDecorated(true); // Style Of Frame
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended demo = new ButtonDemo_Extended();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 190);
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
} }
this might be one way to do it:
`
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class AutoCloseJOption {
private static final int TIME_VISIBLE = 3000;
public static void main(String[] args) {
final JFrame frame1 = new JFrame("My App");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(100, 100);
frame1.setLocation(100, 100);
JButton button = new JButton("My Button");
frame1.getContentPane().add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = new JOptionPane("Message", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(null, "Title");
dialog.setModal(false);
dialog.setVisible(true);
new Timer(TIME_VISIBLE, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
}).start();
}
});
frame1.setVisible(true);
}
}`
I hope this helps you

How do I use CardLayout for my Java Program for Login and Menu Items

I am creating a "Store" program that basically can allow an employee to log in with a username and password I provide. After logging in, the employee can then see a "main menu" with four buttons: Sales Register, PLU Settings, Settings, and Logout. From this screen, the employee can proceed by clicking on any of the buttons to navigate to that screen. I do not want a new window to popup every time a button is clicked, but instead I want there to be some transition (or no transition) to go to the page that is clicked.
So to give an example: When the employee starts the program, he/she is greeted with the login menu. Then the employee enters his/her login information and hits login. If the info is incorrect, the employee is prompted to re-enter the info. If the info is correct, the employee is now sent to the main menu. At the main menu the employee selects "Sales Register" and the program goes to the sales register. All of this should happen in one window.
I have added the code of what I have been able to do, so far. I have created all of the buttons and labels, but I can't get them to show up on the JFrame and use the CardLayout. Also, I do not know how to link the Login code with the CardLayout.
Thank you for helping me. Here is the code:
Main Menu Code (storeMainMenu.java)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class storeMainMenu implements ActionListener {
String loginString = "Login";
String salesRegisterString = "Sales Register";
String pluSettingsString = "PLU Settings";
String settingsString = "Settings";
String logoutString = "Logout";
//JFrame
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
Color myColor = Color.decode("#F1E0B8");
//JPanel
static JPanel buttonPanel = new JPanel();
JPanel test1 = new JPanel();
JPanel test2 = new JPanel();
JPanel test3 = new JPanel();
JPanel test4 = new JPanel();
//Buttons
JButton salesRegister = new JButton("Sales Register");
JButton pluSettings = new JButton("PLU Settings");
JButton settings = new JButton("Settings");
JButton logout = new JButton("Logout");
//Label
JLabel header = new JLabel("Store Register");
JLabel test_1 = new JLabel("Test 1");
JLabel test_2 = new JLabel("Test 2");
JLabel test_3 = new JLabel("Test 3");
JLabel test_4 = new JLabel("Test 4");
public storeMainMenu ()
{
//Header
header.setFont(new Font("Myriad", Font.PLAIN, 50));
header.setBounds((width/6),0,1000,100);
//Sales Register Bounds
salesRegister.setBounds(100, 100, 500, 250);
//PluSettings Bounds
pluSettings.setBounds(700, 100, 500, 250);
//Settings Bounds
settings.setBounds(100, 500, 500, 250);
//Logout Bounds
logout.setBounds(700, 500, 500, 250);
//JPanel bounds
buttonPanel.setLayout(null);
//TEST JPANEL
test1.setLayout(null);
test2.setLayout(null);
test3.setLayout(null);
test4.setLayout(null);
test1.setSize(width, height);
test2.setSize(width,height);
test3.setSize(width, height);
test4.setSize(width, height);
//Test JPANEL Labels
test_1.setFont(new Font("Myriad", Font.PLAIN, 50));
test_1.setBounds((width/6),0,1000,100);
test_2.setFont(new Font("Myriad", Font.PLAIN, 50));
test_2.setBounds((width/6),0,1000,100);
test_3.setFont(new Font("Myriad", Font.PLAIN, 50));
test_3.setBounds((width/6),0,1000,100);
test_4.setFont(new Font("Myriad", Font.PLAIN, 50));
test_4.setBounds((width/6),0,1000,100);
//Adding to test JPanel
test1.add(test_1);
test2.add(test_2);
test3.add(test_3);
test4.add(test_4);
//Adding to JFrame
buttonPanel.add(header);
buttonPanel.add(salesRegister);
buttonPanel.add(pluSettings);
buttonPanel.add(settings);
buttonPanel.add(logout);
}
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = new CardLayout();
if (e.getSource() == salesRegister) {
cardLayout.show(test1, salesRegisterString);
}
if (e.getSource() == pluSettings) {
cardLayout.show(test2, pluSettingsString);
}
if (e.getSource() == settings) {
cardLayout.show(test3, settingsString);
}
if (e.getSource() == logout) {
cardLayout.show(test4, logoutString);
}
}
static void createAndShowGUI() {
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
Color myColor = Color.decode("#F1E0B8");
JFrame frame = new JFrame("Store");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(width, height);
frame.setBackground(myColor);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(buttonPanel);
}
public static void main (String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
Login Code (login.java):
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class login extends JFrame {
//declaring our swing components
JLabel l_name,l_pass;
JTextField t_name;
JPasswordField t_pass; //A special JTextField but hides input text
JButton button;
Container c;
boolean checkLogin = false;
//a inner class to handling ActionEvents
handler handle;
//a separate class for processing database connection and authentication
database db;
login()
{
super("Login form");
c=getContentPane();
c.setLayout(new FlowLayout());
//extra classes
db=new database();
handle =new handler();
//swing components
l_name=new JLabel("Username");
l_pass=new JLabel("Password");
t_name=new JTextField(10);
t_pass=new JPasswordField(10);
button=new JButton("Login");
//adding actionlistener to the button
button.addActionListener(handle);
//add to contaienr
c.add(l_name);
c.add(t_name);
c.add(l_pass);
c.add(t_pass);
c.add(button);
//visual
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,175);
}
public static void main(String args[])
{
#SuppressWarnings("unused")
login sample=new login();
}
//an inner class .You can also write as a separate class
class handler implements ActionListener
{
//must implement method
//This is triggered whenever the user clicks the login button
public void actionPerformed(ActionEvent ae)
{
//checks if the button clicked
if(ae.getSource()==button)
{
char[] temp_pwd=t_pass.getPassword();
String pwd=null;
pwd=String.copyValueOf(temp_pwd);
System.out.println("Username,Pwd:"+t_name.getText()+","+pwd);
//The entered username and password are sent via "checkLogin()" which return boolean
if(db.checkLogin(t_name.getText(), pwd))
{
//a pop-up box
JOptionPane.showMessageDialog(null, "You have logged in successfully","Success",
JOptionPane.INFORMATION_MESSAGE);
checkLogin = true;
}
else
{
//a pop-up box
JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
JOptionPane.ERROR_MESSAGE);
checkLogin = false;
}
}//if
}//method
}//inner class
}
Database Code (the login code references this code for the MySQL info) (database.java)
import java.sql.*;
public class database
{
Connection con;
PreparedStatement pst;
ResultSet rs;
database()
{
try{
//MAKE SURE YOU KEEP THE mysql_connector.jar file in java/lib folder
//ALSO SET THE CLASSPATH
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/SchoolStoreUsers","root","schoolstore");
pst=con.prepareStatement("select * from users where uname=? and pwd=?");
}
catch (Exception e)
{
System.out.println(e);
}
}
//ip:username,password
//return boolean
public Boolean checkLogin(String uname,String pwd)
{
try {
pst.setString(1, uname); //this replaces the 1st "?" in the query for username
pst.setString(2, pwd); //this replaces the 2st "?" in the query for password
//executes the prepared statement
rs=pst.executeQuery();
if(rs.next())
{
//TRUE iff the query founds any corresponding data
return true;
}
else
{
return false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("error while validating"+e);
return false;
}
}
}
Stop using null layouts, seriously, this is the source of more problems then just about anything else with Swing
When adding components to a panel using CardLayout, each panel MUST have a name
In your actionPerformed method, this is not how CardLayout works. To start with, you're creating a new instance of CardLayout, which contains NO components, so how did you expect it to be able to suddenly figure out what to switch to? When using CardLayout#show, the component reference is the parent component that that is begin manged by the CardLayout
Updated with example
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyCardLayout {
public static void main(String[] args) {
new MyCardLayout();
}
public MyCardLayout() {
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 JPanel mainPane;
private JPanel navPane;
private List<String> pages;
private int currentPage;
public TestPane() {
pages = new ArrayList<>(25);
setLayout(new BorderLayout());
mainPane = new JPanel(new CardLayout());
navPane = new JPanel();
for (int index = 0; index < 10; index++) {
addPageTo(mainPane, "Page" + index, new JLabel("Page " + index, JLabel.CENTER));
}
JButton btnPrev = new JButton("<<");
JButton btnNext = new JButton(">>");
navPane.add(btnPrev);
navPane.add(btnNext);
btnPrev.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentPage(getCurrentPage() - 1);
}
});
btnNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentPage(getCurrentPage() + 1);
}
});
add(mainPane);
add(navPane, BorderLayout.SOUTH);
setCurrentPage(0);
}
public int getCurrentPage() {
return currentPage;
}
protected void setCurrentPage(int page) {
if (pages.size() > 0) {
if (page < 0) {
page = pages.size() - 1;
} else if (page >= pages.size()) {
page = 0;
}
currentPage = page;
CardLayout layout = (CardLayout)mainPane.getLayout();
layout.show(mainPane, pages.get(currentPage));
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void addPageTo(JPanel pane, String name, Component comp) {
pages.add(name);
pane.add(comp, name);
}
}
}

After updating JComboBox, how to refresh length of box

I am trying to create a way to update a JComboBox so that when the user enters something into the text field, some code will process the entry and update the JComboBox accordingly.The one issue that I am having is I can update the JComboBox, but the first time it is opened, the box has not refresh the length of the options in it and as seen in the code below it displays extra white space. I do not know if there is a better different way to do this, but this is what I came up with.
Thanks for the help,
Dan
import java.awt.event.*;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Catch{
public static JComboBox dropDown;
public static String dropDownOptions[] = {
"Choose",
"1",
"2",
"3"};
public static void main(String[] args) {
dropDown = new JComboBox(dropDownOptions);
final JTextField Update = new JTextField("Update", 10);
final JFrame frame = new JFrame("Subnet Calculator");
final JPanel panel = new JPanel();
frame.setSize(315,430);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Update.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent arg0) {
}
public void focusLost(FocusEvent arg0) {
dropDown.removeAllItems();
dropDown.insertItemAt("0", 0);
dropDown.insertItemAt("1", 1);
dropDown.setSelectedIndex(0);
}
});
panel.add(Update);
panel.add(dropDown);
frame.getContentPane().add(panel);
frame.setVisible(true);
Update.requestFocus();
Update.selectAll();
}
}
1) JTextField listening for ENTER key from ActionListener
2) remove FocusListener
3) example about add new Item as last Item from JTextField to the JList, only you have to modify for JComboBox and add method insertItemAt() correctly
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ListBottom2 {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JTextField textField = new JTextField("Use Enter to Add");
private JPanel panel = new JPanel(new BorderLayout());
public ListBottom2() {
model.addElement("First");
list.setVisibleRowCount(5);
panel.setBackground(list.getBackground());
panel.add(list, BorderLayout.SOUTH);
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setPreferredSize(new Dimension(200, 100));
frame.add(scrollPane);
frame.add(textField, BorderLayout.NORTH);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField textField = (JTextField) e.getSource();
DefaultListModel model = (DefaultListModel) list.getModel();
model.addElement(textField.getText());
int size = model.getSize() - 1;
list.scrollRectToVisible(list.getCellBounds(size, size));
textField.setText("");
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ListBottom2 frame = new ListBottom2();
}
});
}
}

Applet not appearing full

I just created an applet
public class HomeApplet extends JApplet {
private static final long serialVersionUID = -7650916407386219367L;
//Called when this applet is loaded into the browser.
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
// setSize(400, 400);
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
private void createGUI() {
RconSection rconSection = new RconSection();
rconSection.setOpaque(true);
// CommandArea commandArea = new CommandArea();
// commandArea.setOpaque(true);
JTabbedPane tabbedPane = new JTabbedPane();
// tabbedPane.setSize(400, 400);
tabbedPane.addTab("Rcon Details", rconSection);
// tabbedPane.addTab("Commad Area", commandArea);
setContentPane(tabbedPane);
}
}
where the fisrt tab is:
package com.rcon;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.Bean.RconBean;
import com.util.Utility;
public class RconSection extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -9021500288377975786L;
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
// private DynamicTree treePanel;
public RconSection() {
// super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new GridLayout(1,3));
panel1.add(testButton);
panel1.add(clearButton);
add(panel);
add(panel1);
// add(panel, BorderLayout.NORTH);
// add(panel1, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals(TEST_COMMAND)){
String ip = ipText.getText().trim();
if(!Utility.checkIp(ip)){
ipText.requestFocusInWindow();
ipText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Ip!!!");
return;
}
String port = portText.getText().trim();
if(port.equals("") || !Utility.isIntNumber(port)){
portText.requestFocusInWindow();
portText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Port!!!");
return;
}
String pass = rPassText.getText().trim();
if(pass.equals("")){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Enter Rcon Password!!!");
return;
}
RconBean rBean = RconBean.getBean();
rBean.setIp(ip);
rBean.setPassword(pass);
rBean.setPort(Integer.parseInt(port));
if(!Utility.testConnection()){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Rcon!!!");
return;
}else{
JOptionPane.showMessageDialog(this,"Correct Rcon!!!");
return;
}
}
else if(arg0.getActionCommand().equals(CLEAR_COMMAND)){
ipText.setText("");
portText.setText("");
rPassText.setText("");
}
}
}
it appears as
is has cropped some data how to display it full and make the applet non resizable as well. i tried setSize(400, 400); but it didnt helped the inner area remains the same and outer boundaries increases
Here's another variation on your layout. Using #Andrew's tag-in-source method, it's easy to test from the command line:
$ /usr/bin/appletviewer HomeApplet.java
// <applet code='HomeApplet' width='400' height='200'></applet>
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class HomeApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
createGUI();
}
});
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private void createGUI() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Rcon1", new RconSection());
tabbedPane.addTab("Rcon2", new RconSection());
this.add(tabbedPane);
}
private static class RconSection extends JPanel implements ActionListener {
private static final String TEST_COMMAND = "test";
private static final String CLEAR_COMMAND = "clear";
private JTextField ipText = new JTextField();
private JTextField portText = new JTextField();
private JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel buttons = new JPanel(); // default FlowLayout
buttons.add(testButton);
buttons.add(clearButton);
add(panel, BorderLayout.NORTH);
add(buttons, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
}
}
As I mentioned in a comment, this question is really about how to layout components in a container. This example presumes you wish to add the extra space to the text fields and labels. The size of the applet is set in the HTML.
200x130 200x150
/*
<applet
code='FixedSizeLayout'
width='200'
height='150'>
</applet>
*/
import java.awt.*;
import javax.swing.*;
public class FixedSizeLayout extends JApplet {
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initGui();
}
});
}
private void initGui() {
JTabbedPane tb = new JTabbedPane();
tb.addTab("Rcon Details", new RconSection());
setContentPane(tb);
validate();
}
}
class RconSection extends JPanel {
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout(3,3));
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
panel1.add(testButton);
panel1.add(clearButton);
add(panel, BorderLayout.CENTER);
add(panel1, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Container c = new RconSection();
JOptionPane.showMessageDialog(null, c);
}
});
}
}
Size of applet viewer does not depend on your code.
JApplet is not window, so in java code you can't write japplet dimensions. You have to change run settings. I don't know where exactly are in other ide's, but in Eclipse you can change dimensions in Project Properties -> Run/Debug settings -> click on your launch configurations file (for me there were only 1 - main class) -> edit -> Parameters. There you can choose width and height for your applet. save changes and you are good to go

Categories

Resources