problems in selecting the JComboBox items(in JMenu) Java Swing - java

Im having trouble in selecting the JCombox items here is a gif:
Gif that shows exactly what is the problem
here is code that you can test your own as asked by #UNKNOWN
i delete everything that no needed so you can test , i have no error in console;
the code works perfectly but the combo slection error is there
import javax.swing.*;
import java.awt.*;
public class ForTest extends JFrame {
private JTextArea txtArea= null;
private JComboBox cmbFontSize = null;
private JComboBox cmbFontFamily = null;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ForTest();
}
});
}
private ForTest(){
init();
}
public void init(){
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setTitle("FOR TEST");
this.setLocationRelativeTo(null);
this.setSize(850,500);
txtArea= new JTextArea();
txtArea.setSize(830,470);
JScrollPane panScrollable = new JScrollPane(txtArea);
panScrollable.setSize(840,480);
this.add(panScrollable, BorderLayout.CENTER);
JMenuBar jmbTop= new JMenuBar();
JMenu modifica = new JMenu("Modifica");
modifica.setFont(new Font("arial",Font.PLAIN,15));
JMenu fontSettings= new JMenu("Font Settings");
JMenuItem cmbFam= new JMenuItem("FONT FAMILY");
cmbFontSize = new JComboBox();
cmbFontFamily = new JComboBox();
cmbFam.add(cmbFontFamily);
fontSettings.add(cmbFam);
// fontSettings.add(cmbFontSize);
//fontSettings.add(cmbFontFamily);
modifica.add(fontSettings);
jmbTop.add(modifica);
loadFontFamily();
loadFontSize();
this.setJMenuBar(jmbTop);
this.setVisible(true);
}
private void loadFontFamily() {
String fonts[] =
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for ( int i = 0; i < fonts.length; i++ )
{
cmbFontFamily.addItem(fonts[i]);
}
}
private void loadFontSize() {
for (int i= 10; i<50;i++){
cmbFontSize.addItem(i);
}
}
}
the code is simple but cant understand why i cannot select the items
thanks in advance:)

You should wrap the JComboBox inside a JMenuItem object and then add the to the JMenu one. That would do the trick

Related

Java - Why i can't see my list in JFrame?

I can't see my list under the MenuBar, it should show me a list (playing cards)
What i should do ?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Joc extends JFrame{
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("Optiuni");
JMenuItem mi1 = new JMenuItem("Amesteca");
JMenuItem mi2 = new JMenuItem ("Inchide");
DefaultListModel<Card> model = new DefaultListModel<Card>();
JList<Card> list = new JList<Card>();
JScrollPane jsp = new JScrollPane(list);
Deck d = new Deck ();
public Joc() {
super("Joc");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setJMenuBar(mb);
add(jsp);
mb.add(m1);
m1.add(mi1);
m1.add(mi2);
ArrayList<Card> carti = d.getCards();
for (Card c: carti) {
model.addElement(c);
}
mi1.addActionListener (
new ActionListener() {
public void actionPerformed (ActionEvent ev) {
d.amesteca();
ArrayList<Card> carti = d.getCards();
model.clear();
for (Card c: carti) {
model.addElement(c);
}
}
}
);
mi2.addActionListener (
new ActionListener() {
public void actionPerformed (ActionEvent ev) {
System.exit(0);
}
}
);
setSize(500,500);
setVisible(true);
}
public static void main (String [] args) {
new Joc();
}
}
Can anyone help me with this problem ? I'm new to java and coding , i just play around with the code... but i want results
I don't see where you add the model to the list, so the JList has an empty model with nothing to display
Create the JList using the model:
DefaultListModel<Card> model = new DefaultListModel<Card>();
//JList<Card> list = new JList<Card>();
JList<Card> list = new JList<Card>(model);
Also, you should be using:
list.setVisibleRowCount(...);
This will allow the JList to determine its own preferred size and you can use frame.pack() instead of frame.setSize(...).

Java Radio Buttons within Radio Buttons

