Why getcontentpane() is undefined? - java

I have a code here and I get this error. How do I fix the error for the code below?
Container container = getContentPane();
Here is the running code.
import java.awt.BorderLayout;
import java.awt.Container;
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.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class ModelJTable{
private DefaultTableModel model;
private JTable table;
public ModelJTable() {
super();
model = new DefaultTableModel();
model.addColumn("Product Name");
model.addColumn("Price");
model.addColumn("Quantity");
model.addColumn("Subtotal");
String[] socrates = { "Socrates", "", "469-399 B.C." };
model.addRow(socrates);
table = new JTable(model);
JButton addButton = new JButton("Add Philosopher");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String[] philosopher = { "", "", "" };
model.addRow(philosopher);
}
});
JButton removeButton = new JButton("Remove Selected Philosopher");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
model.removeRow(table.getSelectedRow());
}
});
JPanel inputPanel = new JPanel();
inputPanel.add(addButton);
inputPanel.add(removeButton);
Container container = getContentPane();
container.add(new JScrollPane(table), BorderLayout.CENTER);
container.add(inputPanel, BorderLayout.NORTH);
Global.uniFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Global.uniFrame.setSize(800, 300);
Global.uniFrame.setVisible(true);
}
public static class Global{
public static JFrame uniFrame = new JFrame();
}
private static void createGUI(){
new ModelJTable();
}
public static void main(String args[]) {
createGUI();
}
}
I change the code to this and it doesn't display the contents.
Container container = new Container();
container.add(new JScrollPane(table), BorderLayout.CENTER);
container.add(inputPanel, BorderLayout.NORTH);
Global.uniFrame.getContentPane();
Global.uniFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Global.uniFrame.setSize(800, 300);
Global.uniFrame.setVisible(true);

Because your class doesn't extend from anything that provides that method
public class ModelJTable{
nor does you current class implement such a method...
The only possible class (within your example) that could provide this functionality is the uniFrame in the Global class
... = Global.uniFrame.getContentPane();
To be honest, I would seriously avoid static references to ANY gui component, especially when they are not defined final. There is to much risk that the static reference will be changed or, if declared final locks you into a single possibility.
There is a also the risk that some other piece of code might try and do something it shouldn't, like remove everything...

There is no method getContentPane(). You probably forgot to extend another class.

Related

how to open frame from another frame Java Swing

I am making a program that has multiple sub-programs but when I am trying to open a new frame, it doesn't do anything.
The program that calls the frame:
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Options");
JButton notepad = new JButton("Notepad");
JButton todo = new JButton("To-Do List");
NoteListe noteListener = new NoteListe();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLayout(new GridLayout(1,2));
frame.add(notepad);
frame.add(todo);
notepad.addActionListener(noteListener);
}
}
The action listener for the notepad button:
import java.awt.event.*;
public class NoteListe implements ActionListener{
public void actionPerformed(ActionEvent e){
new MainNote();
}
}
The notepad:
import javax.swing.*;
import java.awt.*;
public class MainNote {
public static void main(String[] args) {
JFrame frame = new JFrame("Text Editor");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLayout(new GridLayout(2,1));
}
}
I really think you need to take a closer look at:
Providing Constructors for Your Classes
Defining Methods
Passing Information to a Method or a Constructor
These are really fundamental concepts and you should have firm grasp of them before you venture into the wild and unforgiving world of GUI development.
import java.awt.BorderLayout;
import java.awt.Component;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
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 MenuPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MenuPane extends JPanel {
public MenuPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(32, 32, 32, 32));
JButton notepad = new JButton("Notepad");
JButton todo = new JButton("To-Do List");
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(8, 8, 8, 8);
add(notepad, gbc);
add(todo, gbc);
notepad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MainNote note = MainNote.show(MenuPane.this);
note.setText("This is where your text goes");
}
});
}
}
public static class MainNote extends JPanel {
private JTextArea ta;
public MainNote() {
setLayout(new BorderLayout());
ta = new JTextArea(20, 40);
add(new JScrollPane(ta));
}
public void setText(String text) {
ta.setText(text);
}
public String getText() {
return ta.getText();
}
public static MainNote show(Component parent) {
MainNote mainNote = new MainNote();
JFrame frame = new JFrame("Text Editor");
frame.add(mainNote);
frame.pack();
frame.setLocationRelativeTo(parent);
frame.setVisible(true);
return mainNote;
}
}
}
Note: I've used a static method (show) to simplify the construction of another window. This is simply a delegation workflow, as I'm delegating the responsibility for creating the window to the method, but I'm still getting back an instance of the MainNote.
Because MainNote is simply a JPanel, it can be added to what ever container I want. Because I've "encapsulated" the functionality into the class itself, it makes it much easier to manage.

