I am trying to create an application with several tabbed panes, and to keep the code manageable, I wanted to have the content for these panes in separate classes, in separate .java files.
I have 3 files currently
(i) TestLayout.java
package testlayout;
public class TestLayout
{
public static void main(String[] args)
{
MainFrame mainFrameObject = new MainFrame();
mainFrameObject.displayMainFrame();
}
}
(ii) MainFrame.java
package testlayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
public class MainFrame
{
JFrame masterFrame = new JFrame("JAVA 1.1");
JTabbedPane tabbedPane = new JTabbedPane();
public void displayMainFrame()
{
masterFrame.setSize(1000, 600);
masterFrame.setVisible(true);
masterFrame.setResizable(false);
masterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
masterFrame.add(tabbedPane);
DisplayReadMe drmObj = new DisplayReadMe();
drmObj.showReadMe();
//showReadMe();
}
/*
public void showReadMe()
{
JPanel panelReadMe = new JPanel(new GridLayout(10,1,8,8));
panelReadMe.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
tabbedPane.addTab("Read Me", null, panelReadMe, "First Tab");
String testreadMeTestMessage = "This is a test message";
JLabel testreadMeLabel = new JLabel(testreadMeTestMessage, SwingConstants.LEFT);
testreadMeLabel.setBorder(BorderFactory.createLineBorder(Color.orange,3));
panelReadMe.add(testreadMeLabel);
}
*/
}
and
(iii) DisplayReadMe.java
package testlayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class DisplayReadMe extends MainFrame
{
public DisplayReadMe()
{
}
public void showReadMe()
{
System.out.println("method showReadMe begins");
JPanel panelReadMe = new JPanel(new GridLayout(10,1,8,8));
panelReadMe.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
tabbedPane.addTab("Read Me", null, panelReadMe, "First Tab");
String testreadMeTestMessage = "This is a test message";
JLabel testreadMeLabel = new JLabel(testreadMeTestMessage, SwingConstants.LEFT);
testreadMeLabel.setBorder(BorderFactory.createLineBorder(Color.orange,3));
panelReadMe.add(testreadMeLabel);
System.out.println("method showReadMe ends");
}
}
My query is, when I uncomment the //showReadMe(); and showReadMe method in MainFrame, it works. The tab is added to the JFrame and the test message shows in the box.
But should the
DisplayReadMe drmObj = new DisplayReadMe();
drmObj.showReadMe();
code, not do the same thing? Am I not calling the showReadMe method from the DisplayReadMe class, akin to showReadMe().
I have tried revalidate, repaint and threading and nothing seems to call the method and show the tab and message ?
Any guidance would be gratefully appreciated
Many Thanks
PG
The method is actually working, but the tabbedPane instance in drmObj is different with respect to the JTabbedPane class member in MainFrame. Try to add tabbedPane as a parameter in showReadMe() and refer to that instance whenever adding elements. It should work.
public void showReadMe(JTabbedPane tabbedPane);
...
drmObj.showReadMe(this.tabbedPane);
Hope it helps!
you may not have duplicated method with same parameters, check if you have another showReadMe method who expects nothing as parameter.
if you make an overwrite of the showReadMe, remember that it will make showReadMe of the main class, then will make showReadMe inherited since it cannot go more up.
i donno if i explained it well at all.
Related
I've been fiddling with TabbedPanes, and I wish to be able to use a method in another class to set which tab is selected.
However, when attempting to do this, I am provided with two errors.
First, it tells me that the parameter 'name' that I have provided the method in the second class has 'private access in Component'
error: name has private access in Component
TabbedPanes.name.setSelectedIndex(0);
Second, it tells me that it cannot find the symbol for the method I wish to call from within the second class' custom method.
error: cannot find symbol
TabbedPanes.name.setSelectedIndex(0);
^
symbol: method setSelectedIndex(int)
location: variable name of type String
My first class, TabbedPanes, can be found below:
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.BoxLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class TabbedPanes extends JFrame implements ActionListener
{
JTabbedPane tabs;
JPanel pan1, pan2, pan3, pan4, pan5, pan6, pan7, pan8;
JFrame frame;
JScrollPane scroll1, scroll2, scroll3, scroll4, scroll5, scroll6, scroll7, scroll8;
public void Tabs()
{
tabs = new JTabbedPane();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pan1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
JScrollPane scroll1 = new JScrollPane(pan1);
scroll1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pan2 = new JPanel();
pan3 = new JPanel();
pan4 = new JPanel();
pan5 = new JPanel();
pan6 = new JPanel();
pan7 = new JPanel();
pan8 = new JPanel();
JScrollPane scroll8 = new JScrollPane(pan8);
scroll8.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll8.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
Container pane = frame.getContentPane();
pane.add(tabs);
tabs.add("Mon", scroll1);
tabs.add("Tue", pan2);
tabs.add("Wed", pan3);
tabs.add("Thu", pan4);
tabs.add("Fri", pan5);
tabs.add("Sat", pan6);
tabs.add("Sun", pan7);
tabs.add("Notes", scroll8);
Dates datesObject = new Dates();
datesObject.tabOnStartup("tabs");
frame.setSize(400,400);
frame.setVisible(true);
}
public static void main(String[] args)
{
TabbedPanes TrueTabs = new TabbedPanes();
TrueTabs.Tabs();
}
}
The second class, Dates, can be found below:
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.BoxLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Dates
{
public void tabOnStartup(String name)
{
TabbedPanes.name.setSelectedIndex(0);
}
Any help will be greatly appreciated, and I hope my code is clean enough to read well.
If I got you right, you have to change the variable JTabbedPane tabs in class TabbedPanes to static:
static JTabbedPane tabs;
Also in class Dates you have to use
TabbedPanes.tabs.setSelectedIndex(0);
instead of
TabbedPanes.name.setSelectedIndex(0);
It seems that you have not implemented a method in class TabbedPanes :
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
If you are using IDE like Eclipse, NetBeans, etc. you should've received an error message like
- The type TabbedPanes must implement the inherited abstract method
ActionListener.actionPerformed(ActionEvent)
After these ammendments the result is:
I am just trying to use the class Box (Java API) using Eclipse Neon. When I import javax.swing.Box, the class seems not to exist anymore.
If I call the function like this:
Box myBox = Box.createHorizontalBox();
Eclipse shows an error: "The method createHorizontalBox() is undefined for the type Box"
Is class Box (and functions) not included in javax.swing? Any idea what is wrong?
Ok I was trying to do that inside a class called "Box", so I just changed the name of the class and all worked find.
Hope to be helpful to anybody else
Yes, it is still.
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class MainClass {
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box rowOne = Box.createHorizontalBox();
rowOne.add(new JLabel("Username"));
rowOne.add(new JTextField());
Box rowTwo = Box.createHorizontalBox();
rowTwo.add(new JLabel("Password"));
rowTwo.add(new JPasswordField());
f.add(rowOne, BorderLayout.NORTH);
f.add(rowTwo, BorderLayout.SOUTH);
f.setSize(300, 200);
f.setVisible(true);
}
}
I am going through thenewboston's tutorials and I have an unexpected error. I have tried to do everything that Eclipse suggest, but can't figure it out where the problem is.
this is my Main Class
import javax.swing.JFrame;
class Main {
public static void main(String args[]) {
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);
}
}
and this is GUI Class
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Gui extends JFrame {
private JButton reg;
private JButton custom;
public Gui(){
super("The title");
setLayout(new FlowLayout());
reg = new JButton("Regular Button");
add(reg);
Icon b = new ImageIcon(getClass().getResource("b.png"));
Icon a = new ImageIcon(getClass().getResource("a.png"));
custom = new JButton("Custom", b);
custom.setRolloverIcon(a);
add(custom);
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
}
Thanks brothers for helping me out!
You've posted a couple of different stacktraces with the error on different line numbers but the code seems to have moved around. The error itself is talking about a NullPointerException in a constructor for ImageIcon. Not really anything to do with the JButton so the tags are misleading.
Basically you're looking up an image location of b.png and a.png. If these two files don't exist then you'll get a runtime exception like you have. The quick fix is to add these two images to the project so they are found.
A more robust solution would be to handle the exception and either output a more meaningful error or just carry on without the icon on the gui.
I made a sample code to start one project just refactoring another one.
This the refactored one:
package com.sh.st;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingConstants;
public class Main extends JFrame implements ActionListener {
/**
*
*/
JMenuBar bar;
JMenu file, register;
JMenuItem close, search;
ImageIcon figure1= new ImageIcon("C:/Users/Victor/Downloads/Untitled.jpg");
//ImageIcon figure2= new ImageIcon("C:/Victor Rocha/carroicon.jpg");
JLabel Ibimagem1,Ibimagem2;
/**
*
*/
public Main()
{
bar= new JMenuBar();
file= new JMenu("file");
register= new JMenu("register");
register.setMnemonic(KeyEvent.VK_R);
file.setMnemonic(KeyEvent.VK_F);
close= new JMenuItem("Close");
close.addActionListener(this);
search= new JMenuItem("Search");
search.addActionListener(this);
Ibimagem1= new JLabel(figure1, JLabel.CENTER);
Ibimagem1.setVerticalTextPosition(SwingConstants.CENTER);
bar.add(file);
bar.add(register);
file.add(close);
register.add(search);
//register.add(carro);
//register.add(cliente);
//register.add(funcionario);
getContentPane().add(Ibimagem1);
setSize(800,600);
setTitle("SHST");
setJMenuBar(bar);
setDefaultCloseOperation(0);
//setIconImage(figure2.getImage());
WindowListener J=new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
};
addWindowListener(J);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
Search s= new Search();
s.setVisible(true);
}
}
}
This is the original one:
package com.professordelphi.locadora;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingConstants;
public class Principal extends JFrame implements ActionListener {
JMenuBar barra;
JMenu arquivo, cadastro;
JMenuItem fechar, cliente, funcionario, carro;
ImageIcon figura1= new ImageIcon("C:/Victor Rocha/carro.jpg");
ImageIcon figura2= new ImageIcon("C:/Victor Rocha/carroicon.jpg");
JLabel Ibimagem1,Ibimagem2;
public Principal()
{
barra= new JMenuBar();
arquivo= new JMenu("Arquivo");
cadastro= new JMenu("Cadastro");
cadastro.setMnemonic(KeyEvent.VK_C);
arquivo.setMnemonic(KeyEvent.VK_A);
fechar= new JMenuItem("Fechar");
fechar.addActionListener(this);
carro= new JMenuItem("Carro");
carro.addActionListener(this);
cliente= new JMenuItem("Cliente");
cliente.addActionListener(this);
funcionario= new JMenuItem("Funcionario");
funcionario.addActionListener(this);
Ibimagem1= new JLabel(figura1, JLabel.CENTER);
Ibimagem1.setVerticalTextPosition(SwingConstants.CENTER);
barra.add(arquivo);
barra.add(cadastro);
arquivo.add(fechar);
cadastro.add(carro);
cadastro.add(cliente);
cadastro.add(funcionario);
getContentPane().add(Ibimagem1);
setSize(800,600);
setTitle("Sistema de Cadastro");
setJMenuBar(barra);
setDefaultCloseOperation(0);
setIconImage(figura2.getImage());
WindowListener J=new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
};
addWindowListener(J);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==fechar){
System.exit(0);
}
if(e.getSource()==carro){
Carro k = new Carro();
k.setVisible(true);
}
if(e.getSource()==cliente){
Cliente c = new Cliente();
c.setVisible(true);
}
if(e.getSource()==funcionario){
Funcionario f= new Funcionario();
f.setVisible(true);
}
}
}
The thing is, the original e building and the refactored is not. The error I receive from the refactored is that "Selection does not contain a main type". I saw a lot of posts regarding this theme but none of them solve my problem. Here is one little list of the things I've tried;
Source: Editor does not contain a main type
clean your workspace and rebuild your Project.
make sure you add your source folder in the project properties -> java build path -> source.
close your project and reopen it.
Trying to run as a Java Application with Eclipse, anyone has suggestions of what should I do?
You dont have a main function defined in the class. The main function is the function that will be called when you run the file.
Try adding
public static void main(String [] args)
{
}
and create and show an object of your JFrame in the main method.
Right click on your project ->Properties -> Java Build Path -> Source -> Add Folder
Now Select the src folder and click on OK
You should define a main method in your class (either one) with the following signature:
public static void main(String args[])
This method is the start point of program.
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingConstants;
public class Main extends JFrame implements ActionListener {
public static void main(String args[]){
// from here the program execution starts
}
....
your other code
.....
}
The entry point for Java programs is the main method.
Does your class contain main method like below ?
public static void main(String[] args) {
//Code
}
If you do not have this, your program will not run.
Why is it that my code is not showing the image that I inserted? there's no compilation error or Syntax error but why is it like that?
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
public class FirstUI extends JFrame{
private JLabel firstlabel;
private JLabel secondLabel;
private JLabel pie;
public FirstUI(){
super("Tittle");
setLayout(new FlowLayout());
firstlabel = new JLabel("Hello World");
firstlabel.setToolTipText("Hello World");
String path = "pie.png";
Icon pie = new ImageIcon(path);
secondLabel = new JLabel("Text with icon",pie,SwingConstants.LEFT);
add(secondLabel);
add(firstlabel);
}
}
main class
import javax.swing.JFrame;
public class FirstUiTest {
public static void main(String[] args){
FirstUI MyUI = new FirstUI();
MyUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyUI.setSize(320,280);
MyUI.setVisible(true);
}
}
if the "pie.png" is in the same Path of FirstUI.class try to use:
Icon pie = new ImageIcon(ImageIO.read( FirstUI.class.getResourceAsStream( "pie.png" ) ) );
I tried this exact code, and it worked. It looks like pie.png cannot be found. If you're using eclipse, put it in the project root (The same folder that has /bin and /src). Otherwise, put it in the same directory where you run the java command from.