JavaFX MenuBar on Pane on Borderpane (top) flickers - java

I'm writing a program in Java and I'm using JavaFX for the GUI,
using the MVC way.
The structure of the view I'm talking about is as follow:
The reason for this structure is because I want to keep my code clean & clear.
Inside the TopPane I want only a menuBar.
I've added this as follow:
public class TopPane extends Pane {
private MenuBar menuBar;
public TopPane() {
initNodes();
layoutNodes();
}
private void initNodes() {
Menu[] menus = new Menu[3];
menus[0] = new Menu("File");
menus[1] = new Menu("Options");
menus[2] = new Menu("Help");
MenuItem[] menuItemsFile = new MenuItem[4];
menuItemsFile[0] = new MenuItem("New game");
menuItemsFile[1] = new MenuItem("Save game");
menuItemsFile[2] = new MenuItem("Load game");
menuItemsFile[3] = new MenuItem("Exit");
menus[0].getItems().addAll(menuItemsFile);
MenuItem options = new MenuItem("Options");
menus[1].getItems().add(options);
MenuItem help = new MenuItem("Help");
menus[2].getItems().add(help);
menuBar = new MenuBar();
menuBar.getMenus().addAll(menus);
}
private void layoutNodes() {
menuBar.setMinWidth(Double.MAX_VALUE);
menuBar.useSystemMenuBarProperty().set(true);
getChildren().add(menuBar);
}
public MenuBar getMenuBar() {
return menuBar;
}
}
In gameview I do the following:
public class GameView extends BorderPane {
private TopPane topPane;
private LeftPane leftPane;
private PlayerView playerView; //centerpane
private RightPane rightPane;
public GameView() {
initNodes();
layoutNodes();
}
private void initNodes() {
topPane = new TopPane();
leftPane = new LeftPane();
playerView = new PlayerView();
rightPane = new RightPane();
}
private void layoutNodes() {
this.setStyle("-fx-background-color: #2a2a2a");
this.setTop(topPane);
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
double screenHeight = screenBounds.getHeight();
int topMargin = 25;
if (screenHeight >= 1050) {
topMargin = 150;
}
System.out.println(screenHeight);
setMargin(leftPane, new Insets(topMargin, 0, 0, 50));
this.setLeft(leftPane);
setMargin(playerView, new Insets(0, 0, 0, 25));
this.setCenter(playerView);
this.setRight(rightPane);
}
}
It shows the menubar succesfully but the problem is that when I click one of the menus, the menuItems just flickers and dissapear immediatly. I think this is because I extend topPane with Pane. But without it couldn't work obviously, and if I extend from menuBar (and delete the variable Menubar), my rightPane & PlayerView won't be added to my GameView for some mysterious dark reason I couldn't figure out (yet) :)
Anybody able to help me?
Thanks in advance!

Thanks to DVarga :
Remove menuBar.setMinWidth(Double.MAX_VALUE);
Extend StackPane instead of Pane
This works perfectly!

Related

Java AWT TextField Size Issue

Currently, I'm working on java Frame. I have an issue with making the size of the textfield bigger since I can't really see what I typed. I used command+a, then copied and pasted what I typed in another textarea, and it showed as I typed. However, I want to make my textfield bigger. Please let me know what I can do.
This is main class.
public static void main(String[]args)
{
Frame f = new Frame("This is practice title bar!");
f.addWindowListener(new ExitListener());
f.setLayout(new GridLayout(2,1,20,20));
Panel myPanel = new Panel();
myPanel.setLayout(new GridLayout(3,3,20,20));
Label lName = new Label("Name");
lName.setAlignment(Label.CENTER);
myPanel.add(lName);
Label lAge = new Label("Age");
lAge.setAlignment(Label.CENTER);
myPanel.add(lAge);
Label lWeight = new Label("Weight");
lWeight.setAlignment(Label.CENTER);
myPanel.add(lWeight);
TextField tfName = new TextField();
myPanel.add(tfName);
TextField tfAge = new TextField();
myPanel.add(tfAge);
kgPanel kp = new kgPanel();
myPanel.add(kp);
Label empty = new Label("");
myPanel.add(empty);
Button addBtn = new Button("Add");
addBtn.addActionListener(new UserActionListener());
myPanel.add(addBtn);
Label empty2 = new Label("");
myPanel.add(empty2);
f.add(myPanel);
TextArea ta = new TextArea();
f.add(ta);
f.pack();
f.setSize(500,500);
f.setVisible(true);
}
This is kgPanel class.
import java.awt.*;
public class kgPanel extends Panel
{
public TextField weightTf = null;
public Label measurement = null;
public kgPanel()
{
tfAndKg();
}
public kgPanel(LayoutManager layout)
{
super(layout);
tfAndKg();
}
public void tfAndKg()
{
weightTf = new TextField();
add(weightTf);
measurement = new Label("kg");
add(measurement);
}
}
And the image is a result. Please let me know which part should I edit to make my textfield bigger.
Thank you
I tried to use
weightTf.setSize()
and
weightTf.setBounds()
but didn't work.
Please help me.