I have learnt to create a menu with radio buttons using java, but I want to know how to make radio buttons WITHIN radio buttons. The real problem is that I have finally created the radio buttons 'within' a radio button by displaying a new menu with a new group of buttons, but whenever I click on these new radio buttons, nothing happens. It is as if the buttons are not being listened to. Here is my code (example, but still the same idea):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestRadioButtons extends JPanel implements ActionListener
{
private String test = "Test Button 1";
private String random = "RANDOM";
private String test2 = "Button to Click";
private String random2 = "RANDOM MK. 2";
private static boolean menu = false;
public TestRadioButtons()
{
super(new BorderLayout());
//creates first set of radio buttons
JRadioButton testButton = new JRadioButton(test);
testButton.setMnemonic(KeyEvent.VK_T);
testButton.setActionCommand(test);
JRadioButton randomButton = new JRadioButton(random);
randomButton.setMnemonic(KeyEvent.VK_R);
randomButton.setActionCommand(random);
//groups the first set of buttons
ButtonGroup group1 = new ButtonGroup();
group1.add(testButton);
group1.add(randomButton);
//register listener for first radio buttons
testButton.addActionListener(this);
randomButton.addActionListener(this);
//put first radio buttons into a column in a panel
JPanel radioPanel1 = new JPanel(new GridLayout(0, 1));
radioPanel1.add(testButton);
radioPanel1.add(randomButton);
//set first menu border
add(radioPanel1, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,250));
//I also have it so that if the a boolean value equals true, the following menu appears:
if (menu == true)
{
JRadioButton test2Button = new JRadioButton(test2);
test2Button.setMnemonic(KeyEvent.VK_A);
test2Button.setActionCommand(test2);
JRadioButton random2Button = new JRadioButton(random2);
random2Button.setMnemonic(KeyEvent.VK_B);
random2Button.setActionCommand(random2);
ButtonGroup group2 = new ButtonGroup();
group2.add(test2Button);
group2.add(random2Button);
test2Button.addActionListener(this);
random2Button.addActionListener(this);
JPanel radioPanel2 = new JPanel(new GridLayout(0, 1));
radioPanel2.add(test2Button);
radioPanel2.add(random2Button);
add(radioPanel2, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,250));
}
}
public static void menu2()
{
JFrame innerMenu = new JFrame();
innerMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent innerComponent = new TestRadioButtons();
innerComponent.setOpaque(true);
innerMenu.setContentPane(innerComponent);
innerMenu.pack();
innerMenu.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (test.equals(e.getActionCommand()))
{
menu = true;
menu2();
if (test2.equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(null, "This is just a TEST!");
}
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Radio Button Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent component = new TestRadioButtons();
component.setOpaque(true);
frame.setContentPane(component);
frame.pack();
frame.setVisible(true);
}
public static void main (String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If anyone is able to help me (as well as fix up my code in the part where I create the new menu), I would be grateful.
Just a } problem
Change your public void actionPerformed(ActionEvent e) like this
public void actionPerformed(ActionEvent e)
{
if (test.equals(e.getActionCommand()))
{
menu = true;
menu2();
}
if (test2.equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(null, "This is just a TEST!");
}
}

Nothing appears when I try to create a JFrame. (JButtons, JMenuBar etc.)

I'm working on a pathfinder program which uses GUI. I tried to run the program before I added some stuff and it showed everything fine. But after working on it some more it stopped showing the buttons and the menu bar.
Here is the code. Some variable names are in Swedish as well, but I hope that it won't be an issue. (Please take in mind that the program is far from finished.)
Thank you in advance!
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class Pathfinder extends JFrame {
JButton hittaVäg, visaFörbindelse, nyPlats, nyFörbindelse, ändraFörbindelse;
JMenuBar menyBar;
JMenuItem ny, avsluta, hittaVägMeny, visaFörbindelseMeny, nyPlatsMeny, nyFörbindelseMeny, ändraFörbindelseMeny;
String str = System.getProperty("user.dir");
JFileChooser jfc;
BildPanel Bild = null;
Pathfinder(){
super("PathFinder");
setLayout(new BorderLayout());
setSize(590, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
jfc = new JFileChooser(".");
JPanel norra = new JPanel();
add(norra, "norra");
JButton hittaVäg = new JButton("Hitta väg");
JButton visaFörbindelse = new JButton("Visa förbindelse");
JButton nyPlats = new JButton("Ny plats");
JButton nyFörbindelse = new JButton("Ny förbindelse");
JButton ändraFörbindelse = new JButton("Ändra förbindelse");
norra.add(hittaVäg);
norra.add(visaFörbindelse);
norra.add(nyPlats);
norra.add(nyFörbindelse);
norra.add(ändraFörbindelse);
hittaVäg.addActionListener(new HittaLyss());
visaFörbindelse.addActionListener(new VisaLyss());
nyPlats.addActionListener(new NyPlatsLyss());
nyFörbindelse.addActionListener(new NyFörbindelseLyss());
ändraFörbindelse.addActionListener(new NyFörbindelseLyss());
JMenuBar menyBar = new JMenuBar();
setJMenuBar(menyBar);
JMenu arkivMeny = new JMenu("Arkiv");
JMenu operationerMeny = new JMenu("Operationer");
menyBar.add(arkivMeny);
menyBar.add(operationerMeny);
JMenuItem ny = new JMenuItem("Ny");
JMenuItem avsluta = new JMenuItem("Avsluta");
arkivMeny.add(ny);
arkivMeny.add(avsluta);
ny.addActionListener(new NyLyss());
avsluta.addActionListener(new AvslutaLyss());
JMenuItem hittaVägMeny = new JMenuItem("Hitta väg");
JMenuItem visaFörbindelseMeny = new JMenuItem("Visa förbindelse");
JMenuItem nyPlatsMeny = new JMenuItem("Ny plats");
JMenuItem nyFörbindelseMeny = new JMenuItem("Ny förbindelse");
JMenuItem ändraFörbindelseMeny = new JMenuItem("Ändra förbindelse");
operationerMeny.add(hittaVägMeny);
operationerMeny.add(visaFörbindelseMeny);
operationerMeny.add(nyPlatsMeny);
operationerMeny.add(nyFörbindelseMeny);
operationerMeny.add(ändraFörbindelseMeny);
hittaVäg.addActionListener(new HittaLyss());
visaFörbindelse.addActionListener(new VisaLyss());
nyPlats.addActionListener(new NyPlatsLyss());
nyFörbindelse.addActionListener(new NyFörbindelseLyss());
ändraFörbindelse.addActionListener(new ÄndraFörbindelseLyss());
}
class HittaLyss implements ActionListener{
public void actionPerformed(ActionEvent ave){
}
}
class VisaLyss implements ActionListener{
public void actionPerformed(ActionEvent ave){
}
}
class NyPlatsLyss implements ActionListener{
public void actionPerformed(ActionEvent ave){
}
}
class NyFörbindelseLyss implements ActionListener{
public void actionPerformed(ActionEvent ave){
}
}
class ÄndraFörbindelseLyss implements ActionListener{
public void actionPerformed(ActionEvent ave){
}
}
class NyLyss implements ActionListener{
public void actionPerformed(ActionEvent ave){
int svar = jfc.showOpenDialog(Pathfinder.this);
if (svar == JFileChooser.APPROVE_OPTION){
File f = jfc.getSelectedFile();
String filnamn = f.getAbsolutePath();
if (Bild != null)
remove(Bild);
Bild = new BildPanel(filnamn);
add(Bild, BorderLayout.CENTER);
validate();
repaint();
pack();
}
}
}
class AvslutaLyss implements ActionListener{
public void actionPerformed(ActionEvent ave){
}
}
public static void main (String[] args){
new Pathfinder();
}
}
One of the issues is IllegalArgumentException at line
add(norra, "norra");
The layout of the frame's content pane is set to BorderLayout, but this layout does not understand "norra" constraint. See How to Use BorderLayout for more details and examples.
Also, you should call setVisible once all the components are added and initialized.
Call setVisible(true) on the JFrame after adding all components, not before. The order should be:
Add components
Call pack() on the JFrame
Then call setVisible(true) on the JFrame.
You need to first add the components and then call setVisible(true).
So the order matters here. Try it, see if it helps.

JFrame not showing up

I have one class called TabBuilder which I use to create the interface of my application, but I'm going through a weird problem. If I try to run the code as it's below it will draw the mainScreen but if I request the SearchScreen from the BarMenu it doesn't show up. If I try to execute only SearchScreen by itself (calling its builder) within the public static void main (String[] args) MainString it wont show up too. but If go to the request event and tip TabBuilder tb = new TabBuilder(); tb.requestTab();the screen will show up as it should be. So, what might be wrong? Thanks in advance
MainScreen:
public class MainScreen{
public MainScreen()
{
TabBuilder tb = new TabBuilder();
tb.mainTab();
}
}
SearchScreen:
public class SearchScreen{
public void SearchScreen(){
TabBuilder tb = new TabBuilder();
tb.requestTab();
}
}
TabBuilder:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TabBuilder implements ActionListener {
JTabbedPane tabbedPane = new JTabbedPane();
JMenuItem close, request;
protected JTextField txtrequest = new JTextField();
JButton btrequest = new JButton();
protected JFrame requestFrame = new JFrame();
public void TabBuilder(){
}
public void mainTab(){
JMenuBar bar;
JMenu file, register;
JFrame mainFrame = new JFrame();
bar= new JMenuBar();
file= new JMenu("File");
register= new JMenu("Request");
close= new JMenuItem("Close");
close.addActionListener(this);
request= new JMenuItem("Request Query");
request.addActionListener(this);
bar.add(file);
bar.add(register);
file.add(close);
register.add(request);
mainFrame.setExtendedState(mainFrame.getExtendedState() | mainFrame.MAXIMIZED_BOTH); // Maximized Window or setSize(getMaximumSize());
mainFrame.setTitle("SHST");
mainFrame.setJMenuBar(bar);
mainFrame.setDefaultCloseOperation(0);
mainFrame.setVisible(true);
WindowListener J=new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
};
mainFrame.addWindowListener(J);
}
public void requestTab(){
JLabel lbrequest;
JPanel requestPane;
btrequest= new JButton("request");
lbrequest= new JLabel("Type Keywords in english to be requested below:");
txtrequest= new JTextField();
requestPane=new JPanel();
requestPane.setBackground(Color.gray);
requestPane.add(lbrequest);
requestPane.add(txtrequest);
requestPane.add(btrequest);
requestPane.setLayout(new GridLayout(3,3));
btrequest.setEnabled(true);
requestFrame.add(requestPane);
requestFrame.setTitle("SHST");
requestFrame.setSize(400, 400);
requestFrame.setVisible(true);
requestFrame.setDefaultCloseOperation(1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==request){
TabBuilder tb = new TabBuilder();
tb.requestTab();
}
}
public static void main (String[] args){
MainScreen m = new MainScreen();
}
}
The constructor of SearchScreen was settled as void. That caused nothing to return as object when calling the constructor. Newbie failure but simple solution.

How do I build a JMenu dynamically?

I am trying to build a JMenu dynamically right when clicking in it (I'm only getting an empty menu), below is my code.
final JMenu JMWindows = new JMenu("Opened Windows");
JMWindows.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(JInternalFrame ji : desktop.getAllFrames())
{
JMWindows.add(ji.getTitle());
}
}
});
I've realized that the actionperformed is never called, the JMenu is inside a JMenuBar. What could be the problem ?
You add ActionListener to JMenu this cannot be done for JMenu use MenuListener and set it via JMenu#addMenuListener(..)
Also you need to call revalidate() and repaint() on JMenu instance after adding/removing components from it or the changes will not be reflected (we could also call this on the containers instance i.e JMenuBar or JFrame, but we know only 1 specific JMenu will change so no need IMO).
Please watch your variable naming schemes JMWindow should be jmWindow/jMWindow variables always begin with no caps and the 1st letter of every new word thereafter gets capitalized (besides for constants and enums).
Here is an example using MenuListener:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class Test {
private JDesktopPane jdpDesktop;
private static int openFrameCount = 0;
final JFrame frame = new JFrame("JInternalFrame Usage Demo");
public Test() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// A specialized layered pane to be used with JInternalFrames
jdpDesktop = new JDesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
};
for (int i = 0; i < 3; i++) {
createFrame(); // Create first window
}
frame.setContentPane(jdpDesktop);
frame.setJMenuBar(createMenuBar());
// Make dragging faster by setting drag mode to Outline
jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");
frame.pack();
frame.setVisible(true);
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Frame");
menu.setMnemonic(KeyEvent.VK_N);
JMenuItem menuItem = new JMenuItem("New IFrame");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createFrame();
}
});
menu.add(menuItem);
menuBar.add(menu);
final JMenu jmWindows = new JMenu("Opened Windows");
jmWindows.addMenuListener(new MenuListener() {
#Override
public void menuSelected(MenuEvent me) {
jmWindows.removeAll();//remove previous opened window jmenuitems
for (JInternalFrame ji : jdpDesktop.getAllFrames()) {
JMenuItem menuItem = new JMenuItem(ji.getTitle());
jmWindows.add(menuItem);
}
jmWindows.revalidate();
jmWindows.repaint();
jmWindows.doClick();
}
#Override
public void menuDeselected(MenuEvent me) {
}
#Override
public void menuCanceled(MenuEvent me) {
}
});
menuBar.add(jmWindows);
return menuBar;
}
protected void createFrame() {
Test.MyInternalFrame frame = new Test.MyInternalFrame();
frame.setVisible(true);
// Every JInternalFrame must be added to content pane using JDesktopPane
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame() {
super("IFrame #" + (++openFrameCount), true, // resizable
true, // closable
true, // maximizable
true);// iconifiable
setSize(300, 300);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition
* openFrameCount);
}
}
}
You need to repaint and or validate your frame after adding or removing something.
you can use the methods repaint() and validate() in your JFrame for this
You missed defining a JMenuItem.
final JMenu JMWindows = new JMenu("Opened Windows");
JMWindows.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(JInternalFrame ji : desktop.getAllFrames())
{
JMenuItem menuItem = new JMenuItem(ji.getTitle());
JMWindows.add(menuItem);
}
}
});

Categories

Resources