I have a MainForm class that extends JFrame and has a JList in it.
Now on clicking a button a JDialog pops up, to enter credentials, which in turn downloads a list of values which is to be populated in the Jlist of the parent window.
Now how do I populate my mainForm attribute from my child class ?
MainForm.java
public class MainForm extends JFrame {
static MainForm mainForm;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
mainForm = new MainForm();
mainForm.setVisible(true);
}
});
}
public MainForm() {
loadUI();
}
private void loadUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
final JList<String> jList = new JList<String>();
final JButton settings = new JButton(settingImage);
settings.setBorder(new EmptyBorder(3, 0, 3, 0));
settings.setBounds(50, 60, 100, 30);
vertical.add(settings);
settings.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
LoginDialog loginDlg = new LoginDialog(mainForm);
loginDlg.setVisible(true);
// if logon successfully
if(loginDlg.isSucceeded()){
settings.setText("Hi " + loginDlg.getUsername() + "!");
}
}
});
add(vertical, BorderLayout.WEST);
add(jList, BorderLayout.CENTER);
DialogWindow.java
public LoginDialog(final Frame parent) {
super(parent, "Login", true);
//
JPanel panel = new JPanel(new GridBagLayout());
//some more lines of code
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ftpAuthenticationVO.setIp(urlIP.getText());
ftpAuthenticationVO.setUsername(tfUsername.getText());
ftpAuthenticationVO.setPassword(pfPassword.getText());
FileUtils.saveFTPDetails(ftpAuthenticationVO);
if(ftpConnect.startFTP(CommonConstants.TEMP_TXT_FILE));
{
List<String> list = readSplitTextFiles.readTextFile(CommonConstants.TEMP_TXT_FILE);
//This is the value that is to be populated in the Jlist inside the parent window.
}
Just make your JList as attribute of the MainForm
public class MainForm extends JFrame {
private JList jlist;
.
.
.
private void loadUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
jList = new JList<String>();
final JButton settings = new JButton(settingImage);
settings.setBorder(new EmptyBorder(3, 0, 3, 0));
settings.setBounds(50, 60, 100, 30);
vertical.add(settings);
.
.
}
public void setJListModel(List<String> list){
jlist.setModel(new Vector(list));
}
}
And in JDialog
public void actionPerformed(ActionEvent e) {
ftpAuthenticationVO.setIp(urlIP.getText());
ftpAuthenticationVO.setUsername(tfUsername.getText());
ftpAuthenticationVO.setPassword(pfPassword.getText());
FileUtils.saveFTPDetails(ftpAuthenticationVO);
if(ftpConnect.startFTP(CommonConstants.TEMP_TXT_FILE));
{
List<String> list = readSplitTextFiles.readTextFile(CommonConstants.TEMP_TXT_FILE);
(MainForm)parent.setJListModel(list);
}
Also parent must be declared as final.
Related
Please, how can I appear automatically some JTextField from what user choose in JComboBox ?
My example is simple. I have a JComboBox in my box with some operation. And depending on what the user choose from this JComboBox, I appear one or more JTextField.
I have this code:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CalculatriceFenetre fenetre = new CalculatriceFenetre();
fenetre.setVisible(true);
}
});
}
.
public class CalculatriceFenetre extends JFrame {
private JTextField field1, field2;
private JComboBox liste;
public CalculatriceFenetre() {
super();
build();
}
private void build() {
setTitle("Calculatrice");
setSize(400, 200);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(buildContentPane());
}
private JPanel buildContentPane() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(Color.white);
field1 = new JTextField();
field1.setColumns(10);
field2 = new JTextField();
field2.setColumns(10);
field2.setVisible(false);
panel.add(field1);
panel.add(field2);
liste = new JComboBox(new OperateursModel());
liste.addActionListener(new CustomActionListener());
panel.add(liste);
return panel;
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (liste.getSelectedItem().equals("op1")) {
field2.setVisible(true);
}
}
}
.
public class OperateursModel extends DefaultComboBoxModel {
private ArrayList<String> operateurs;
public OperateursModel(){
super();
operateurs = new ArrayList<String>();
operateurs.add("op1");
}
public String getSelectedOperateur(){
return (String)getSelectedItem();
}
#Override
public Object getElementAt(int index) {
return operateurs.get(index);
}
#Override
public int getSize() {
return operateurs.size();
}
#Override
public int getIndexOf(Object element) {
return operateurs.indexOf(element);
}
}
And depending on what the user choose from this JComboBox, I appear one or more JTextField.
Then you can write an ActionListener to handle the selection of an item from the combo box.
You can start by reading the section from the Swing tutorial on How to Use a Combo Box for a working example that uses an ActionListener.
In your case you want to add a text field to the frame so the code would be something like:
JTextField textField = new JTextField(10);
frame.add( textField );
frame.revalidate();
frame.repaint();
Also, there is no need for you to create a custom ComboBoxModel. You can just add items to the default model. Again, the tutorial will show you how to do this.
Like I mentioned, this is an easy approach for your question. Create all the JTextFields you need first and toggle its visibility instead of removing and adding it on run time.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DynamicTextFieldsApp
{
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("JTextField Toggler");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.add(new DisplayPanel());
f.pack();
f.setLocationRelativeTo(null);
}});
}
}
A simple JPanel with comboBox and several JTextFields.
class DisplayPanel extends JPanel
{
public static final int PLAYERS = 5;
private JComboBox cmbPlayerNumber;
private JTextField[] txtPlayerName;
private JLabel lblPlayerNumber;
public DisplayPanel(){
setPreferredSize(new Dimension(170, 240));
createComponents();
initComponents();
loadComponents();
setBoundsForComponents();
}
private void createComponents(){
cmbPlayerNumber = new JComboBox(new String[]{"1", "2", "3", "4", "5"});
txtPlayerName = new JTextField[PLAYERS];
lblPlayerNumber = new JLabel("Num of Players");
}
private void initComponents(){
for(int x=0; x<PLAYERS; x++){
txtPlayerName[x] = new JTextField("No Name " + (x+1));
txtPlayerName[x].setVisible(false);
}
cmbPlayerNumber.setSelectedIndex(-1);
cmbPlayerNumber.addActionListener(new CmbListener());
}
private void loadComponents(){
add(cmbPlayerNumber);
add(lblPlayerNumber);
for(int x=0; x<PLAYERS; x++)
add(txtPlayerName[x]);
}
private void setBoundsForComponents(){
setLayout(null);
lblPlayerNumber.setBounds(10, 0, 150, 30);
cmbPlayerNumber.setBounds(10, 30, 150, 30);
for(int x=0; x<PLAYERS; x++)
txtPlayerName[x].setBounds(10, (30*x)+70, 150, 30);
}
private class CmbListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int numOfPlayers = cmbPlayerNumber.getSelectedIndex() + 1;
for(int x=0; x<numOfPlayers; x++)
txtPlayerName[x].setVisible(true);
for(int x=numOfPlayers; x<PLAYERS; x++){
txtPlayerName[x].setVisible(false);
txtPlayerName[x].setText("No name " + (x+1));
}
}
}
}
And of course, you can work with some layout manager instead of null layout.
I'm using webcam-capture libraries and AWT to develop a simple interface for taking pictures from a webcam. The buttons and the combobox in my JFrame disappear after minimizing the window or after moving another window on top of it. Moving the pointer over the frame restores the components' visibility. I'm not skilled with Java UI, I can't figure out what's wrong with my code.
#SuppressWarnings("serial")
public class ImageCaptureManager extends JFrame {
private class SkipCapture extends AbstractAction {
public SkipCapture() {
super(“Skip”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class SnapMeAction extends AbstractAction {
public SnapMeAction() {
super(“Snap”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class captureCompleted extends AbstractAction {
public captureCompleted() {
super(“Completed”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class saveImage extends AbstractAction {
public saveImage() {
super(“Save”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class deleteImage extends AbstractAction {
public deleteImage() {
super(“Delete”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class StartAction extends AbstractAction implements Runnable {
public StartAction() {
super(“Start”);
}
#Override
public void actionPerformed(ActionEvent e) {
btStart.setEnabled(false);
btSnapMe.setEnabled(true);
executor.execute(this);
}
#Override
public void run() {
panel.start();
}
}
private Executor executor = Executors.newSingleThreadExecutor();
private Dimension captureSize = new Dimension(640, 480);
private Dimension displaySize = new Dimension(640, 480);
private Webcam webcam = Webcam.getDefault();
private WebcamPanel panel;
private JButton btSnapMe = new JButton(new SnapMeAction());
private JButton btStart = new JButton(new StartAction());
private JButton btComplete = new JButton(new captureCompleted());
private JButton btSave = new JButton(new saveImage());
private JButton btDelete = new JButton(new deleteImage());
private JButton btSkip = new JButton(new SkipCapture());
private JComboBox comboBox = new JComboBox();
public ImageCaptureManager() {
super(“Frame”);
this.addWindowListener( new WindowAdapter()
{
#Override
public void windowDeiconified(WindowEvent arg0) {
}
public void windowClosing(WindowEvent e)
{
}
});
List<Webcam> webcams = Webcam.getWebcams();
for (Webcam webcam : webcams) {
System.out.println(webcam.getName());
if (webcam.getName().startsWith("USB2.0 Camera 1")) {
this.webcam = webcam;
break;
}
}
panel = new WebcamPanel(webcam, displaySize, false);
webcam.setViewSize(captureSize);
panel.setFPSDisplayed(true);
panel.setFillArea(true);
btSnapMe.setEnabled(false);
btSave.setEnabled(false);
btDelete.setEnabled(false);
setLayout(new FlowLayout());
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new GridLayout(10, 1));
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSnapMe);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSave);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btDelete);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btComplete);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSkip);
JLabel label1 = new JLabel("Test");
label1.setText(“Bla bla bla”);
JLabel label2 = new JLabel("Test");
label2.setText(" ");
Panel captionAndWebcamPanel = new Panel();
captionAndWebcamPanel.add(label1);
captionAndWebcamPanel.add(label2);
captionAndWebcamPanel.add(panel);
captionAndWebcamPanel.add(label2);
captionAndWebcamPanel.add(comboBox);
captionAndWebcamPanel.setLayout(new BoxLayout(captionAndWebcamPanel, BoxLayout.Y_AXIS));
add(captionAndWebcamPanel);
add(buttonPanel);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
btStart.doClick();
setSize(900,600);
}
}
You are mixing AWT and Swing components.
"Historically, in the Java language, mixing heavyweight and lightweight components in the same container has been problematic."
http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html
I suggest you try using JPanels instead of Panels for captionAndWebcamPanel and buttonPanel, I'd also set layout to captionAndWebcamPanel before adding components.
I am making a battleship game and I'm trying to figure out a way to control buttons in a pane so that I can drag drop them and keep track of their indexes with a default list model.If I add string or ImageIcons it works fine but with buttons I get something different.
Here's my code:
public class ListModelExample extends JPanel {
JList list;
DefaultListModel model;
int counter = 15;
public ListModelExample() {
setLayout(new BorderLayout());
model = new DefaultListModel();
list = new JList(model);
JScrollPane pane = new JScrollPane(list);
JButton addButton = new JButton("Add Element");
JButton removeButton = new JButton("Remove Element");
final JButton button = new JButton("button");
for (int i = 0; i < 5; i++)
model.addElement(button);
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addElement(button);
counter++;
}
});
removeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (model.getSize() > 0)
model.removeElementAt(0);
}
});
add(pane, BorderLayout.NORTH);
add(addButton, BorderLayout.WEST);
add(removeButton, BorderLayout.EAST);
}
public static void main(String s[]) {
JFrame frame = new JFrame("List Model Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ListModelExample());
frame.setSize(260, 200);
frame.setVisible(true);
}
}
If I add Buttons I get this result:
So my question is: How is it possible to make buttons appear normally and not as text in a default list model?
this could be done only by Renderer, put only String value to the DefaultListModel
don't put any JComponents to the XxxModel
I'd be use JPanel with JButtons instead of JList as containers (required to change getScrollableBlockIncrement / getScrollableUnitIncrement for natural scrolling in compare with JList or JTable)
example about both a.m. ways
import java.awt.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.*;
public class ListButtons extends JFrame {
private static final long serialVersionUID = 1L;
public ListButtons() {
setLayout(new GridLayout(0, 2, 10, 10));
DefaultListModel model = new DefaultListModel();
model.addElement(createButtons("one"));
model.addElement(createButtons("two"));
model.addElement(createButtons("three"));
model.addElement(createButtons("four"));
model.addElement(createButtons("five"));
model.addElement(createButtons("six"));
model.addElement(createButtons("seven"));
model.addElement(createButtons("eight"));
model.addElement(createButtons("nine"));
model.addElement(createButtons("ten"));
model.addElement(createButtons("eleven"));
model.addElement(createButtons("twelwe"));
JList list = new JList(model);
list.setCellRenderer(new PanelRenderer());
JScrollPane scroll1 = new JScrollPane(list);
final JScrollBar scrollBar = scroll1.getVerticalScrollBar();
scrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar.getValue());
}
});
add(scroll1);
JScrollPane scroll2 = new JScrollPane(createPanel());
add(scroll2);
final JScrollBar scrollBar1 = scroll2.getVerticalScrollBar();
scrollBar1.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar1.getValue());
}
});
}
public static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 1, 1));
panel.add(createButtons("one"));
panel.add(createButtons("two"));
panel.add(createButtons("three"));
panel.add(createButtons("four"));
panel.add(createButtons("five"));
panel.add(createButtons("six"));
panel.add(createButtons("seven"));
panel.add(createButtons("eight"));
panel.add(createButtons("nine"));
panel.add(createButtons("ten"));
panel.add(createButtons("eleven"));
panel.add(createButtons("twelwe"));
return panel;
}
public static JButton createButtons(String text) {
JButton button = new JButton(text);
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ListButtons frame = new ListButtons();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//frame.pack();
frame.setSize(270, 200);
frame.setVisible(true);
}
});
}
class PanelRenderer implements ListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JButton renderer = (JButton) value;
renderer.setBackground(isSelected ? Color.red : list.getBackground());
return renderer;
}
}
}
I have problem with this code
when I click on file and click on new ,new panel comes to screen and when I want to change JRadioBox status to change Label status,Label status changes but also the panel goes away :(
public class MainClass {
public static void main(String[] args) {
new MainFrame();
}
}
class Toolbar extends JPanel {
private JRadioButton Status1;
private JRadioButton Status2;
private ButtonGroup radioButtonGroup;
public Toolbar() {
super();
setLayout(new FlowLayout());
Status1 = new JRadioButton("Status1");
Status2 = new JRadioButton("Status2");
radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(Status2);
radioButtonGroup.add(Status1);
Status1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
MainFrame m = new MainFrame();
m.l.setText("Status1");
}
});
Status2.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
MainFrame m = new MainFrame();
m.l.setText("Status2");
}
});
add(Status1);
add(Status2);
}
}
class Panel extends JPanel {
public Panel() {
super();
setBackground(Color.MAGENTA);
}
}
class MenuBar extends JMenuBar {
private JMenu menu;
private JMenuItem fileItems;
public boolean panel = false;
public MenuBar() {
super();
menu = new JMenu("File");
add(menu);
fileItems = new JMenuItem("New");
menu.add(fileItems);
fileItems.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MainFrame mf = new MainFrame();
Panel p = new Panel();
mf.addPanel(p);
mf.add(new Toolbar(), BorderLayout.NORTH);
repaint();
}
});
}
}
class MainFrame extends JFrame {
public static JLabel l;
public MainFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 400);
l = new JLabel("No Status");
add(l, BorderLayout.SOUTH);
MenuBar mb = new MenuBar();
setJMenuBar(mb);
setVisible(true);
}
public void addPanel(Panel p) {
add(p, BorderLayout.CENTER);
}
}
Stop making new MainFrames all over the place. Create it once and maintain a handle to it for whenever you need it.
I have 2 windows. one got an empty JList and the other one got a button. So I want to add the value to the list whenever I press the button. Here is my code but not completed:
Window 1
final DefaultListModel<String> favouriteNames = new DefaultListModel<String>();
JList namesList = new JList(favouriteNames);
Window 2
public class button extends JFrame {
private JList namesList;
private DefaultListModel<String> favouriteNames;
this.namesList = namesList;
JButton addThis = new JButton("Add");
addThis.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
favouriteNames.addElement("Jack");
}
});
}
}
Pass an instance of your DefaultListModel to Window 2 in the constructor.
Edited to add: Here's how you pass an instance in a constructor.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ButtonFrame implements Runnable {
private JFrame frame;
private DefaultListModel favouriteNames;
public ButtonFrame(final DefaultListModel favouriteNames) {
this.favouriteNames = favouriteNames;
}
#Override
public void run() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton addThis = new JButton("Add");
addThis.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
favouriteNames.addElement("Jack");
}
});
frame.add(addThis);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new ButtonFrame(new DefaultListModel()));
}
}
I made a simpler version of my program, but still have a problem, I believe the ActionPerformed sends the data but the JList does not recognise it or or basically did not expect to receive it. So here is what I have done so far. So it is a bit more of my research and attempts, maybe it gives more details about the problem.
Main Window:
public class main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new ClassA();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
ClassA:
public class ClassA extends JFrame {
DefaultListModel<String> myList;
JList list;
public ClassA() {
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,1));
myList = new DefaultListModel<String>();
list = new JList(myList);
//ClassB sendsText = new ClassB(myList, list);
JButton find = new JButton("Find");
find.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
new ClassB().setVisible(true);
}
});
add(panel);
panel.add(find);
panel.add(list);
}
}
ClassB:
public class ClassB extends JFrame {
DefaultListModel<String> myList;
JList list;
public ClassB(DefaultListModel<String> myList, JList list){
this.myList = myList;
this.list = list;
}
public ClassB() {
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,1));
JButton addMe = new JButton("Add Me");
addMe.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
myList.addElement("Danial");
}
});
add(panel);
panel.add(addMe);
}
}