How to change selected text with a JSpinner?

I'm following a course and, in theory, I'm already able to handle POO, JFrame, JPanel, Event and Layout. I'm in the middle of the Swing components and I'm trying to extend one of the practices made by the teacher.
The objective is to modify a selected text through some JItems. The teacher used JItem to modify the size of the selected text in the same way he did with the formatting and style. In my case, I would like to use a JSpinner to control only the selected text. I don't know if I can do this.
I am enclosing the code of what I have done.
public class ProcesadorDeTextos {
public static void main(String[] args) {
// TODO Auto-generated method stub
MarcoProcesador marquito = new MarcoProcesador();
marquito.setDefaultCloseOperation(3);
}
}
class MarcoProcesador extends JFrame{
MarcoProcesador(){
setTitle("El Palabra");
setBounds(300, 200, 800, 450);
add(new LaminaProcesador());
setVisible(true);
}
}
class LaminaProcesador extends JPanel{
public LaminaProcesador() {
setLayout(new BorderLayout());
//-----2 principle components
campoTexto = new JTextPane();
barraTools = new JMenuBar();
//Scroll
scrollTexto = new JScrollPane(campoTexto);
//---------------toolbar/barraTools-------------
fuente = new JMenu("Fuente");
estilo = new JMenu("Estilo");
configuraMenu("Arial", "fuente","Arial",1,1);
configuraMenu("Courier", "fuente","Courier",1,1);
configuraMenu("Verdana", "fuente","Verdana",1,1);
configuraMenu("Negrita", "estilo","",Font.BOLD,1);
configuraMenu("Cursiva", "estilo","", Font.ITALIC,1);
configuraMenu("", "","", 1,1);
barraTools.add(fuente);
barraTools.add(estilo);
//-------------------Adding principal components----------------
JPanel Herramientas = new JPanel();
Herramientas.add(barraTools);
add(scrollTexto, BorderLayout.CENTER);
add(Herramientas, BorderLayout.NORTH);
}
private void configuraMenu(String rotulo, String menu, String tipoLetra, int estilos, int tamagnos) {
JMenuItem elemMenu = new JMenuItem(rotulo);
if(menu == "fuente") {
fuente.add(elemMenu);
elemMenu.addActionListener(new StyledEditorKit.FontFamilyAction("cambiaLetra", tipoLetra));
// StyledEditorKit.FontFamilyAction ya tiene el método ActionPerformed desarrollado
}
else if(menu == "estilo") {
estilo.add(elemMenu);
if(estilos == Font.BOLD) {
elemMenu.addActionListener(new StyledEditorKit.BoldAction());
}
else elemMenu.addActionListener(new StyledEditorKit.ItalicAction());
}
else {
JSpinner size = new JSpinner(new SpinnerNumberModel(12, 8, 24, 2));
size.setPreferredSize(new Dimension (45,2));
//size.addChangeListener(new StyledEditorKit.FontSizeAction("cambiaTamaño", ));
barraTools.add(size);
}
}
private JTextPane campoTexto;
private JScrollPane scrollTexto;
private JMenuBar barraTools;
private JMenu fuente, estilo;
}

Java AWT Menu and TextArea not showing

