質問

I have two buttons to edit the font in a text. Bold button and Italic button, separately, they work fine but not togheter. How do I get my buttons to work togheter? (Bold+Italic)

final JToggleButton boldbuttonpage1 = new JToggleButton("");
        boldbuttonpage1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(boldbuttonpage1.isSelected()){
                    textpage1.setFont(new Font("Arial", Font.BOLD, 12));
                }
                else textpage1.setFont(new Font("Arial", Font.PLAIN, 12));
            }
        });
        boldbuttonpage1.setBounds(21, 32, 27, 23);
        gtapage1.add(boldbuttonpage1);

        final JToggleButton italicbuttonpage1 = new JToggleButton("");
        italicbuttonpage1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(italicbuttonpage1.isSelected()){
                    textpage1.setFont(new Font("Arial", Font.ITALIC, 12));
                }
                else textpage1.setFont(new Font("Arial", Font.PLAIN, 12));
            }
        });
        italicbuttonpage1.setBounds(21, 93, 27, 23);
        gtapage1.add(italicbuttonpage1);
役に立ちましたか?

解決

When you set the font with one button push, you over-write the previous font, negating any possible effect from a previous button press. Myself, I would have both ActionListeners (or ItemListeners) call the same method, one that checks the state of both buttons and sets the font correspondingly to the button values.

Also, as per my comment, get rid of the Eclipse tag and instead add a Swing tag to your question so it's not misleading anyone. Eclipse is just the tool you're using as an IDE and has no bearing on your question.

As an aside, you should not set bounds of components or use null layouts but rather will want to use proper layout managers.


Edit
You ask:

A method to check the state of the buttons? Can you elaborate that please?

You already know how to check the state of your buttons, with your isSelected() method call. Well rather than check only one button when a button is pressed, check both. In fact you can give both buttons the same ActionListener:

ActionListener actionListener = new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // check selected states of both button one and two and set font accordingly
    // you can use if (foo && bar) {...}
    // else if (foo) {...}
    // else if (bar) {...}
    // else {.. default...}
  }
};
button1.addActionListener(actionListener);
button2.addActionListener(actionListener);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top