how to open frame from another frame Java Swing - java

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.

Related

Unable to add button to frame GUI

I am trying to add a simple JButton to a JPanel in my program. The problem is when I run the problem, I do not see any button at all.
This is my code:
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GuiStopwatch {
public GuiStopwatch() {
JPanel panel = new JPanel();
JButton Startbtn = new JButton("START");
panel.add(Startbtn);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Stopwatch");
frame.setSize(600, 600);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
}
May I know what did I do wrong and how do I fix this?
You are not adding the panel to the frame at any point.
EDIT
Here is the code you would need if you wanted it in a separate method:
import javax.swing.*;
import java.awt.*;
public class GuiStopwatch {
private static void stopwatch(JFrame frame) {
JPanel panel = new JPanel();
JButton Startbtn = new JButton("START");
panel.add(Startbtn);
frame.add(panel);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Stopwatch");
stopwatch(frame);
frame.setSize(600, 600);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
}
You could swap things, create everything you need for your frame on the constructor, what makes the code more organized and also you can use it in other Classes, putting on main method will limit what you can do and makes the code not organized
See here an example:
public GuiStopwatch() {
setTitle("Stopwatch");
setSize(600, 600);
// Create JButton and JPanel
JButton button = new JButton("START");
JPanel panel = new JPanel();
panel.add(button);
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
GuiStopwatch guistopwatch = new GuiStopwatch();
}

Resizing BasicArrowButton

I'm trying to get a BasicArrowButton component to resize and can't get it to work for the life of me. The following code is a much simpler version of the problem, but still demonstrates what I'm trying to do. The button is in a JPanel with the panel's layout set to FlowLayout. It needs to resize while still remaining in the panel with the same layout. Thanks in advance, and sorry for bad formatting:
Main class:
package PackageMain;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Main {
public static JFrame frame = new JFrame("Window");
public static PanelOne p1;
public static PanelTwo p2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 800, 600);
p1 = new PanelOne();
frame.setVisible(true);
} catch(Exception e){
}
}
});
}
}
Second Class:
package PackageMain;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicArrowButton;
public class PanelOne{
public PanelOne(){
FlowLayout fl = new FlowLayout();
BasicArrowButton b1 = new BasicArrowButton(BasicArrowButton.WEST);
JPanel p1 = new JPanel();
p1.add(b1);
p1.setLayout(fl);
b1.setPreferredSize(new Dimension(100, 100)); //DOESN'T WORK!
Main.frame.add(p1);
}
}
The problem is that the class BasicArrowButton overrides the method getPreferredSize(). So you either need to use layout, which does not honor this method, or provide your own implementation for this method.
First proposal:
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicArrowButton;
public class BasicArrowButtonTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frm = new JFrame("Test arrow button");
JPanel p = new JPanel(new GridLayout(1, 1));
p.setPreferredSize(new Dimension(100, 100));
p.add(new BasicArrowButton(BasicArrowButton.WEST));
frm.add(p);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
});
}
}
Second proposal:
package org.swingsamples.label;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicArrowButton;
public class BasicArrowButtonTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frm = new JFrame("Test arrow button");
JPanel p = new JPanel(new FlowLayout());
BasicArrowButton btn = new BasicArrowButton(BasicArrowButton.WEST) {
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
p.add(btn);
frm.add(p);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
});
}
}

Placing the JPanel in JScrollPane [duplicate]