Update JTable from DefaultTableModel

so what i want to do is update a JTable when a button is pressed. Im using a DefaultTableModel as a source.
Table class:
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.Dimension;
public class TableDemo extends JPanel {
String[] columnNames = {"Tipo","Cantidad"};
DefaultTableModel dtm = new DefaultTableModel(null,columnNames);
final JTable table = new JTable(dtm);
public TableDemo() {
table.setPreferredScrollableViewportSize(new Dimension(500, 700));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
public void addRow(Object [] row)
{
dtm.addRow(row);
}
}
the form class:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
public class MyForm extends JFrame {
JPanel panel;
JLabel label;
JTextField txtName;
JTextField txtSurname;
JButton btnAccept;
TableDemo tb = new TableDemo();
public MyForm(){
initControls();
}
private void initControls() {
setTitle("Form Example");
setSize(600, 400);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(null);
label = new JLabel("Welcome to Swing");
label.setBounds(50, 10, 200, 30);
txtName = new JTextField();
txtName.setBounds(50, 50, 200, 30);
txtSurname = new JTextField();
txtSurname.setBounds(270, 50, 200, 30);
btnAccept = new JButton("Add");
btnAccept.setBounds(120, 100, 150, 30);
onAcceptClick();
TableDemo tablePanel = new TableDemo();
panel.add(label);
panel.add(txtName);
panel.add(txtSurname);
panel.add(btnAccept);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
tablePanel,panel );
splitPane.setDividerLocation(205);
splitPane.setEnabled(false);
getContentPane().add(splitPane);
}
private void onAcceptClick() {
btnAccept.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tb.addRow(new Object[]{"taza",txtName.getText()});
}
});
public static void main(String[] args) {
//Initilizer init = new Initilizer();
Runnable init = new Runnable() {
#Override
public void run() {
MyForm form = new MyForm();
form.setVisible(true);
}
};
SwingUtilities.invokeLater(init);
}
}
As you can see i call the addRow function but in never updates in the JTable, what am i missing? Thnx
You're creating two TableDemo objects -- one you add to the GUI, tablePanel, the other you add a row to, tb;
// ...
TableDemo tb = new TableDemo(); // TableDemo #1. Never displayed
private void initControls() {
// ...
TableDemo tablePanel = new TableDemo(); // TableDemo #2
// ...
// TableDemo #2 is here added to the GUI
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tablePanel,panel );
// ...
}
btnAccept.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// here you add a row to the non-displayed TableDemo #1
tb.addRow(new Object[]{"taza",txtName.getText()});
}
});
Solution: Don't do this (obviously)! Use only one TableDemo instance, display it and make changes to it. So get rid of the tablePanel variable and only use the tb variable.
Other problems:
You're using null layouts. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.

JList position resets to default whenever update occurs