I can't manage to display menu and textarea with awt (see the code below). What could be the problem? I think I'm doing everything correctly, but could it be caused by the fact, that Frame object isn't instantiated while I'm trying to add TextArea and Menu to it?
BTW. I know AWT is obsolete, but I want to gain some knowledge of it before moving onto Swing or JavaFX. Also point me to any mistakes I've made while creating this post (as it's the first of mine).
class Notepad extends Frame{
Notepad(String name){
super(name);
TextArea text = new TextArea(" ", 10, 30, SCROLLBARS_VERTICAL_ONLY);
add(text);
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
Menu file = new Menu("File");
MenuItem New, Open, Save, Close;
file.add(New = new MenuItem("New"));
file.add(Open = new MenuItem("Open"));
file.add(Save = new MenuItem("Save"));
file.add(Close = new MenuItem("Close"));
mbar.add(file);
Menu edit = new Menu("Edit");
MenuItem Find, Replace, ReplaceAll;
edit.add(Find = new MenuItem("Find"));
edit.add(Replace = new MenuItem("Replace"));
edit.add(ReplaceAll = new MenuItem("ReplaceAll"));
mbar.add(edit);
MenuHandler menuHandler = new MenuHandler(this);
New.addActionListener(menuHandler);
Open.addActionListener(menuHandler);
Save.addActionListener(menuHandler);
Close.addActionListener(menuHandler);
Find.addActionListener(menuHandler);
Replace.addActionListener(menuHandler);
ReplaceAll.addActionListener(menuHandler);
MyWindowAdapter w_listener = new MyWindowAdapter(this);
addWindowListener(w_listener);
//this.setVisible(true);
}
public void paint(Graphics g){
}
public static void main(String[] foo){
Notepad notepad = new Notepad("Notepad");
notepad.setSize(500, 500);
notepad.setVisible(true);
}
}
class MyWindowAdapter extends WindowAdapter{
Notepad notepad;
MyWindowAdapter(Notepad notepadframe){
this.notepad = notepad;
}
public void windowClosing(WindowEvent we){
notepad.setVisible(false);
System.exit(0);
}
}
class MenuHandler implements ActionListener{
Notepad notepad;
public MenuHandler(Notepad notepad){
this.notepad = notepad;
}
public void actionPerformed(ActionEvent ae){
String arg = ae.getActionCommand();
if(arg.equals("New")){
}
}
}

JButton doesn't work at all after i dispose existing frame and sets the new frame(re instantiate another frame)