I've got a probelm with my swing ui lately. Everything works fine,untill i trigger a tooltip from a JButton.After that moving the mouse over the rest of the ui is causing weird artifacts and glitching.
Bugged:
I can't show the whole code because its too much but here im initialising the button :
GridBagConstraints bottompane_gbc = new GridBagConstraints();
toggleTorConnectionButton = new JButton();
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
toggleTorConnectionButton.setIcon(new ImageIcon(ResourceHandler.Menueicon3_1));
toggleTorConnectionButton.setMinimumSize(new Dimension(removeFinishedDownloads.getMinimumSize().width, toggleTorConnectionButton.getIcon().getIconHeight()+5));
toggleTorConnectionButton.addActionListener(); // unimportant
bottompane_gbc.gridy = 1;
bottompane_gbc.fill = GridBagConstraints.BOTH;
bottompane_gbc.insets = new Insets(0,15,10,5);
bottompane.add(ToggleTorConnectionButton,bottompane_gbc);
this.add(bottompane,BorderLayout.PAGE_END);
If anybody needs more information to help me pls feel free to ask.Im kind of desperated. XD
EDIT:
After some tinkering im guessing that the problem is related to swing and my use of it.Currently im using alot of Eventlisteners (is this bad?), that might slow down the awt thread ?
Here is a brief extract from HPROF:
http://www.pastebucket.com/96444
EDIT 2:
I was able to recreate the error in a handy and simple example. When you move over the button,wait for the tooltip and then over the ui.You will see ghosting :(.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class Main_frame {
public static void main(String[] args) {
new Main_frame();
}
public Main_frame() {
JFrame frame = new JFrame("LOL");
frame.setFocusable(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 500));
frame.setLocationRelativeTo(null);
Download_window download_window = new Download_window();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Download", null, download_window, "Main Download Window.");
for (int i = 0; i < 5; i++) {
JPanel pane = new JPanel();
Dimension dim = new Dimension(370, 60);
pane.setPreferredSize(dim);
pane.setMaximumSize(dim);
pane.setBackground(Color.blue);
pane.setMinimumSize(dim);
download_window.jobpanel.add(pane);
}
download_window.jobpanel.repaint();
download_window.jobpanel.revalidate();
frame.add(tabbedPane);
frame.setVisible(true);
}
public class Download_window extends JPanel {
JPanel jobpanel;
public Download_window() {
this.setLayout(new BorderLayout());
jobpanel = new JPanel();
jobpanel.setLayout(new BoxLayout(jobpanel, BoxLayout.Y_AXIS));
JPanel bottompane = new JPanel();
bottompane.setPreferredSize(new Dimension(385, 40));
JButton toggleTorConnectionButton = new JButton();
toggleTorConnectionButton.setPreferredSize(new Dimension(100, 50));
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
bottompane.add(toggleTorConnectionButton);
this.add(bottompane, BorderLayout.PAGE_END);
JScrollPane jobScrollPane = new JScrollPane(jobpanel);
jobScrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(jobScrollPane, BorderLayout.CENTER);
}
}
}
Edit 3: Concerning trashgods ideas, I used the EventDispatchThread, I modified the setter to override the getter for size and i crossed out incompatibility by using trashgods code and it was working fine.... So where is the actual difference?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class Main_frame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Main_frame();
}
});
}
public Main_frame() {
JFrame frame = new JFrame("LOL");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 500));
Download_window download_window = new Download_window();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Download", null, download_window, "Main Download Window.");
frame.add(tabbedPane);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class Download_window extends JPanel {
JPanel jobpanel;
public Download_window() {
this.setLayout(new BorderLayout());
jobpanel = new JPanel();
jobpanel.setLayout(new BoxLayout(jobpanel, BoxLayout.Y_AXIS));
for (int i = 0; i < 5; i++) {
JPanel pane = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(370, 60);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(370, 60);
}
#Override
public Dimension getMinimumSize() {
return new Dimension(370, 60);
}
};
pane.setBackground(Color.blue);
jobpanel.add(pane);
}
JPanel bottompane = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(385, 40);
}
};
JButton toggleTorConnectionButton = new JButton("Button"){
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 30);
}
};
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
bottompane.add(toggleTorConnectionButton);
this.add(bottompane, BorderLayout.PAGE_END);
JScrollPane jobScrollPane = new JScrollPane(jobpanel);
jobScrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(jobScrollPane, BorderLayout.CENTER);
}
}
}
Could anyone please verify that strange behavior himself? You just need to copy&paste the code from above in Edit3.
Your code exhibits none of the glitches shown above when run on my platform.
Verify that you have no painting problems e.g. neglecting super.paintComponent() as discussed here.
Verify that you have no driver incompatibilities, as discussed here.
Construct and modify all GUI objects on the event dispatch thread.
Don't use set[Preferred|Maximum|Minimum]Size() when you really mean to override get[Preferred|Maximum|Minimum]Size(), as discussed here. The example below overrides getPreferredSize() on the scroll pane, but you can implement Scrollable, as discussed here.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
/** #see https://stackoverflow.com/a/34319260/230513 */
public class MainFrame {
private static final int H = 64;
public static void main(String[] args) {
EventQueue.invokeLater(() -> new MainFrame());
}
public MainFrame() {
JFrame frame = new JFrame("LOL");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
for (int i = 0; i < 8; i++) {
panel.add(new DownloadPanel());
}
JScrollPane jsp = new JScrollPane(panel) {
#Override
public Dimension getPreferredSize() {
return new Dimension(6 * H, 4 * H);
}
};
tabbedPane.addTab("Download", null, jsp, "Main Download Window.");
tabbedPane.addTab("Options", null, null, "Options");
frame.add(tabbedPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class DownloadPanel extends JPanel {
JPanel jobPanel = new JPanel();
public DownloadPanel() {
this.setLayout(new BorderLayout());
this.setBackground(Color.lightGray);
JProgressBar jpb = new JProgressBar();
jpb.setIndeterminate(true);
this.add(jpb);
JPanel buttonPane = new JPanel();
JButton toggleTorConnectionButton = new JButton("Button");
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
buttonPane.add(toggleTorConnectionButton);
this.add(buttonPane, BorderLayout.WEST);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(4 * H, H);
}
}
}

Why getcontentpane() is undefined?

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.

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();
}
});
}
}

Categories