list is to accept input from Action1 this works, however, whenever a new element is added to the list, the list's position moves back to the default top-middle position.
This also occurs when the frame is resized, so as a temporary fix I the line frame.setResizable(false) but I do not want that to be permanent.
How would I fix both of these issues?
import static java.lang.String.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class lists
{
static String newUrl;
static DefaultListModel<String> model = new DefaultListModel<String>();
static int listXCoord = 650;
static int listYCoord = 10;
public static void createGUI()
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(800,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel panel = new JPanel();
frame.add(panel);
JButton addurl = new JButton("Add URL");
panel.add(addurl);
addurl.addActionListener(new Action1());
JButton remurl = new JButton("Remove URL");
panel.add(remurl);
//model.addElement("one");
//model.addElement("two");
//model.addElement("three");
JList list = new JList<String>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
list.setLocation(listXCoord, listYCoord);
list.setBackground(new Color(186, 203, 250));
//list.setLocation(650, 10);
panel.add(list);
list.setSize(130, 540);
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
newUrl = JOptionPane.showInputDialog("Enter the URL to be Launched");
model.addElement(newUrl);
}
}
public static void main(String[] args)
{
createGUI();
}
}
Basically, you're fighting the layout manager (Flowlayout) and losing. When you add a new element to the JList, the container hierarchy is been revalidated which is causing the layout managers to re-layout the contents of their containers
The basic solution would be to use a different layout, but, JFrame uses a BorderLayout, so instead of adding the JList to the JPanel, you could simply add it to the EAST position of the frame instead
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Lists {
static String newUrl;
static DefaultListModel<String> model = new DefaultListModel<String>();
static int listXCoord = 650;
static int listYCoord = 10;
public static void createGUI() {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton addurl = new JButton("Add URL");
panel.add(addurl);
addurl.addActionListener(new Action1());
JButton remurl = new JButton("Remove URL");
panel.add(remurl);
//model.addElement("one");
//model.addElement("two");
//model.addElement("three");
JList list = new JList<String>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
list.setLocation(listXCoord, listYCoord);
list.setBackground(new Color(186, 203, 250));
//list.setLocation(650, 10);
frame.add(new JScrollPane(list), BorderLayout.EAST);
frame.setVisible(true);
}
static class Action1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
newUrl = JOptionPane.showInputDialog("Enter the URL to be Launched");
model.addElement(newUrl);
}
}
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();
}
createGUI();
}
});
}
}
See Laying Out Components Within a Container, How to Use BorderLayout and How to use FlowLayout for more details.
You should also be calling setVisible last, after all the components have been added to the frame, this reduces the possibilities that some of your components won't be displayed when you think they should be.
JList will also benefit from been contained within a JScrollPane. See How to Use Lists and How to Use Scroll Panes for more details

Java EventHandling

When I compile it show error in line 33 : Cannot find symbol.
I am calling jbtNew.addActionListener(listener), so why it's unable to find jbtNew in
(e.getSource() == jbtNew) in line 33.
from code
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AnonymousListenerDemo extends JFrame {
public AnonymousListenerDemo() {
// Create four buttons
JButton jbtNew = new JButton("New");
JButton jbtOpen = new JButton("Open");
JButton jbtSave = new JButton("Save");
JButton jbtPrint = new JButton("Print");
// Create a panel to hold buttons
JPanel panel = new JPanel();
panel.add(jbtNew);
panel.add(jbtOpen);
panel.add(jbtSave);
panel.add(jbtPrint);
add(panel);
// Create and register anonymous inner-class listener
AnonymousListenerDemo.ButtonListener listener = new AnonymousListenerDemo.ButtonListener();
jbtNew.addActionListener(listener);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbtNew) //Here it show the problem
{
System.out.println("Process New");
}
}
}
/** Main method */
public static void main(String[] args) {
JFrame frame = new AnonymousListenerDemo();
frame.setTitle("AnonymousListenerDemo");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
That's a local variable.
It doesn't exist outside the constructor.
You need to make a field in the class.
this could be work (in the form as you posted here) and #SLaks mentioned +1, with a few major changes
in the case that all methods will be placed into separated classes to use put/getClientProperty()
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AnonymousListenerDemo {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame("AnonymousListenerDemo");
// Create four buttons
private JButton jbtNew = new JButton("New");
private JButton jbtOpen = new JButton("Open");
private JButton jbtSave = new JButton("Save");
private JButton jbtPrint = new JButton("Print");
public AnonymousListenerDemo() {
JPanel panel = new JPanel();// Create a panel to hold buttons
panel.add(jbtNew);
panel.add(jbtOpen);
panel.add(jbtSave);
panel.add(jbtPrint);
// Create and register anonymous inner-class listener
jbtNew.addActionListener(new ButtonListener());
frame.add(panel);
//frame.setTitle("AnonymousListenerDemo");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbtNew) {
System.out.println("Process New");
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new AnonymousListenerDemo();
}
});
}
}