I made a calculator and to increase its functionality and simplicity i made three frames which support simple , scientific and conversion calculator
calculator works perfect till i use it once but when i change my calculator type from simple to scientific and scientific to conversion and then again to simple calculator , program doesn't do anything at all , jbutton doesn't perform any action even actionPerformed is getting called i checked that by putting println statement in method actionPerformed.
i instantiate my three frames in constructor and i'd made three methods each for calculator type to instantiating and adding buttons and other stuff to JPanels and adding panels to JFrame
//Constructor
public Calculator()
{
//instantiating buttons
buttons = new JButton[15];
optionButtons = new JButton[5];
scientificOptionButtons = new JButton[20];
constantButtons = new JButton[5];
//instantiating calculatorFrames
simpleCalculatorFrame = new JFrame("Calculator");
scientificCalculatorFrame = new JFrame("Scientific Calculator");
convertCalculatorFrame = new JFrame("Conversion Calculator");
} // end of the constructor
when i choose calculator type from my JMenuItems i dispose the active frame and call other calculatortype methods for creating and adding stuff to panels and setting up frame like
//if statements inside method actionPerformed to check which type of calculator should run
if(event.getSource() == scientificMenuItem)
{
if(simpleCalculatorFrame.isActive())
{
simpleCalculatorFrame.dispose();
scientificCalculatorBuilder();
}
else if(convertCalculatorFrame.isActive())
{
convertCalculatorFrame.dispose();
scientificCalculatorBuilder();
}
}
else if(event.getSource() == simpleMenuItem)
{
if(scientificCalculatorFrame.isActive())
{
scientificCalculatorFrame.dispose();
simpleCalculatorBuilder();
}
else if(convertCalculatorFrame.isActive())
{
convertCalculatorFrame.dispose();
simpleCalculatorBuilder();
}
}
else if(event.getSource() == convertMenuItem)
{
if(simpleCalculatorFrame.isActive())
{
simpleCalculatorFrame.dispose();
convertCalculatorBuilder();
}
else if(scientificCalculatorFrame.isActive())
{
scientificCalculatorFrame.dispose();
convertCalculatorBuilder();
}
}
else if(event.getSource() == exitMenuItem)
{
System.exit(0);
}
everything looks fine just not getting where the problem is
here's code of my methods which instantiates the components
public void simpleCalculatorBuilder()
{
//instantiating menuBar , fileMenu and menuItems and adding functionality
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
scientificMenuItem = new JMenuItem("Scientific Calculator");
convertMenuItem = new JMenuItem("Conversion Calculator");
convertMenuItem.addActionListener(handler);
scientificMenuItem.addActionListener(handler);
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(handler);
menuBar.add(fileMenu);
fileMenu.add(scientificMenuItem);
fileMenu.add(convertMenuItem);
fileMenu.add(exitMenuItem);
//instantiating and adding textField appearing at the top of calculator to show ongoing processes and results
myField = new JTextField();
myField.setPreferredSize(new Dimension(this.getWidth() , 40));
myField.setEditable(false);
simpleCalculatorFrame.add(myField , BorderLayout.NORTH);
//instantiating panels to hold buttons
buttonsPanel = new JPanel(new GridLayout(5 , 3 , 3 , 6));
optionButtonsPanel = new JPanel(new GridLayout(5, 1 , 3 , 3));
//loop to add buttons to panel , adding eventListeners to buttons , setting background color of buttons
for(int i = 0 ; i<buttons.length ; i++)
{
buttons[i] = new JButton(buttonTitles[i]);
buttons[i].setBackground(Color.BLACK);
buttons[i].setForeground(Color.WHITE);
buttons[i].addActionListener(handler);
buttons[i].addMouseListener(handler);
buttonsPanel.add(buttons[i]);
if(i<5)
{
optionButtons[i] = new JButton(optionButtonTitles[i]);
optionButtons[i].setBackground(Color.BLACK);
optionButtons[i].setForeground(Color.WHITE);
optionButtons[i].addActionListener(handler);
optionButtons[i].addMouseListener(handler);
optionButtonsPanel.add(optionButtons[i]);
}
}
//setting background color of panels
buttonsPanel.setBackground(Color.DARK_GRAY);
optionButtonsPanel.setBackground(Color.DARK_GRAY);
//adding items and panels to the frame and setting the simpleCalculatorFrame
simpleCalculatorFrame.setJMenuBar(menuBar);
simpleCalculatorFrame.add(buttonsPanel , BorderLayout.CENTER);
simpleCalculatorFrame.add(optionButtonsPanel , BorderLayout.EAST);
simpleCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
simpleCalculatorFrame.setSize(240 , 270);
simpleCalculatorFrame.setLocationRelativeTo(null);
simpleCalculatorFrame.setVisible(true);
simpleCalculatorFrame.setResizable(false);
} // end of simple calculator builder
public void scientificCalculatorBuilder()
{
//instantiating menuBar , fileMenu and menuItems and adding functionality
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
simpleMenuItem = new JMenuItem("Simple Calculator");
simpleMenuItem.addActionListener(handler);
convertMenuItem = new JMenuItem("Conversion Calculator");
convertMenuItem.addActionListener(handler);
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(handler);
menuBar.add(fileMenu);
fileMenu.add(simpleMenuItem);
fileMenu.add(convertMenuItem);
fileMenu.add(exitMenuItem);
//instantiating and adding textField appearing at the top of calculator to show ongoing processes and results
myField = new JTextField();
myField.setPreferredSize(new Dimension(this.getWidth() , 40));
myField.setEditable(false);
scientificCalculatorFrame.add(myField , BorderLayout.NORTH);
//instantiating panels to hold buttons
buttonsPanel = new JPanel(new GridLayout(5 , 3 , 3 , 6));
optionButtonsPanel = new JPanel(new GridLayout(5, 1 , 3 , 3));
scientificOptionButtonsPanel = new JPanel(new GridLayout(5 , 4 , 3 , 3));
constantButtonsPanel = new JPanel(new GridLayout(5, 1 , 3 , 3));
scientificPanelManager = new JPanel(new GridLayout(1 , 2));
//loop to add buttons to panel , adding eventListeners to buttons , setting background color of buttons
for(int i = 0 ; i<scientificOptionButtons.length ; i++)
{
if(i<5)
{
optionButtons[i] = new JButton(optionButtonTitles[i]);
optionButtons[i].setBackground(Color.BLACK);
optionButtons[i].setForeground(Color.WHITE);
optionButtons[i].addActionListener(handler);
optionButtons[i].addMouseListener(handler);
optionButtonsPanel.add(optionButtons[i]);
constantButtons[i] = new JButton(constantButtonTitles[i]);
constantButtons[i].setBackground(Color.BLACK);
constantButtons[i].setForeground(Color.WHITE);
constantButtons[i].addActionListener(handler);
constantButtons[i].addMouseListener(handler);
constantButtonsPanel.add(constantButtons[i]);
}
if(i<15)
{
buttons[i] = new JButton(buttonTitles[i]);
buttons[i].setBackground(Color.BLACK);
buttons[i].setForeground(Color.WHITE);
buttons[i].addActionListener(handler);
buttons[i].addMouseListener(handler);
buttonsPanel.add(buttons[i]);
}
scientificOptionButtons[i] = new JButton(scientificOptionButtonTitles[i]);
scientificOptionButtons[i].setBackground(Color.BLACK);
scientificOptionButtons[i].setForeground(Color.WHITE);
scientificOptionButtons[i].addActionListener(handler);
scientificOptionButtons[i].addMouseListener(handler);
scientificOptionButtonsPanel.add(scientificOptionButtons[i]);
}// end of for loop
//setting background color of panels
buttonsPanel.setBackground(Color.DARK_GRAY);
optionButtonsPanel.setBackground(Color.DARK_GRAY);
scientificOptionButtonsPanel.setBackground(Color.DARK_GRAY);
constantButtonsPanel.setBackground(Color.DARK_GRAY);
scientificPanelManager.add(scientificOptionButtonsPanel);
scientificPanelManager.add(buttonsPanel);
scientificCalculatorFrame.setJMenuBar(menuBar);
scientificCalculatorFrame.add(constantButtonsPanel , BorderLayout.WEST);
scientificCalculatorFrame.add(optionButtonsPanel , BorderLayout.EAST);
scientificCalculatorFrame.add(scientificPanelManager , BorderLayout.CENTER);
scientificCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scientificCalculatorFrame.setSize(580 , 300);
scientificCalculatorFrame.setLocationRelativeTo(null);
scientificCalculatorFrame.setVisible(true);
scientificCalculatorFrame.setResizable(false);
} // end of scientificCalculatorBuilder
//method which starts convertCalculatorFrame and initializes frame needs
public void convertCalculatorBuilder()
{
convertCalculatorTopPanel = new JPanel(new GridLayout(2 , 1 , 0 , 4));
convertCalculatorCenterPanel = new JPanel(new GridLayout(2 , 2 , 5 , 3));
convertCalculatorEastPanel = new JPanel(new GridLayout(2 , 1 ,1 , 3));
convertCalculatorSouthPanel = new JPanel(new GridLayout(1 , 2 , 5 , 2));
//instantiating menuBar , fileMenu and menuItems and adding functionality
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
simpleMenuItem = new JMenuItem("Simple Calculator");
simpleMenuItem.addActionListener(handler);
scientificMenuItem = new JMenuItem("Scientific Calculator");
scientificMenuItem.addActionListener(handler);
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(handler);
menuBar.add(fileMenu);
fileMenu.add(simpleMenuItem);
fileMenu.add(scientificMenuItem);
fileMenu.add(exitMenuItem);
typeConvertCalculatorComboBox = new JComboBox<String>();
typeConvertCalculatorComboBox.setBackground(Color.BLACK);
typeConvertCalculatorComboBox.setForeground(Color.WHITE);
typeConvertCalculatorComboBox.setMaximumRowCount(3);
typeConvertCalculatorComboBox.addItem("Choose type of conversion");
typeConvertCalculatorComboBox.addItem("Distance Conversion");
typeConvertCalculatorComboBox.addItem("Memory Conversion");
typeConvertCalculatorComboBox.addItem("Temperature Conversion");
typeConvertCalculatorComboBox.addItem("Mass Conversion");
typeConvertCalculatorComboBox.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(typeConvertCalculatorComboBox.getSelectedItem() == "Distance Conversion")
{
fromConvertCalculatorComboBox.setEnabled(true);
toConvertCalculatorComboBox.setEnabled(true);
fromConvertCalculatorComboBox.removeAllItems();
fromConvertCalculatorComboBox.setMaximumRowCount(3);
fromConvertCalculatorComboBox.addItem("Centimeter(s)");
fromConvertCalculatorComboBox.addItem("Meter(s)");
fromConvertCalculatorComboBox.addItem("Kilometer(s)");
fromConvertCalculatorComboBox.addItem("Mile(s)");
toConvertCalculatorComboBox.removeAllItems();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.addItem("Centimeter(s)");
toConvertCalculatorComboBox.addItem("Meter(s)");
toConvertCalculatorComboBox.addItem("Kilometer(s)");
toConvertCalculatorComboBox.addItem("Mile(s)");
}
else if(typeConvertCalculatorComboBox.getSelectedItem() == "Memory Conversion")
{
fromConvertCalculatorComboBox.setEnabled(true);
toConvertCalculatorComboBox.setEnabled(true);
fromConvertCalculatorComboBox.removeAllItems();
fromConvertCalculatorComboBox.setMaximumRowCount(3);
fromConvertCalculatorComboBox.addItem("Kilobyte(s)");
fromConvertCalculatorComboBox.addItem("Megabyte(s)");
fromConvertCalculatorComboBox.addItem("Gigabyte(s)");
fromConvertCalculatorComboBox.addItem("Terabyte(s)");
toConvertCalculatorComboBox.removeAllItems();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.addItem("Kilobyte(s)");
toConvertCalculatorComboBox.addItem("Megabyte(s)");
toConvertCalculatorComboBox.addItem("Gigabyte(s)");
toConvertCalculatorComboBox.addItem("Terabyte(s)");
}
else if(typeConvertCalculatorComboBox.getSelectedItem() == "Temperature Conversion")
{
fromConvertCalculatorComboBox.setEnabled(true);
toConvertCalculatorComboBox.setEnabled(true);
fromConvertCalculatorComboBox.removeAllItems();
fromConvertCalculatorComboBox.addItem("Centigrade");
fromConvertCalculatorComboBox.addItem("Fahrenheit");
fromConvertCalculatorComboBox.addItem("Kelvin");
toConvertCalculatorComboBox.removeAllItems();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.addItem("Centigrade");
toConvertCalculatorComboBox.addItem("Fahrenheit");
toConvertCalculatorComboBox.addItem("Kelvin");
}
else if(typeConvertCalculatorComboBox.getSelectedItem() == "Mass Conversion")
{
fromConvertCalculatorComboBox.setEnabled(true);
toConvertCalculatorComboBox.setEnabled(true);
fromConvertCalculatorComboBox.removeAllItems();
fromConvertCalculatorComboBox.setMaximumRowCount(3);
fromConvertCalculatorComboBox.addItem("Milligram(s)");
fromConvertCalculatorComboBox.addItem("Pound(s) (lbs)");
fromConvertCalculatorComboBox.addItem("Kilogram(s)");
toConvertCalculatorComboBox.removeAllItems();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.addItem("Milligram(s)");
toConvertCalculatorComboBox.addItem("Pound(s) (lbs)");
toConvertCalculatorComboBox.addItem("Kilogram(s)");
}
}
}
);
fromConvertCalculatorComboBox = new JComboBox<String>();
fromConvertCalculatorComboBox.setMaximumRowCount(3);
fromConvertCalculatorComboBox.setBackground(Color.BLACK);
fromConvertCalculatorComboBox.setForeground(Color.WHITE);
fromConvertCalculatorComboBox.setEnabled(false);
toConvertCalculatorComboBox = new JComboBox<String>();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.setBackground(Color.BLACK);
toConvertCalculatorComboBox.setForeground(Color.WHITE);
toConvertCalculatorComboBox.setEnabled(false);
topConvertCalculatorLabel = new JLabel("What type of conversion you want ?");
topConvertCalculatorLabel.setForeground(Color.WHITE);
fromConvertCalculatorLabel = new JLabel("From");
fromConvertCalculatorLabel.setForeground(Color.WHITE);
toConvertCalculatorLabel = new JLabel("To");
toConvertCalculatorLabel.setForeground(Color.WHITE);
fromConvertCalculatorField = new JTextField();
fromConvertCalculatorField.setPreferredSize(new Dimension(120 , 2));
fromConvertCalculatorField.addActionListener(convertHandler);
ansConvertCalculatorField = new JTextField();
ansConvertCalculatorField.setEditable(false);
convertButton = new JButton("Convert");
convertButton.setBackground(Color.BLACK);
convertButton.setForeground(Color.WHITE);
convertButton.addMouseListener(handler);
convertButton.addActionListener(convertHandler);
convertCalculatorFrame.setJMenuBar(menuBar);
//adding components to panel and adding panels to frame
{
convertCalculatorTopPanel.add(topConvertCalculatorLabel);
convertCalculatorTopPanel.add(typeConvertCalculatorComboBox);
convertCalculatorTopPanel.setBackground(Color.DARK_GRAY);
convertCalculatorFrame.add(convertCalculatorTopPanel , BorderLayout.NORTH);
convertCalculatorCenterPanel.add(fromConvertCalculatorLabel);
convertCalculatorCenterPanel.add(fromConvertCalculatorComboBox);
convertCalculatorCenterPanel.add(toConvertCalculatorLabel);
convertCalculatorCenterPanel.add(toConvertCalculatorComboBox);
convertCalculatorCenterPanel.setBackground(Color.DARK_GRAY);
convertCalculatorFrame.add(convertCalculatorCenterPanel , BorderLayout.CENTER);
convertCalculatorEastPanel.add(fromConvertCalculatorField);
convertCalculatorEastPanel.setBackground(Color.DARK_GRAY);
convertCalculatorFrame.add(convertCalculatorEastPanel , BorderLayout.EAST);
convertCalculatorSouthPanel.add(convertButton);
convertCalculatorSouthPanel.add(ansConvertCalculatorField);
convertCalculatorSouthPanel.setBackground(Color.DARK_GRAY);
convertCalculatorFrame.add(convertCalculatorSouthPanel , BorderLayout.SOUTH);
convertCalculatorFrame.getContentPane().validate();
convertCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
convertCalculatorFrame.setSize(390 , 200);
convertCalculatorFrame.setLocationRelativeTo(null);
convertCalculatorFrame.setVisible(true);
convertCalculatorFrame.setResizable(false);
}
}//end of convertCalculatorBuilder
i dont have much experience in programming hope you people won't mind helping
here's an MCVE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
Practice application = new Practice();
application.forFrame1();
}
}
class Practice extends JPanel
{
Handler handler = new Handler();
private JButton[] buttons;
private JButton[] moreButtons;
private JMenuBar menuBar;
private JMenu myMenu;
private JMenuItem firstItem;
private JMenuItem secondItem;
private JFrame frame1;
private JFrame frame2;
private JPanel panel1;
private JPanel panel2;
public Practice()
{
buttons = new JButton[3];
moreButtons = new JButton[5];
frame1 = new JFrame();
frame2 = new JFrame();
}
public void forFrame1()
{
menuBar = new JMenuBar();
myMenu = new JMenu("menu");
secondItem = new JMenuItem("goto 2nd frame");
secondItem.addActionListener(handler);
menuBar.add(myMenu);
myMenu.add(secondItem);
frame1.setJMenuBar(menuBar);
panel1 = new JPanel(new GridLayout(3 , 1));
for(int i = 0 ; i<buttons.length ; i++)
{
buttons[i] = new JButton(""+ i);
buttons[i].addActionListener(handler);
panel1.add(buttons[i]);
}
frame1.add(panel1);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(200 , 200);
frame1.setVisible(true);
}
public void forFrame2()
{
menuBar = new JMenuBar();
myMenu = new JMenu("menu");
firstItem = new JMenuItem("goto 1st frame");
firstItem.addActionListener(handler);
menuBar.add(myMenu);
myMenu.add(firstItem);
frame2.setJMenuBar(menuBar);
panel2 = new JPanel(new GridLayout(1 , 5));
for(int i = 0 ; i<moreButtons.length ; i++)
{
moreButtons[i] = new JButton(""+ i);
moreButtons[i].addActionListener(handler);
panel2.add(moreButtons[i]);
}
frame2.add(panel2);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setSize(200 , 200);
frame2.setVisible(true);
}
private class Handler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == firstItem)
{
frame2.dispose();
forFrame1();
}
else if(event.getSource() == secondItem)
{
frame1.dispose();
forFrame2();
}
for(int i = 0 ; i< moreButtons.length ; i++)
{
if(i<buttons.length)
{
if(event.getSource() == buttons[i])
JOptionPane.showMessageDialog(null, "frame1 component working");
}
if(event.getSource() == moreButtons[i])
JOptionPane.showMessageDialog(null, "frame2 components working");
}
}
}
}
try using component after changing frame by choosing menuItem
I'm not going to go through all that code without an mcve, but your symptoms tell me the overall problem and the solution: you're re-building an already created JFrame, re-stuffing it with components, without removing old components, without unhooking old listeners, and the components then don't work. This suggests that something in the process of re-building an already built GUI is mucking up your functionality, and if so, the solution is to simply not do this. If you absolutely need to swap JFrames (a very annoying GUI design from a user's perspective by the way), then only create your GUI objects once, but display them multiple times if needed. In other words, call your builder methods just once, perhaps in the constructor, and in your button's ActionListener, don't call the builder methods but rather only the .setVisible(true) and .setVisible(false)
The bug that is causing your error is that you're adding components to an already filled JFrame and are not packing it, and so the old buttons are shown and are pressed, but their references don't match that of the new buttons. To see this for yourself, add one line to each of the forFrame1() and forFrame2() methods:
frame1.getContentPane().removeAll(); // ****** add this *****
frame1.add(panel1);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(200, 200);
frame1.setVisible(true);
By removing all the old components, you all the new ones to be displayed and to function, and your code will work.
Having said this, I still feel that your design is off in several ways:
Myself, I'd swap JPanels to achieve the desired GUI change, but I wouldn't use a CardLayout since I'd want the container that holds the swapping JPanels to change sizes when the JPanel held has a different preferredSize. This means removing all components, adding new components, and re-packing the GUI.
If you must swap windows, then simply swap visibility, and don't re-create your windows as you're doing.
Other unrelated issues
Let the layout managers and components size themselves by not setting any sizes and by packing the GUI after creation.
I think you should use JFrame.setVisible(false) instead of JFrame.dispose()

JMenuPopup not accurte?

Image of the problem:
http://gyazo.com/56c4f7f5fc10805695fc80de567b92c5.png
private JButton settingsButton = new JButton("Settings");
private JPopupMenu settings = new JPopupMenu();
private JMenuItem accounts = new JMenuItem("Accounts");
settings.add(accounts);
settingsButton.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
settings.show(e.getComponent(), 0, 0);
}
});
So as you have seen on the image, I don't think this is any accurate. Is there any (better) method to get it on a the right spot?
I have clicked on the JButton: "Settings" and it should popup just a tad down it.
You are better off using a JMenuBar and then adding JMenus with JMenuItems, there is no point on reinventing the wheel:
JMenuBar menubar = new JMenuBar();
JMenu settings = new JMenu("Settings");
JMenuItem accounts = new JMenuItem("Accounts");
settings.add(accounts);
menubar.add(settings);
myFrame.setJMenuBar(menubar);

Categories