Adding a file via jFileChoser to a jList

As i am new to java swing, i am finding a little difficulty in integrating the JFileChooser with JList. My goal is to select a file from the dialog-box(JFileChooser) and click 'add' so that it gets added to the JList automatically and the same mechanism with 'remove'. I tried going through a few tutorials and a few hints but it dint work. It would be really great if any of you could help me with this step.
Thanks in advance..!!
package examples;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JSplitPane;
//import javax.swing.SwingConstants;
class SplitPane extends JFrame
{
private static final long serialVersionUID = 1L;
private JSplitPane splitPaneV;
private JSplitPane splitPaneH;
private JLayeredPane panel1;
private JPanel panel2;
private JPanel panel3;
private JButton add;
private JButton remove;
private JScrollBar scrollBar;
private JList list;
public SplitPane()
{
setTitle("AdditionalLoaderInformation");
setBackground(Color.blue);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
topPanel.setPreferredSize(new Dimension(700, 500));
getContentPane().add(topPanel);
// Create the panels
createPanel1();
createPanel2();
createPanel3();
// Create a splitter pane
splitPaneV = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
topPanel.add(splitPaneV, BorderLayout.CENTER);
splitPaneH = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPaneH.setLeftComponent(panel1);
splitPaneH.setRightComponent(panel2);
splitPaneV.setLeftComponent(splitPaneH);
splitPaneV.setRightComponent(panel3);
scrollBar = new JScrollBar();
scrollBar.setOrientation(JScrollBar.HORIZONTAL);
panel3.add(scrollBar, BorderLayout.SOUTH);
list = new JList();
panel3.add(list, BorderLayout.CENTER);
}
public void createPanel1()
{
panel1 = new JLayeredPane();
panel1.setLayout(new BorderLayout());
}
public void createPanel2()
{
panel2 = new JPanel();
add = new JButton("ADD");
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
************************************
}
});
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
panel2.add(add);
remove = new JButton("REMOVE");
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeActionPerformed(e);
}
private void removeActionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
panel2.add(remove);
}
public void createPanel3()
{
panel3 = new JPanel();
panel3.setLayout(new BorderLayout());
panel3.setPreferredSize(new Dimension(400, 100));
panel3.setMinimumSize(new Dimension(100, 50));
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(true);
//fileChooser.showOpenDialog(fileChooser);
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser .setDialogTitle("OPEN");
panel3.add(fileChooser, BorderLayout.NORTH);
//fileChooser.addActionListener(new ActionListener()
// {
// public void actionPerformed(ActionEvent e)
//{
// }
//});
}
public static void main(String args[]) {
// Create an instance of the test application
SplitPane mainFrame = new SplitPane();
mainFrame.pack();
mainFrame.setVisible(true);
}
}
When you get a new file name in your chooser's action listener, shown here, add it to (or remove it from) the list's models, as shown in this example.
Addendum: To display the file's content in the JList, you'll need to create a suitable renderer using one of the text components.
Read the JFileChooser tutorial
If the above step is not sufficient, take a look at the class javadoc of JFileChooser and note the APPROVE_OPTION and the getSelectedFile method. This should allow you to obtain the file
Read the JList tutorial
If the above step is not sufficient, take a look at the available API of JList and ListModel, and more in particular the default implementation DefaultListModel which contains add and remove methods

Categories